snarkvm_circuit_program/data/identifier/
mod.rs1#[cfg(test)]
17use snarkvm_circuit_types::environment::assert_scope;
18
19mod equal;
20mod from_bits;
21mod from_field;
22mod size_in_bits;
23mod to_bits;
24mod to_field;
25
26use snarkvm_circuit_network::Aleo;
27use snarkvm_circuit_types::{Boolean, Field, U8, environment::prelude::*};
28use snarkvm_utilities::ToBits as TB;
29
30#[derive(Clone)]
40pub struct Identifier<A: Aleo>(Field<A>, u8); impl<A: Aleo> Inject for Identifier<A> {
43 type Primitive = console::Identifier<A::Network>;
44
45 fn new(_: Mode, identifier: Self::Primitive) -> Self {
48 let identifier = identifier.to_string();
50
51 let field = Field::from_bits_le(&Vec::<Boolean<_>>::constant(identifier.to_bits_le()));
54
55 Self(field, identifier.len() as u8)
57 }
58}
59
60impl<A: Aleo> Eject for Identifier<A> {
61 type Primitive = console::Identifier<A::Network>;
62
63 fn eject_mode(&self) -> Mode {
65 debug_assert!(self.0.eject_mode() == Mode::Constant, "Identifier::eject_mode - Mode must be 'Constant'");
66 Mode::Constant
67 }
68
69 fn eject_value(&self) -> Self::Primitive {
71 match console::FromField::from_field(&self.0.eject_value()) {
72 Ok(identifier) => identifier,
73 Err(error) => A::halt(format!("Failed to convert an identifier to a string: {error}")),
74 }
75 }
76}
77
78impl<A: Aleo> Parser for Identifier<A> {
79 #[inline]
81 fn parse(string: &str) -> ParserResult<Self> {
82 let (string, identifier) = console::Identifier::parse(string)?;
84
85 Ok((string, Identifier::constant(identifier)))
86 }
87}
88
89impl<A: Aleo> FromStr for Identifier<A> {
90 type Err = Error;
91
92 #[inline]
94 fn from_str(string: &str) -> Result<Self> {
95 match Self::parse(string) {
96 Ok((remainder, object)) => {
97 ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
99 Ok(object)
101 }
102 Err(error) => bail!("Failed to parse string. {error}"),
103 }
104 }
105}
106
107impl<A: Aleo> Debug for Identifier<A> {
108 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
109 Display::fmt(self, f)
110 }
111}
112
113impl<A: Aleo> Display for Identifier<A> {
114 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
116 write!(f, "{}", self.eject_value())
117 }
118}
119
120impl<A: Aleo> Eq for Identifier<A> {}
121
122impl<A: Aleo> PartialEq for Identifier<A> {
123 fn eq(&self, other: &Self) -> bool {
125 self.0.eject_value() == other.0.eject_value()
126 }
127}
128
129impl<A: Aleo> core::hash::Hash for Identifier<A> {
130 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
132 self.0.eject_value().hash(state);
133 }
134}
135
136impl<A: Aleo> From<Identifier<A>> for LinearCombination<A::BaseField> {
137 fn from(identifier: Identifier<A>) -> Self {
139 From::from(&identifier)
140 }
141}
142
143impl<A: Aleo> From<&Identifier<A>> for LinearCombination<A::BaseField> {
144 fn from(identifier: &Identifier<A>) -> Self {
146 LinearCombination::from(&identifier.0)
147 }
148}
149
150#[cfg(test)]
151pub(crate) mod tests {
152 use super::*;
153 use crate::Circuit;
154 use console::{Rng, TestRng};
155
156 use anyhow::{Result, bail};
157 use core::str::FromStr;
158 use rand::distributions::Alphanumeric;
159
160 pub(crate) fn sample_console_identifier<A: Aleo>() -> Result<console::Identifier<A::Network>> {
162 let string = sample_console_identifier_as_string::<A>()?;
164 console::Identifier::from_str(&string)
166 }
167
168 pub(crate) fn sample_console_identifier_as_string<A: Aleo>() -> Result<String> {
170 let rng = &mut TestRng::default();
172 let string = "a".to_string()
174 + &rng
175 .sample_iter(&Alphanumeric)
176 .take(A::BaseField::size_in_data_bits() / (8 * 2))
177 .map(char::from)
178 .collect::<String>();
179 let max_bytes = A::BaseField::size_in_data_bits() / 8; match string.len() <= max_bytes {
182 true => Ok(string),
184 false => bail!("Identifier exceeds the maximum capacity allowed"),
185 }
186 }
187
188 pub(crate) fn sample_lowercase_console_identifier_as_string<A: Aleo>() -> Result<String> {
190 let string = sample_console_identifier_as_string::<A>()?;
192 Ok(string.to_lowercase())
194 }
195
196 #[test]
197 fn test_identifier_parse() -> Result<()> {
198 let candidate = Identifier::<Circuit>::parse("foo_bar").unwrap();
199 assert_eq!("", candidate.0);
200 assert_eq!(Identifier::<Circuit>::constant("foo_bar".try_into()?).eject(), candidate.1.eject());
201 Ok(())
202 }
203
204 #[test]
205 fn test_identifier_parse_fails() -> Result<()> {
206 let identifier = Identifier::<Circuit>::parse("foo_bar~baz").unwrap();
208 assert_eq!(("~baz", Identifier::<Circuit>::from_str("foo_bar")?.eject()), (identifier.0, identifier.1.eject()));
209 let identifier = Identifier::<Circuit>::parse("foo_bar-baz").unwrap();
210 assert_eq!(("-baz", Identifier::<Circuit>::from_str("foo_bar")?.eject()), (identifier.0, identifier.1.eject()));
211
212 assert!(Identifier::<Circuit>::parse("_").is_err());
214 assert!(Identifier::<Circuit>::parse("__").is_err());
215 assert!(Identifier::<Circuit>::parse("___").is_err());
216 assert!(Identifier::<Circuit>::parse("____").is_err());
217
218 assert!(Identifier::<Circuit>::parse("1").is_err());
220 assert!(Identifier::<Circuit>::parse("2").is_err());
221 assert!(Identifier::<Circuit>::parse("3").is_err());
222 assert!(Identifier::<Circuit>::parse("1foo").is_err());
223 assert!(Identifier::<Circuit>::parse("12").is_err());
224 assert!(Identifier::<Circuit>::parse("111").is_err());
225
226 let identifier =
228 Identifier::<Circuit>::parse("foo_bar_baz_qux_quux_quuz_corge_grault_garply_waldo_fred_plugh_xyzzy");
229 assert!(identifier.is_err());
230 Ok(())
231 }
232
233 #[test]
234 fn test_identifier_display() -> Result<()> {
235 let identifier = Identifier::<Circuit>::from_str("foo_bar")?;
236 assert_eq!("foo_bar", format!("{identifier}"));
237 Ok(())
238 }
239
240 #[test]
241 fn test_identifier_bits() -> Result<()> {
242 let identifier = Identifier::<Circuit>::from_str("foo_bar")?;
243 assert_eq!(
244 identifier.to_bits_le().eject(),
245 Identifier::from_bits_le(&identifier.to_bits_le()).to_bits_le().eject()
246 );
247 assert_eq!(
248 identifier.to_bits_be().eject(),
249 Identifier::from_bits_be(&identifier.to_bits_be()).to_bits_be().eject()
250 );
251 Ok(())
252 }
253}