1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::Vec;
use anyhow::Result;
pub trait ToBits: Sized {
/// Returns `self` as a boolean array in little-endian order.
fn to_bits_le(&self) -> Vec<bool>;
/// Returns `self` as a boolean array in big-endian order.
fn to_bits_be(&self) -> Vec<bool>;
}
pub trait FromBits: Sized {
/// Reads `Self` from a boolean array in little-endian order.
fn from_bits_le(bits: &[bool]) -> Result<Self>;
/// Reads `Self` from a boolean array in big-endian order.
fn from_bits_be(bits: &[bool]) -> Result<Self>;
}
pub trait ToMinimalBits: Sized {
/// Returns `self` as a minimal boolean array.
fn to_minimal_bits(&self) -> Vec<bool>;
}
impl<T: ToMinimalBits> ToMinimalBits for Vec<T> {
fn to_minimal_bits(&self) -> Vec<bool> {
let mut res_bits = vec![];
for elem in self.iter() {
res_bits.extend(elem.to_minimal_bits());
}
res_bits
}
}
/********************/
/****** Tuples ******/
/********************/
/// A helper macro to implement `ToBits` for a tuple of `ToBits` circuits.
macro_rules! to_bits_tuple {
(($t0:ident, $i0:tt), $(($ty:ident, $idx:tt)),+) => {
impl<$t0: ToBits, $($ty: ToBits),+> ToBits for ($t0, $($ty),+) {
/// A helper method to return a concatenated list of little-endian bits from the circuits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The tuple is order-preserving, meaning the first circuit in is the first circuit bits out.
self.$i0.to_bits_le().into_iter()
$(.chain(self.$idx.to_bits_le().into_iter()))+
.collect()
}
/// A helper method to return a concatenated list of big-endian bits from the circuits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The tuple is order-preserving, meaning the first circuit in is the first circuit bits out.
self.$i0.to_bits_be().into_iter()
$(.chain(self.$idx.to_bits_be().into_iter()))+
.collect()
}
}
impl<'a, $t0: ToBits, $($ty: ToBits),+> ToBits for &'a ($t0, $($ty),+) {
/// A helper method to return a concatenated list of little-endian bits from the circuits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The tuple is order-preserving, meaning the first circuit in is the first circuit bits out.
self.$i0.to_bits_le().into_iter()
$(.chain(self.$idx.to_bits_le().into_iter()))+
.collect()
}
/// A helper method to return a concatenated list of big-endian bits from the circuits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The tuple is order-preserving, meaning the first circuit in is the first circuit bits out.
self.$i0.to_bits_be().into_iter()
$(.chain(self.$idx.to_bits_be().into_iter()))+
.collect()
}
}
}
}
to_bits_tuple!((C0, 0), (C1, 1));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5), (C6, 6));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5), (C6, 6), (C7, 7));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5), (C6, 6), (C7, 7), (C8, 8));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5), (C6, 6), (C7, 7), (C8, 8), (C9, 9));
to_bits_tuple!((C0, 0), (C1, 1), (C2, 2), (C3, 3), (C4, 4), (C5, 5), (C6, 6), (C7, 7), (C8, 8), (C9, 9), (C10, 10));
/********************/
/***** Integers *****/
/********************/
macro_rules! impl_bits_for_integer {
($int:ty) => {
impl ToBits for $int {
/// Returns `self` as a boolean array in little-endian order.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
let mut bits_le = Vec::with_capacity(<$int>::BITS as usize);
let mut value = *self;
for _ in 0..<$int>::BITS {
bits_le.push(value & 1 == 1);
value = value.wrapping_shr(1u32);
}
bits_le
}
/// Returns `self` as a boolean array in big-endian order.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
self.to_bits_le().into_iter().rev().collect()
}
}
impl FromBits for $int {
/// Reads `Self` from a boolean array in little-endian order.
#[inline]
fn from_bits_le(bits: &[bool]) -> Result<Self> {
Ok(bits.iter().rev().fold(0, |value, bit| match bit {
true => (value.wrapping_shl(1)) ^ 1,
false => (value.wrapping_shl(1)) ^ 0,
}))
}
/// Reads `Self` from a boolean array in big-endian order.
#[inline]
fn from_bits_be(bits: &[bool]) -> Result<Self> {
Ok(bits.iter().fold(0, |value, bit| match bit {
true => (value.wrapping_shl(1)) ^ 1,
false => (value.wrapping_shl(1)) ^ 0,
}))
}
}
};
}
impl_bits_for_integer!(u8);
impl_bits_for_integer!(u16);
impl_bits_for_integer!(u32);
impl_bits_for_integer!(u64);
impl_bits_for_integer!(u128);
impl_bits_for_integer!(i8);
impl_bits_for_integer!(i16);
impl_bits_for_integer!(i32);
impl_bits_for_integer!(i64);
impl_bits_for_integer!(i128);
/********************/
/****** String ******/
/********************/
impl ToBits for String {
/// A helper method to return a concatenated list of little-endian bits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The vector is order-preserving, meaning the first byte in is the first byte bits out.
self.as_bytes().to_bits_le()
}
/// A helper method to return a concatenated list of big-endian bits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The vector is order-preserving, meaning the first byte in is the first byte bits out.
self.as_bytes().to_bits_be()
}
}
/********************/
/****** Arrays ******/
/********************/
impl<C: ToBits> ToBits for Vec<C> {
/// A helper method to return a concatenated list of little-endian bits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The vector is order-preserving, meaning the first variable in is the first variable bits out.
self.as_slice().to_bits_le()
}
/// A helper method to return a concatenated list of big-endian bits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The vector is order-preserving, meaning the first variable in is the first variable bits out.
self.as_slice().to_bits_be()
}
}
impl<C: ToBits, const N: usize> ToBits for [C; N] {
/// A helper method to return a concatenated list of little-endian bits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The slice is order-preserving, meaning the first variable in is the first variable bits out.
self.as_slice().to_bits_le()
}
/// A helper method to return a concatenated list of big-endian bits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The slice is order-preserving, meaning the first variable in is the first variable bits out.
self.as_slice().to_bits_be()
}
}
impl<C: ToBits> ToBits for &[C] {
/// A helper method to return a concatenated list of little-endian bits.
#[inline]
fn to_bits_le(&self) -> Vec<bool> {
// The slice is order-preserving, meaning the first variable in is the first variable bits out.
self.iter().flat_map(|c| c.to_bits_le()).collect()
}
/// A helper method to return a concatenated list of big-endian bits.
#[inline]
fn to_bits_be(&self) -> Vec<bool> {
// The slice is order-preserving, meaning the first variable in is the first variable bits out.
self.iter().flat_map(|c| c.to_bits_be()).collect()
}
}
impl FromBits for Vec<u8> {
/// A helper method to return `Self` from a concatenated list of little-endian bits.
#[inline]
fn from_bits_le(bits: &[bool]) -> Result<Self> {
// The vector is order-preserving, meaning the first variable in is the first variable bits out.
bits.chunks(8).map(u8::from_bits_le).collect::<Result<Vec<_>>>()
}
/// A helper method to return `Self` from a concatenated list of big-endian bits.
#[inline]
fn from_bits_be(bits: &[bool]) -> Result<Self> {
// The vector is order-preserving, meaning the first variable in is the first variable bits out.
bits.chunks(8).map(u8::from_bits_be).collect::<Result<Vec<_>>>()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{TestRng, Uniform};
use anyhow::Result;
const ITERATIONS: u64 = 10000;
#[test]
fn test_integers() -> Result<()> {
macro_rules! check_integer {
($integer:tt, $rng:expr) => {{
for _ in 0..ITERATIONS {
let expected: $integer = Uniform::rand($rng);
let bits_le = expected.to_bits_le();
assert_eq!(expected, $integer::from_bits_le(&bits_le)?);
let bits_be = expected.to_bits_be();
assert_eq!(expected, $integer::from_bits_be(&bits_be)?);
}
}};
}
let mut rng = TestRng::default();
check_integer!(u8, &mut rng);
check_integer!(u16, &mut rng);
check_integer!(u32, &mut rng);
check_integer!(u64, &mut rng);
check_integer!(u128, &mut rng);
check_integer!(i8, &mut rng);
check_integer!(i16, &mut rng);
check_integer!(i32, &mut rng);
check_integer!(i64, &mut rng);
check_integer!(i128, &mut rng);
Ok(())
}
}