cairo_lang_sierra/extensions/modules/
is_zero.rs

1use std::marker::PhantomData;
2
3use super::non_zero::nonzero_ty;
4use crate::extensions::lib_func::{
5    BranchSignature, LibfuncSignature, OutputVarInfo, ParamSignature, SierraApChange,
6    SignatureSpecializationContext,
7};
8use crate::extensions::{NoGenericArgsGenericLibfunc, OutputVarReferenceInfo, SpecializationError};
9use crate::ids::GenericTypeId;
10
11/// Trait for implementing a IsZero library function for a type.
12pub trait IsZeroTraits: Default {
13    /// The is_zero library function id.
14    const IS_ZERO: &'static str;
15    /// The id of the generic type to implement the library functions for.
16    const GENERIC_TYPE_ID: GenericTypeId;
17}
18
19/// Libfunc for checking whether the given value is zero or not, and returning a non-zero wrapped
20/// value in case of success.
21#[derive(Default)]
22pub struct IsZeroLibfunc<TIsZeroTraits: IsZeroTraits> {
23    _phantom: PhantomData<TIsZeroTraits>,
24}
25impl<TIsZeroTraits: IsZeroTraits> NoGenericArgsGenericLibfunc for IsZeroLibfunc<TIsZeroTraits> {
26    const STR_ID: &'static str = TIsZeroTraits::IS_ZERO;
27
28    fn specialize_signature(
29        &self,
30        context: &dyn SignatureSpecializationContext,
31    ) -> Result<LibfuncSignature, SpecializationError> {
32        let ty = context.get_concrete_type(TIsZeroTraits::GENERIC_TYPE_ID, &[])?;
33        Ok(LibfuncSignature {
34            param_signatures: vec![ParamSignature::new(ty.clone())],
35            branch_signatures: vec![
36                // Zero.
37                BranchSignature {
38                    vars: vec![],
39                    ap_change: SierraApChange::Known { new_vars_only: true },
40                },
41                // NonZero.
42                BranchSignature {
43                    vars: vec![OutputVarInfo {
44                        ty: nonzero_ty(context, &ty)?,
45                        ref_info: OutputVarReferenceInfo::SameAsParam { param_idx: 0 },
46                    }],
47                    ap_change: SierraApChange::Known { new_vars_only: true },
48                },
49            ],
50            fallthrough: Some(0),
51        })
52    }
53}