Skip to content
This repository was archived by the owner on Feb 6, 2024. It is now read-only.
This repository was archived by the owner on Feb 6, 2024. It is now read-only.

Unsized Cids #5

@Stebalien

Description

@Stebalien

I'm currently trying to define an "object safe" blockstore but I'd also like the blockstore to be generic over CID sizes. Unfortunately, I can't have generic functions in an object safe type.

However:

  1. I'm taking CIDs by reference (don't need to keep copies).
  2. Don't really care about the size.

So I'd like to erase it. Luckily. This seems to be entirely possible in safe and stable rust using unsized types:

#[derive(Debug)]
#[doc(hidden)]
pub struct MultihashBase<T: ?Sized> {
    code: u64,
    size: u8,
    digest: T,
}

#[derive(Debug)]
pub enum Version {
    V0,
    V1,
}

pub type Codec = u64;

#[derive(Debug)]
#[doc(hidden)]
pub struct CidBase<T: ?Sized> {
    version: Version,
    codec: Codec,
    hash: MultihashBase<T>,
}

pub type Cid<const S: usize> = CidBase<[u8; S]>;
pub type Multihash<const S: usize> = MultihashBase<[u8; S]>;

pub type CidSlice = CidBase<[u8]>; // Not sure how to name this...
pub type MultihashSlice = MultihashBase<[u8]>;

fn main() {
    let c: Cid<32> = Cid {
        version: Version::V1,
        codec: 0x55,
        hash: Multihash {
            code: 0,
            size: 32,
            digest: [0; 32],
        },
    };
    let cs: &CidSlice = &c; // this seems to "just work" on the latest stable compiler, no unsafe needed.
    println!("{:?}", cs);
}

It may be possible to do this without redefining these types, but it likely requires liberal use of transmute and a custom deref function. The above implementation is probably faster and safer (and more likely to play well with the borrow checker, especially NLL.

Would you be open to a set of PRs to implement this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions