/ console / types / string / src / lib.rs
lib.rs
 1  // Copyright (c) 2025 ADnet Contributors
 2  // This file is part of the AlphaVM library.
 3  
 4  // Licensed under the Apache License, Version 2.0 (the "License");
 5  // you may not use this file except in compliance with the License.
 6  // You may obtain a copy of the License at:
 7  
 8  // http://www.apache.org/licenses/LICENSE-2.0
 9  
10  // Unless required by applicable law or agreed to in writing, software
11  // distributed under the License is distributed on an "AS IS" BASIS,
12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  // See the License for the specific language governing permissions and
14  // limitations under the License.
15  
16  #![cfg_attr(test, allow(clippy::assertions_on_result_states))]
17  #![warn(clippy::cast_possible_truncation)]
18  
19  mod bitwise;
20  mod bytes;
21  mod parse;
22  mod random;
23  mod serialize;
24  
25  pub use alphavm_console_network_environment::prelude::*;
26  pub use alphavm_console_types_boolean::Boolean;
27  pub use alphavm_console_types_field::Field;
28  pub use alphavm_console_types_integers::Integer;
29  
30  use core::marker::PhantomData;
31  
32  #[derive(Clone, PartialEq, Eq, Hash)]
33  pub struct StringType<E: Environment> {
34      /// The underlying string.
35      string: String,
36      /// PhantomData
37      _phantom: PhantomData<E>,
38  }
39  
40  impl<E: Environment> StringTrait for StringType<E> {}
41  
42  impl<E: Environment> StringType<E> {
43      /// Initializes a new string.
44      pub fn new(string: &str) -> Self {
45          // Ensure the string is within the allowed capacity.
46          let num_bytes = string.len();
47          match num_bytes <= E::MAX_STRING_BYTES as usize {
48              true => Self { string: string.to_string(), _phantom: PhantomData },
49              false => E::halt(format!("Attempted to allocate a string of size {num_bytes}")),
50          }
51      }
52  }
53  
54  impl<E: Environment> TypeName for StringType<E> {
55      /// Returns the type name as a string.
56      #[inline]
57      fn type_name() -> &'static str {
58          "string"
59      }
60  }
61  
62  impl<E: Environment> Deref for StringType<E> {
63      type Target = str;
64  
65      #[inline]
66      fn deref(&self) -> &Self::Target {
67          self.string.as_str()
68      }
69  }