snarkvm_console_program/data/literal/cast/scalar.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
16use super::*;
17
18impl<E: Environment> Cast<Address<E>> for Scalar<E> {
19 /// Casts a `Scalar` to an `Address`.
20 ///
21 /// This operation converts the scalar to a field element, and then attempts to recover
22 /// the group element by treating the field element as an x-coordinate. The group element
23 /// is then converted to an address.
24 ///
25 /// To cast arbitrary scalars to addresses, use `Scalar::cast_lossy`.
26 #[inline]
27 fn cast(&self) -> Result<Address<E>> {
28 let field: Field<E> = self.cast()?;
29 Address::from_field(&field)
30 }
31}
32
33impl<E: Environment> Cast<Boolean<E>> for Scalar<E> {
34 /// Casts a `Scalar` to a `Boolean`, if the scalar is zero or one.
35 ///
36 /// To cast arbitrary scalars to booleans, use `Scalar::cast_lossy`.
37 #[inline]
38 fn cast(&self) -> Result<Boolean<E>> {
39 if self.is_zero() {
40 Ok(Boolean::new(false))
41 } else if self.is_one() {
42 Ok(Boolean::new(true))
43 } else {
44 bail!("Failed to convert scalar to boolean: scalar is not zero or one")
45 }
46 }
47}
48
49impl<E: Environment> Cast<Group<E>> for Scalar<E> {
50 /// Casts a `Scalar` to a `Group`.
51 ///
52 /// This operation converts the scalar to a field element, and then attempts to recover
53 /// the group element by treating the field element as an x-coordinate.
54 ///
55 /// To cast arbitrary scalars to groups, use `Scalar::cast_lossy`.
56 #[inline]
57 fn cast(&self) -> Result<Group<E>> {
58 let field: Field<E> = self.cast()?;
59 Group::from_field(&field)
60 }
61}
62
63impl<E: Environment> Cast<Field<E>> for Scalar<E> {
64 /// Casts a `Scalar` to a `Field`.
65 #[inline]
66 fn cast(&self) -> Result<Field<E>> {
67 self.to_field()
68 }
69}
70
71impl<E: Environment, I: IntegerType> Cast<Integer<E, I>> for Scalar<E> {
72 /// Casts a `Scalar` to an `Integer`, if the scalar is in the range of the integer.
73 ///
74 /// To cast arbitrary scalars to integers, via truncation, use `Scalar::cast_lossy`.
75 #[inline]
76 fn cast(&self) -> Result<Integer<E, I>> {
77 let bits_le = self.to_bits_le();
78 Integer::<E, I>::from_bits_le(&bits_le)
79 }
80}
81
82impl<E: Environment> Cast<Scalar<E>> for Scalar<E> {
83 /// Casts a `Scalar` to a `Scalar`.
84 #[inline]
85 fn cast(&self) -> Result<Scalar<E>> {
86 Ok(*self)
87 }
88}