kaze/graph/
constant.rs

1/// A container for different types of integer constant values.
2///
3/// This type isn't typically used explicitly, as the graph API always takes `Constant` parameters as `Into<Constant>`, and `Constant` implements `From` for most of Rust's unsigned integer types. If an API entry point requires a `Constant`, prefer passing integer values/literals directly.
4///
5/// # Examples
6///
7/// ```
8/// use kaze::*;
9///
10/// let c = Context::new();
11///
12/// let m = c.module("MyModule");
13///
14/// let a = m.lit(true, 16);
15/// let b = m.lit(0xdeadbeefu32, 47);
16/// let c = m.reg("data", 20);
17/// c.default_value(5u32);
18/// let d = m.lit(42u32, 8);
19/// ```
20pub enum Constant {
21    /// Contains a boolean value
22    Bool(bool),
23    /// Contains an unsigned, 32-bit value
24    U32(u32),
25    /// Contains an unsigned, 64-bit value
26    U64(u64),
27    /// Contains an unsigned, 128-bit value
28    U128(u128),
29}
30
31impl Constant {
32    // TODO: Specific tests? I don't necessarily want to make this part of the public API at least.
33    pub(super) fn required_bits(&self) -> u32 {
34        match *self {
35            Constant::Bool(value) => 32 - (value as u32).leading_zeros(),
36            Constant::U32(value) => 32 - value.leading_zeros(),
37            Constant::U64(value) => 64 - value.leading_zeros(),
38            Constant::U128(value) => 128 - value.leading_zeros(),
39        }
40    }
41
42    pub(crate) fn numeric_value(&self) -> u128 {
43        match *self {
44            Constant::Bool(value) => value.into(),
45            Constant::U32(value) => value.into(),
46            Constant::U64(value) => value.into(),
47            Constant::U128(value) => value,
48        }
49    }
50}
51
52impl From<bool> for Constant {
53    fn from(value: bool) -> Self {
54        Constant::Bool(value)
55    }
56}
57
58impl From<u8> for Constant {
59    fn from(value: u8) -> Self {
60        Constant::U32(value as _)
61    }
62}
63
64impl From<u16> for Constant {
65    fn from(value: u16) -> Self {
66        Constant::U32(value as _)
67    }
68}
69
70impl From<u32> for Constant {
71    fn from(value: u32) -> Self {
72        Constant::U32(value)
73    }
74}
75
76impl From<u64> for Constant {
77    fn from(value: u64) -> Self {
78        Constant::U64(value)
79    }
80}
81
82impl From<u128> for Constant {
83    fn from(value: u128) -> Self {
84        Constant::U128(value)
85    }
86}