snarkvm_console_types_string/
lib.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM 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
19mod bitwise;
20mod bytes;
21mod parse;
22mod random;
23mod serialize;
24
25pub use snarkvm_console_network_environment::prelude::*;
26pub use snarkvm_console_types_boolean::Boolean;
27pub use snarkvm_console_types_field::Field;
28pub use snarkvm_console_types_integers::Integer;
29
30use core::marker::PhantomData;
31
32#[derive(Clone, PartialEq, Eq, Hash)]
33pub struct StringType<E: Environment> {
34    /// The underlying string.
35    string: String,
36    /// PhantomData
37    _phantom: PhantomData<E>,
38}
39
40impl<E: Environment> StringTrait for StringType<E> {}
41
42impl<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
54impl<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
62impl<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}