snarkvm_utilities/serialize/
mod.rs

1// Copyright 2024 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
16pub mod error;
17pub use error::*;
18
19mod helpers;
20pub use helpers::*;
21
22mod impls;
23#[allow(unused_imports)]
24pub use impls::*;
25
26mod flags;
27pub use flags::*;
28
29mod traits;
30pub use traits::*;
31
32#[cfg(feature = "derive")]
33pub use snarkvm_utilities_derives::*;
34
35/// Return the number of (byte-aligned) bits and bytes required to represent the given number of bits.
36///
37/// Examples:
38/// - Given `64 bits`, returns `(64, 8)`.
39/// - Given `251 bits`, returns `(256, 32)`.
40/// - Given `999 bits`, returns `(1000, 125)`.
41#[inline]
42pub const fn number_of_bits_and_bytes(num_bits: usize) -> (usize, usize) {
43    let byte_size = number_of_bits_to_number_of_bytes(num_bits);
44    ((byte_size * 8), byte_size)
45}
46
47/// Return the number of bytes required to represent the given number of bits.
48#[inline]
49pub const fn number_of_bits_to_number_of_bytes(num_bits: usize) -> usize {
50    (num_bits + 7) / 8
51}
52
53#[test]
54fn test_number_of_bits_and_bytes() {
55    assert_eq!((64, 8), number_of_bits_and_bytes(64));
56    assert_eq!((256, 32), number_of_bits_and_bytes(251));
57    assert_eq!((1000, 125), number_of_bits_and_bytes(999));
58}