cairo_lang_utils/
lib.rs

1//! Cairo utilities.
2
3#![cfg_attr(not(feature = "std"), no_std)]
4
5#[cfg(not(feature = "std"))]
6extern crate alloc;
7
8#[cfg(not(feature = "std"))]
9use alloc::boxed::Box;
10use core::fmt;
11
12/// Re-exporting the [`smol_str`] crate so that downstream projects can always use the same
13/// instance the compiler does.
14pub use ::smol_str;
15
16pub mod bigint;
17pub mod byte_array;
18pub mod casts;
19pub mod collection_arithmetics;
20pub mod deque;
21pub mod extract_matches;
22#[cfg(feature = "std")]
23pub mod graph_algos;
24pub mod iterators;
25#[cfg(feature = "tracing")]
26pub mod logging;
27pub mod ordered_hash_map;
28pub mod ordered_hash_set;
29#[cfg(feature = "std")]
30pub mod small_ordered_map;
31pub mod unordered_hash_map;
32pub mod unordered_hash_set;
33
34/// Similar to From / TryFrom, but returns an option.
35pub trait OptionFrom<T>
36where
37    Self: Sized,
38{
39    fn option_from(other: T) -> Option<Self>;
40}
41
42pub fn write_comma_separated<Iter: IntoIterator<Item = V>, V: core::fmt::Display>(
43    f: &mut fmt::Formatter<'_>,
44    values: Iter,
45) -> fmt::Result {
46    let mut iter = values.into_iter();
47    if let Some(value) = iter.next() {
48        write!(f, "{value}")?;
49    }
50    for value in iter {
51        write!(f, ", {value}")?;
52    }
53    Ok(())
54}
55
56/// Helper operations on `Option<T>`.
57pub trait OptionHelper {
58    fn on_none<F: FnOnce()>(self, f: F) -> Self;
59}
60impl<T> OptionHelper for Option<T> {
61    fn on_none<F: FnOnce()>(self, f: F) -> Self {
62        if self.is_none() {
63            f();
64        }
65        self
66    }
67}
68
69/// Borrows a mutable reference as Box for the lifespan of this function.
70///
71/// Runs the given closure with the boxed value as a parameter.
72/// The closure is expected to return a boxed value, whose changes will be reflected on the mutable
73/// reference.
74/// Example:
75/// ```
76/// use cairo_lang_utils::borrow_as_box;
77/// let mut x = 5;
78/// borrow_as_box(&mut x, |mut x: Box<usize>| {
79///     *x += 1;
80///     ((), x)
81/// });
82/// assert_eq!(x, 6);
83/// ```
84pub fn borrow_as_box<T: Default, R, F: FnOnce(Box<T>) -> (R, Box<T>)>(ptr: &mut T, f: F) -> R {
85    // TODO(spapini): Consider replacing take with something the leaves the memory dangling, instead
86    // of filling with default().
87    let (res, boxed) = f(Box::new(core::mem::take(ptr)));
88    *ptr = *boxed;
89    res
90}
91
92#[cfg(feature = "std")]
93pub trait Intern<'db, Target> {
94    fn intern(self, db: &'db dyn salsa::Database) -> Target;
95}
96
97/// TODO(eytan-starkware): Remove this macro entirely and rely on `salsa::interned`.
98// Defines a short id struct for use with salsa interning.
99// Interning is the process of representing a value as an id in a table.
100// We usually denote the value type as "long id", and the id type as "short id" or just "id".
101// Example:
102//   A function's long id may be the module in which it is defined and its name. The function is
103//   assigned a sequential integer (salsa::InternId) which will be its short id. Salsa will hold a
104//   table to translate between the two representations. Note that a long id of an entity will
105//   usually include the short id of the entity's parent.
106#[macro_export]
107macro_rules! define_short_id {
108    ($short_id:ident, $long_id:path) => {
109        // 1. Modern interned struct.
110        #[salsa::interned(revisions = usize::MAX)]
111        pub struct $short_id<'db> {
112            #[returns(ref)]
113            pub long: $long_id,
114        }
115
116        impl<'db> std::fmt::Debug for $short_id<'db> {
117            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118                write!(f, "{}({:x})", stringify!($short_id), self.as_intern_id().index())
119            }
120        }
121
122        impl<'db> cairo_lang_utils::Intern<'db, $short_id<'db>> for $long_id {
123            fn intern(self, db: &'db dyn salsa::Database) -> $short_id<'db> {
124                $short_id::new(db, self)
125            }
126        }
127
128        impl<'db> $short_id<'db> {
129            pub fn from_intern_id(intern_id: salsa::Id) -> Self {
130                use salsa::plumbing::FromId;
131                Self::from_id(intern_id)
132            }
133
134            pub fn as_intern_id(self) -> salsa::Id {
135                use salsa::plumbing::AsId;
136                self.as_id()
137            }
138        }
139
140        // 4. DebugWithDb identical to old macro.
141        impl<'db> cairo_lang_debug::DebugWithDb<'db> for $short_id<'db> {
142            type Db = dyn salsa::Database;
143            fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db Self::Db) -> std::fmt::Result {
144                use core::fmt::Debug;
145
146                use cairo_lang_debug::helper::{Fallback, HelperDebug};
147
148                HelperDebug::<$long_id, dyn salsa::Database>::helper_debug(self.long(db), db).fmt(f)
149            }
150        }
151    };
152}
153
154/// Returns `Some(())` if the condition is true, otherwise `None`.
155///
156/// Useful in functions returning `None` on some condition:
157/// `require(condition)?;`
158/// And for functions returning `Err` on some condition:
159/// `require(condition).ok_or_else(|| create_err())?;`
160#[must_use = "This function is only relevant to create a possible return."]
161pub fn require(condition: bool) -> Option<()> {
162    condition.then_some(())
163}