Skip to main content

snarkvm_console_types_string/
lib.rs

1// Copyright (c) 2019-2026 Provable Inc.
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
19pub mod identifier_literal;
20pub use identifier_literal::{IdentifierLiteral, SIZE_IN_BITS, SIZE_IN_BYTES};
21
22mod bitwise;
23mod bytes;
24mod parse;
25mod random;
26mod serialize;
27
28pub use snarkvm_console_network_environment::prelude::*;
29pub use snarkvm_console_types_boolean::Boolean;
30pub use snarkvm_console_types_field::Field;
31pub use snarkvm_console_types_integers::Integer;
32
33use core::marker::PhantomData;
34
35#[derive(Clone, PartialEq, Eq, Hash)]
36pub struct StringType<E: Environment> {
37    /// The underlying string.
38    string: String,
39    /// PhantomData
40    _phantom: PhantomData<E>,
41}
42
43impl<E: Environment> StringTrait for StringType<E> {}
44
45impl<E: Environment> StringType<E> {
46    /// Initializes a new string.
47    pub fn new(string: &str) -> Self {
48        // Ensure the string is within the allowed capacity.
49        let num_bytes = string.len();
50        match num_bytes <= E::MAX_STRING_BYTES as usize {
51            true => Self { string: string.to_string(), _phantom: PhantomData },
52            false => E::halt(format!("Attempted to allocate a string of size {num_bytes}")),
53        }
54    }
55}
56
57impl<E: Environment> TypeName for StringType<E> {
58    /// Returns the type name as a string.
59    #[inline]
60    fn type_name() -> &'static str {
61        "string"
62    }
63}
64
65impl<E: Environment> Deref for StringType<E> {
66    type Target = str;
67
68    #[inline]
69    fn deref(&self) -> &Self::Target {
70        self.string.as_str()
71    }
72}