cairo_lang_sierra/extensions/modules/
bytes31.rs

1use num_bigint::BigInt;
2
3use super::consts::{ConstGenLibfunc, WrapConstGenLibfunc};
4use super::try_from_felt252::{TryFromFelt252, TryFromFelt252Libfunc};
5use super::utils::reinterpret_cast_signature;
6use crate::define_libfunc_hierarchy;
7use crate::extensions::felt252::Felt252Type;
8use crate::extensions::lib_func::{LibfuncSignature, SignatureSpecializationContext};
9use crate::extensions::{
10    NamedType, NoGenericArgsGenericLibfunc, NoGenericArgsGenericType, SpecializationError,
11};
12use crate::ids::GenericTypeId;
13
14/// Type for bytes31.
15#[derive(Default)]
16pub struct Bytes31Type {}
17impl NoGenericArgsGenericType for Bytes31Type {
18    const ID: GenericTypeId = GenericTypeId::new_inline("bytes31");
19    const STORABLE: bool = true;
20    const DUPLICATABLE: bool = true;
21    const DROPPABLE: bool = true;
22    const ZERO_SIZED: bool = false;
23}
24
25define_libfunc_hierarchy! {
26    pub enum Bytes31Libfunc {
27        Const(Bytes31ConstLibfunc),
28        ToFelt252(Bytes31ToFelt252Libfunc),
29        TryFromFelt252(Bytes31FromFelt252Libfunc),
30    }, Bytes31ConcreteLibfunc
31}
32
33/// Libfunc for creating a constant bytes31.
34#[derive(Default)]
35pub struct Bytes31ConstLibfuncWrapped {}
36impl ConstGenLibfunc for Bytes31ConstLibfuncWrapped {
37    const STR_ID: &'static str = "bytes31_const";
38    const GENERIC_TYPE_ID: GenericTypeId = <Bytes31Type as NoGenericArgsGenericType>::ID;
39
40    fn bound() -> BigInt {
41        BigInt::from(2).pow(248)
42    }
43}
44pub type Bytes31ConstLibfunc = WrapConstGenLibfunc<Bytes31ConstLibfuncWrapped>;
45
46/// Libfunc for converting a bytes31 into a felt252.
47#[derive(Default)]
48pub struct Bytes31ToFelt252Libfunc {}
49impl NoGenericArgsGenericLibfunc for Bytes31ToFelt252Libfunc {
50    const STR_ID: &'static str = "bytes31_to_felt252";
51
52    fn specialize_signature(
53        &self,
54        context: &dyn SignatureSpecializationContext,
55    ) -> Result<LibfuncSignature, SpecializationError> {
56        Ok(reinterpret_cast_signature(
57            context.get_concrete_type(Bytes31Type::id(), &[])?,
58            context.get_concrete_type(Felt252Type::id(), &[])?,
59        ))
60    }
61}
62
63/// Libfunc for attempting to convert a felt252 into a bytes31.
64#[derive(Default)]
65pub struct Bytes31FromFelt252Trait;
66impl TryFromFelt252 for Bytes31FromFelt252Trait {
67    const STR_ID: &'static str = "bytes31_try_from_felt252";
68    const GENERIC_TYPE_ID: GenericTypeId = <Bytes31Type as NoGenericArgsGenericType>::ID;
69}
70
71type Bytes31FromFelt252Libfunc = TryFromFelt252Libfunc<Bytes31FromFelt252Trait>;