snarkvm_console_program/data/plaintext/
from_fields.rs

1// Copyright (c) 2019-2025 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
16use super::*;
17
18impl<N: Network> TryFrom<Vec<Field<N>>> for Plaintext<N> {
19    type Error = Error;
20
21    /// Initializes a plaintext from a list of base field elements.
22    fn try_from(fields: Vec<Field<N>>) -> Result<Self, Self::Error> {
23        Self::from_fields(&fields)
24    }
25}
26
27impl<N: Network> TryFrom<&[Field<N>]> for Plaintext<N> {
28    type Error = Error;
29
30    /// Initializes a plaintext from a list of base field elements.
31    fn try_from(fields: &[Field<N>]) -> Result<Self, Self::Error> {
32        Self::from_fields(fields)
33    }
34}
35
36impl<N: Network> FromFields for Plaintext<N> {
37    type Field = Field<N>;
38
39    /// Initializes a plaintext from a list of base field elements.
40    fn from_fields(fields: &[Self::Field]) -> Result<Self> {
41        // Ensure the number of field elements does not exceed the maximum allowed size.
42        if fields.len() > N::MAX_DATA_SIZE_IN_FIELDS as usize {
43            bail!("Plaintext exceeds maximum allowed size")
44        }
45
46        // Unpack the field elements into little-endian bits, and reverse the list for popping the terminus bit off.
47        let mut bits_le =
48            fields.iter().flat_map(|field| field.to_bits_le().into_iter().take(Field::<N>::size_in_data_bits())).rev();
49        // Remove the terminus bit that was added during encoding.
50        for boolean in bits_le.by_ref() {
51            // Drop all extraneous `0` bits, in addition to the final `1` bit.
52            if boolean {
53                // This case will always be reached, since the terminus bit is always `1`.
54                break;
55            }
56        }
57        // Reverse the bits back and recover the data from the bits.
58        Self::from_bits_le(&bits_le.rev().collect::<Vec<_>>())
59    }
60}