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