snarkvm_console_program/data/plaintext/
from_bits.rs

1// Copyright 2024-2025 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
16use super::*;
17
18impl<N: Network> FromBits for Plaintext<N> {
19    /// Initializes a new plaintext from a list of little-endian bits *without* trailing zeros.
20    fn from_bits_le(bits_le: &[bool]) -> Result<Self> {
21        Self::from_bits_le_internal(bits_le, 0)
22    }
23
24    /// Initializes a new plaintext from a list of big-endian bits *without* trailing zeros.
25    fn from_bits_be(bits_be: &[bool]) -> Result<Self> {
26        Self::from_bits_be_internal(bits_be, 0)
27    }
28}
29
30impl<N: Network> Plaintext<N> {
31    /// Initializes a new plaintext from a list of little-endian bits *without* trailing zeros, while the depth of the data.
32    fn from_bits_le_internal(bits_le: &[bool], depth: usize) -> Result<Self> {
33        // Ensure that the depth is within the maximum limit.
34        if depth > N::MAX_DATA_DEPTH {
35            bail!("Plaintext depth exceeds maximum limit: {}", N::MAX_DATA_DEPTH)
36        }
37
38        let bits = bits_le;
39
40        // The starting index used to create subsequent subslices of the `bits` slice.
41        let mut index = 0;
42
43        // Helper function to get the next n bits as a slice.
44        let mut next_bits = |n: usize| -> Result<&[bool]> {
45            // Safely procure a subslice with the length `n` starting at `index`.
46            let subslice = bits.get(index..index + n);
47            // Check if the range is within bounds.
48            if let Some(next_bits) = subslice {
49                // Move the starting index.
50                index += n;
51                // Return the subslice.
52                Ok(next_bits)
53            } else {
54                bail!("Insufficient bits");
55            }
56        };
57
58        let variant = next_bits(2)?;
59        let variant = [variant[0], variant[1]];
60
61        // Literal
62        if variant == [false, false] {
63            let literal_variant = u8::from_bits_le(next_bits(8)?)?;
64            let literal_size = u16::from_bits_le(next_bits(16)?)?;
65            let literal = Literal::from_bits_le(literal_variant, next_bits(literal_size as usize)?)?;
66
67            // Cache the plaintext bits, and return the literal.
68            Ok(Self::Literal(literal, OnceCell::with_value(bits_le.to_vec())))
69        }
70        // Struct
71        else if variant == [false, true] {
72            let num_members = u8::from_bits_le(next_bits(8)?)?;
73            if num_members as usize > N::MAX_STRUCT_ENTRIES {
74                bail!("Struct exceeds maximum of entries.");
75            }
76
77            let mut members = IndexMap::with_capacity(num_members as usize);
78            for _ in 0..num_members {
79                let identifier_size = u8::from_bits_le(next_bits(8)?)?;
80                let identifier = Identifier::from_bits_le(next_bits(identifier_size as usize)?)?;
81
82                let member_size = u16::from_bits_le(next_bits(16)?)?;
83                let value = Plaintext::from_bits_le_internal(next_bits(member_size as usize)?, depth + 1)?;
84
85                if members.insert(identifier, value).is_some() {
86                    bail!("Duplicate identifier in struct.");
87                }
88            }
89
90            // Cache the plaintext bits, and return the struct.
91            Ok(Self::Struct(members, OnceCell::with_value(bits_le.to_vec())))
92        }
93        // Array
94        else if variant == [true, false] {
95            let num_elements = u32::from_bits_le(next_bits(32)?)?;
96            if num_elements as usize > N::MAX_ARRAY_ELEMENTS {
97                bail!("Array exceeds maximum of elements.");
98            }
99
100            let mut elements = Vec::with_capacity(num_elements as usize);
101            for _ in 0..num_elements {
102                let element_size = u16::from_bits_le(next_bits(16)?)?;
103                let element = Plaintext::from_bits_le_internal(next_bits(element_size as usize)?, depth + 1)?;
104
105                elements.push(element);
106            }
107
108            // Cache the plaintext bits, and return the array.
109            Ok(Self::Array(elements, OnceCell::with_value(bits_le.to_vec())))
110        }
111        // Unknown variant.
112        else {
113            bail!("Unknown plaintext variant - {variant:?}");
114        }
115    }
116
117    /// Initializes a new plaintext from a list of big-endian bits *without* trailing zeros, while tracking the depth of the data.
118    fn from_bits_be_internal(bits_be: &[bool], depth: usize) -> Result<Self> {
119        // Ensure that the depth is within the maximum limit.
120        if depth > N::MAX_DATA_DEPTH {
121            bail!("Plaintext depth exceeds maximum limit: {}", N::MAX_DATA_DEPTH)
122        }
123
124        let bits = bits_be;
125
126        // The starting index used to create subsequent subslices of the `bits` slice.
127        let mut index = 0;
128
129        // Helper function to get the next n bits as a slice.
130        let mut next_bits = |n: usize| -> Result<&[bool]> {
131            // Safely procure a subslice with the length `n` starting at `index`.
132            let subslice = bits.get(index..index + n);
133            // Check if the range is within bounds.
134            if let Some(next_bits) = subslice {
135                // Move the starting index.
136                index += n;
137                // Return the subslice.
138                Ok(next_bits)
139            } else {
140                bail!("Insufficient bits");
141            }
142        };
143
144        let variant = next_bits(2)?;
145        let variant = [variant[0], variant[1]];
146
147        // Literal
148        if variant == [false, false] {
149            let literal_variant = u8::from_bits_be(next_bits(8)?)?;
150            let literal_size = u16::from_bits_be(next_bits(16)?)?;
151            let literal = Literal::from_bits_be(literal_variant, next_bits(literal_size as usize)?)?;
152
153            // Cache the plaintext bits, and return the literal.
154            Ok(Self::Literal(literal, OnceCell::with_value(bits_be.to_vec())))
155        }
156        // Struct
157        else if variant == [false, true] {
158            let num_members = u8::from_bits_be(next_bits(8)?)?;
159            if num_members as usize > N::MAX_STRUCT_ENTRIES {
160                bail!("Struct exceeds maximum of entries.");
161            }
162            let mut members = IndexMap::with_capacity(num_members as usize);
163            for _ in 0..num_members {
164                let identifier_size = u8::from_bits_be(next_bits(8)?)?;
165                let identifier = Identifier::from_bits_be(next_bits(identifier_size as usize)?)?;
166                let member_size = u16::from_bits_be(next_bits(16)?)?;
167                let value = Plaintext::from_bits_be_internal(next_bits(member_size as usize)?, depth + 1)?;
168                if members.insert(identifier, value).is_some() {
169                    bail!("Duplicate identifier in struct.");
170                }
171            }
172
173            // Cache the plaintext bits, and return the struct.
174            Ok(Self::Struct(members, OnceCell::with_value(bits_be.to_vec())))
175        }
176        // Array
177        else if variant == [true, false] {
178            let num_elements = u32::from_bits_be(next_bits(32)?)?;
179            if num_elements as usize > N::MAX_ARRAY_ELEMENTS {
180                bail!("Array exceeds maximum of elements.");
181            }
182
183            let mut elements = Vec::with_capacity(num_elements as usize);
184            for _ in 0..num_elements {
185                let element_size = u16::from_bits_be(next_bits(16)?)?;
186                let element = Plaintext::from_bits_be_internal(next_bits(element_size as usize)?, depth + 1)?;
187
188                elements.push(element);
189            }
190
191            // Cache the plaintext bits, and return the array.
192            Ok(Self::Array(elements, OnceCell::with_value(bits_be.to_vec())))
193        }
194        // Unknown variant.
195        else {
196            bail!("Unknown plaintext variant - {variant:?}");
197        }
198    }
199}