snarkvm_console_program/data/literal/cast_lossy/
mod.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
16mod boolean;
17mod field;
18mod integer;
19mod scalar;
20
21use crate::{Literal, LiteralType};
22use snarkvm_console_algorithms::Elligator2;
23use snarkvm_console_network::Network;
24use snarkvm_console_types::{Boolean, integers::Integer, prelude::*};
25
26/// Unary operator for casting values of one type to another, with lossy truncation.
27pub trait CastLossy<T: Sized = Self> {
28    /// Casts the value of `self` into a value of type `T`, with lossy truncation.
29    ///
30    /// This method makes a *best-effort* attempt to preserve all bits of information,
31    /// but it is not guaranteed to do so.
32    fn cast_lossy(&self) -> T;
33}
34
35impl<N: Network> Literal<N> {
36    /// Casts the literal to the given literal type, with lossy truncation.
37    ///
38    /// This method makes a *best-effort* attempt to preserve all bits of information,
39    /// but it is not guaranteed to do so.
40    ///
41    /// The hierarchy of casting is as follows:
42    ///  - (`Address`, `Group`) <-> `Field` <-> `Scalar` <-> `Integer` <-> `Boolean`
43    ///  - `Signature` (not supported)
44    ///  - `String` (not supported)
45    ///
46    /// Note that casting to left along the hierarchy always preserves information.
47    pub fn cast_lossy(&self, to_type: LiteralType) -> Result<Self> {
48        match self {
49            Self::Address(address) => cast_lossy_group_to_type(address.to_group(), to_type),
50            Self::Boolean(boolean) => cast_lossy_boolean_to_type(boolean, to_type),
51            Self::Field(field) => cast_lossy_field_to_type(field, to_type),
52            Self::Group(group) => cast_lossy_group_to_type(group, to_type),
53            Self::I8(integer) => cast_lossy_integer_to_type(integer, to_type),
54            Self::I16(integer) => cast_lossy_integer_to_type(integer, to_type),
55            Self::I32(integer) => cast_lossy_integer_to_type(integer, to_type),
56            Self::I64(integer) => cast_lossy_integer_to_type(integer, to_type),
57            Self::I128(integer) => cast_lossy_integer_to_type(integer, to_type),
58            Self::U8(integer) => cast_lossy_integer_to_type(integer, to_type),
59            Self::U16(integer) => cast_lossy_integer_to_type(integer, to_type),
60            Self::U32(integer) => cast_lossy_integer_to_type(integer, to_type),
61            Self::U64(integer) => cast_lossy_integer_to_type(integer, to_type),
62            Self::U128(integer) => cast_lossy_integer_to_type(integer, to_type),
63            Self::Scalar(scalar) => cast_lossy_scalar_to_type(scalar, to_type),
64            Self::Signature(..) => bail!("Cannot cast a signature literal to another type."),
65            Self::String(..) => bail!("Cannot cast a string literal to another type."),
66        }
67    }
68}
69
70/// A helper macro to implement the body of the `cast_lossy` methods.
71macro_rules! impl_cast_lossy_body {
72    ($type_name:ident, $cast_lossy:ident, $input:expr, $to_type:expr) => {
73        match $to_type {
74            LiteralType::Address => Ok(Literal::Address($input.$cast_lossy())),
75            LiteralType::Boolean => Ok(Literal::Boolean($input.$cast_lossy())),
76            LiteralType::Field => Ok(Literal::Field($input.$cast_lossy())),
77            LiteralType::Group => Ok(Literal::Group($input.$cast_lossy())),
78            LiteralType::I8 => Ok(Literal::I8($input.$cast_lossy())),
79            LiteralType::I16 => Ok(Literal::I16($input.$cast_lossy())),
80            LiteralType::I32 => Ok(Literal::I32($input.$cast_lossy())),
81            LiteralType::I64 => Ok(Literal::I64($input.$cast_lossy())),
82            LiteralType::I128 => Ok(Literal::I128($input.$cast_lossy())),
83            LiteralType::U8 => Ok(Literal::U8($input.$cast_lossy())),
84            LiteralType::U16 => Ok(Literal::U16($input.$cast_lossy())),
85            LiteralType::U32 => Ok(Literal::U32($input.$cast_lossy())),
86            LiteralType::U64 => Ok(Literal::U64($input.$cast_lossy())),
87            LiteralType::U128 => Ok(Literal::U128($input.$cast_lossy())),
88            LiteralType::Scalar => Ok(Literal::Scalar($input.$cast_lossy())),
89            LiteralType::Signature => {
90                bail!(concat!("Cannot cast (lossy) a ", stringify!($type_name), " literal to a signature type."))
91            }
92            LiteralType::String => {
93                bail!(concat!("Cannot cast (lossy) a ", stringify!($type_name), " literal to a string type."))
94            }
95        }
96    };
97}
98
99/// Casts a boolean literal to the given literal type, with lossy truncation.
100fn cast_lossy_boolean_to_type<N: Network>(input: &Boolean<N>, to_type: LiteralType) -> Result<Literal<N>> {
101    impl_cast_lossy_body!(boolean, cast_lossy, input, to_type)
102}
103
104/// Casts a field literal to the given literal type, with lossy truncation.
105fn cast_lossy_field_to_type<N: Network>(input: &Field<N>, to_type: LiteralType) -> Result<Literal<N>> {
106    impl_cast_lossy_body!(field, cast_lossy, input, to_type)
107}
108
109/// Casts a group literal to the given literal type, with lossy truncation.
110fn cast_lossy_group_to_type<N: Network>(input: &Group<N>, to_type: LiteralType) -> Result<Literal<N>> {
111    match to_type {
112        LiteralType::Address => Ok(Literal::Address(Address::new(*input))),
113        LiteralType::Group => Ok(Literal::Group(*input)),
114        _ => cast_lossy_field_to_type(&input.to_x_coordinate(), to_type),
115    }
116}
117
118/// Casts an integer literal to the given literal type, with lossy truncation.
119fn cast_lossy_integer_to_type<N: Network, I>(input: &Integer<N, I>, to_type: LiteralType) -> Result<Literal<N>>
120where
121    I: AsPrimitive<u8>
122        + AsPrimitive<u16>
123        + AsPrimitive<u32>
124        + AsPrimitive<u64>
125        + AsPrimitive<u128>
126        + AsPrimitive<i8>
127        + AsPrimitive<i16>
128        + AsPrimitive<i32>
129        + AsPrimitive<i64>
130        + AsPrimitive<i128>
131        + IntegerType,
132{
133    impl_cast_lossy_body!(integer, cast_lossy, input, to_type)
134}
135
136/// Casts a scalar literal to the given literal type, with lossy truncation.
137fn cast_lossy_scalar_to_type<N: Network>(input: &Scalar<N>, to_type: LiteralType) -> Result<Literal<N>> {
138    impl_cast_lossy_body!(scalar, cast_lossy, input, to_type)
139}