Skip to content

Why don’t you include the default Storable implementation for bool? #185

@linnefromice

Description

@linnefromice

There are cases where I want to use stable memory for things like flags that are represented by bools.
I think it would be possible to provide an implementation similar to the already existing one for u8.
Is it possible to provide this implementation?

The max_size is in bytes, so it may not be properly set, and the conversion to bool may not be optimal, but I have included an example of the code needed.

Example Code
impl Storable for bool {
    fn to_bytes(&self) -> Cow<[u8]> {
        let num: u8 = if *self { 1 } else { 0 };
        Cow::Owned(num.to_be_bytes().to_vec())
    }

    fn from_bytes(bytes: Cow<[u8]>) -> Self {
        let num = u8::from_be_bytes(bytes.as_ref().try_into().unwrap());
        match num {
            0 => false,
            1 => true,
            _ => panic!("Invalid bool encoding: expected 0 or 1, found {}", num)
        }
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 1,
        is_fixed_size: true,
    };
}

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