foundationdb-rs icon indicating copy to clipboard operation
foundationdb-rs copied to clipboard

Subspace as a const

Open Defman opened this issue 5 years ago • 4 comments

Would it be possible to change Supsace such that you are able to initialize it as a const? ie.

const SPACE: &Subspace = &Subspace::from(&"space");

I'm far from an expert, more like a beginner; but from what I'm aware only tuple structs are able to be consts and no allocation is allowed. Since it should be easy to convert any static value into a byte array at compile time.

Defman avatar Feb 18 '20 15:02 Defman

pack would also have to be a const fn.

Defman avatar Feb 18 '20 15:02 Defman

Rust doesn't support const fn for complex expressions. pack is far too complex to be marked const fn. There is work in progress to support for expressions, even allocations, but it's far from done and even further away from stable.

The only way to make Subspace "const" right now would be to change it's internals to support a &'static T variant and lazily pack T when necessary. Either that or change Vec<u8> to Cow<'static, [u8]>, and provided a prepacked const fn cstor.

I'm open to suggestion, feel free to provide a PR, even WIP if you need guidance so we can discuss on a more concrete ground.

An example of your use case might be great too.

Speedy37 avatar Feb 18 '20 20:02 Speedy37

This is definitely an enhancement/ergonomic request. It would improve performance slightly, due to the serialization of any type to byte array would be done at compile time.


fn myspace() -> Subspace {
    Subspace::from(&"myspace");
}

Would become

const MYSPACE: &Subspace  = &Subspace::from(&"myspace");

lazy_static

Defman avatar Feb 23 '20 21:02 Defman

Doing pack at compile is possible, but would requires some complex macro setup to work. rustc const might be able one day to do it, but I don't think it will be possible for at least a year or two.

I'm wondering about changing the Subspace definition so it can be copy free:

pub struct Subspace<'a> {
    prefix: Cow<'a, [u8]>,
}

Either that or:

pub struct Subspace<'a> {
    prefix: Prefix<'a>,
}
enum Prefix<'a> {
    Owned(Box<[u8]>),
    Borrowed(&'a[u8]),
    Value(&'a dyn TuplePack),
}

Speedy37 avatar Feb 26 '20 23:02 Speedy37