dusk_cdf/element/
scalar.rs1use std::io;
2use std::ops::{Deref, DerefMut};
3
4use crate::{
5 Config, DecodableElement, DecoderContext, Element, EncodableElement, EncoderContext, Preamble,
6};
7
8#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Scalar {
13 scalar: [u8; Self::LEN],
14}
15
16impl Scalar {
17 pub const LEN: usize = 32;
19}
20
21impl From<[u8; Scalar::LEN]> for Scalar {
22 fn from(scalar: [u8; Self::LEN]) -> Self {
23 Self { scalar }
24 }
25}
26
27impl AsRef<[u8]> for Scalar {
28 fn as_ref(&self) -> &[u8] {
29 &self.scalar
30 }
31}
32
33impl Deref for Scalar {
34 type Target = [u8; Self::LEN];
35
36 fn deref(&self) -> &Self::Target {
37 &self.scalar
38 }
39}
40
41impl DerefMut for Scalar {
42 fn deref_mut(&mut self) -> &mut Self::Target {
43 &mut self.scalar
44 }
45}
46
47impl Element for Scalar {
48 fn len(ctx: &Config) -> usize {
49 if ctx.zeroed_scalar_values {
50 0
51 } else {
52 Self::LEN
53 }
54 }
55
56 fn validate(&self, _preamble: &Preamble) -> io::Result<()> {
57 Ok(())
58 }
59}
60
61impl EncodableElement for Scalar {
62 fn to_buffer(&self, ctx: &mut EncoderContext, buf: &mut [u8]) {
63 if !ctx.config().zeroed_scalar_values {
64 let buf = &mut buf[..Self::LEN];
65
66 buf.copy_from_slice(&self.scalar);
67 }
68 }
69}
70
71impl DecodableElement for Scalar {
72 fn try_from_buffer_in_place<'b>(
73 &mut self,
74 ctx: &DecoderContext,
75 buf: &'b [u8],
76 ) -> io::Result<()> {
77 Self::validate_buffer(ctx.config(), buf)?;
78
79 if !ctx.config().zeroed_scalar_values {
80 self.scalar.copy_from_slice(&buf[..Self::LEN]);
81 }
82
83 Ok(())
84 }
85}