#safe #cast #type #foo-bar #as

safecast

Traits to define safe casting between types

8 releases

0.2.2 Dec 20, 2023
0.2.1 Sep 3, 2023
0.2.0 Jul 3, 2023
0.1.4 Jan 21, 2023
0.1.1 Jan 5, 2021

#659 in Rust patterns

Download history 184/week @ 2023-12-18 45/week @ 2023-12-25 32/week @ 2024-01-01 32/week @ 2024-01-08 24/week @ 2024-01-15 46/week @ 2024-01-22 62/week @ 2024-01-29 19/week @ 2024-02-05 36/week @ 2024-02-12 45/week @ 2024-02-19 99/week @ 2024-02-26 225/week @ 2024-03-04 61/week @ 2024-03-11 164/week @ 2024-03-18 289/week @ 2024-03-25 335/week @ 2024-04-01

873 downloads per month
Used in 26 crates (21 directly)

Apache-2.0

12KB
191 lines

safecast

Rust traits to define safe casting between types.

Example usage:

use safecast::*;

struct Foo {
    a: i32,
}

struct Bar {
    b: u16,
}

enum Baz {
    Foo(Foo),
    Bar(Bar),
}

impl CastFrom<Bar> for Foo {
    fn cast_from(bar: Bar) -> Self {
        Foo { a: bar.b as i32 }
    }
}

impl TryCastFrom<Foo> for Bar {
    fn can_cast_from(foo: &Foo) -> bool {
        foo.a >= 0 && foo.a <= u16::MAX
    }

    fn opt_cast_from(foo: Foo) -> Option<Self> {
        if foo.a >= 0 && foo.a <= u16::MAX {
            Some(Self { b: foo.a as u16 })
        } else {
            None
        }
    }
}

impl AsType<Foo> for Baz {
    fn as_type(&self) -> Option<&Foo> {
        match self {
            Self::Foo(foo) => Some(foo),
            _ => None,
        }
    }

    fn as_type_mut(&mut self) -> Option<&mut Foo> {
        match self {
            Self::Foo(foo) => Some(foo),
            _ => None,
        }
    }

    fn into_type(self) -> Option<Foo> {
        match self {
            Self::Foo(foo) => Some(foo),
            _ => None,
        }
    }
}

No runtime deps