/ console / program / src / data / literal / size_in_bits.rs
size_in_bits.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the alphavm 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  
16  use super::*;
17  
18  impl<N: Network> Literal<N> {
19      /// Returns the number of bits of this literal.
20      pub fn size_in_bits(&self) -> u16 {
21          let size = match self {
22              Self::Address(..) => Address::<N>::size_in_bits(),
23              Self::Boolean(..) => Boolean::<N>::size_in_bits(),
24              Self::Field(..) => Field::<N>::size_in_bits(),
25              Self::Group(..) => Group::<N>::size_in_bits(),
26              Self::I8(..) => I8::<N>::size_in_bits(),
27              Self::I16(..) => I16::<N>::size_in_bits(),
28              Self::I32(..) => I32::<N>::size_in_bits(),
29              Self::I64(..) => I64::<N>::size_in_bits(),
30              Self::I128(..) => I128::<N>::size_in_bits(),
31              Self::U8(..) => U8::<N>::size_in_bits(),
32              Self::U16(..) => U16::<N>::size_in_bits(),
33              Self::U32(..) => U32::<N>::size_in_bits(),
34              Self::U64(..) => U64::<N>::size_in_bits(),
35              Self::U128(..) => U128::<N>::size_in_bits(),
36              Self::Scalar(..) => Scalar::<N>::size_in_bits(),
37              Self::Signature(..) => Signature::<N>::size_in_bits(),
38              Self::String(string) => match string.len().checked_mul(8) {
39                  Some(size) => size,
40                  None => N::halt("String exceeds usize::MAX bits."),
41              },
42          };
43          u16::try_from(size).or_halt_with::<N>("Literal exceeds u16::MAX bits.")
44      }
45  }