#casting #safe #type #foo-bar #as

safecast

Traits to define safe casting between types

9 releases

0.2.3 Aug 13, 2024
0.2.2 Dec 20, 2023
0.2.1 Sep 3, 2023
0.2.0 Jul 3, 2023
0.1.1 Jan 5, 2021

#563 in Rust patterns

Download history 223/week @ 2024-11-14 202/week @ 2024-11-21 168/week @ 2024-11-28 219/week @ 2024-12-05 241/week @ 2024-12-12 118/week @ 2024-12-19 16/week @ 2024-12-26 72/week @ 2025-01-02 167/week @ 2025-01-09 166/week @ 2025-01-16 203/week @ 2025-01-23 199/week @ 2025-01-30 438/week @ 2025-02-06 309/week @ 2025-02-13 177/week @ 2025-02-20 218/week @ 2025-02-27

1,164 downloads per month
Used in 29 crates (22 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