1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::io;
use std::ops::{Deref, DerefMut};
use crate::{Config, Context, ContextUnit, Element, Preamble};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Scalar {
scalar: [u8; Self::LEN],
}
impl Scalar {
pub const LEN: usize = 32;
}
impl From<[u8; Scalar::LEN]> for Scalar {
fn from(scalar: [u8; Self::LEN]) -> Self {
Self { scalar }
}
}
impl AsRef<[u8]> for Scalar {
fn as_ref(&self) -> &[u8] {
&self.scalar
}
}
impl Deref for Scalar {
type Target = [u8; Self::LEN];
fn deref(&self) -> &Self::Target {
&self.scalar
}
}
impl DerefMut for Scalar {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.scalar
}
}
impl Element for Scalar {
type Config = Config;
fn zeroed() -> Self {
Self::default()
}
fn len(config: &Self::Config) -> usize {
if config.zeroed_scalar_values {
0
} else {
Self::LEN
}
}
fn to_buffer(&self, config: &Self::Config, _context: &mut ContextUnit, buf: &mut [u8]) {
if !config.zeroed_scalar_values {
let buf = &mut buf[..Self::LEN];
buf.copy_from_slice(&self.scalar);
}
}
fn try_from_buffer_in_place<S>(
&mut self,
config: &Self::Config,
_context: &mut Context<S>,
buf: &[u8],
) -> io::Result<()> {
Self::validate_buffer_len(config, buf.len())?;
if !config.zeroed_scalar_values {
self.scalar.copy_from_slice(&buf[..Self::LEN]);
}
Ok(())
}
fn validate(&self, _config: &Preamble) -> io::Result<()> {
Ok(())
}
}
#[test]
fn bytes_encode_works() {
let mut bytes = [0xfa; Scalar::LEN];
let mut scalar = Scalar::from(bytes);
assert_eq!(&bytes, scalar.as_ref());
assert_eq!(bytes, *scalar);
assert_eq!(&mut bytes, scalar.deref_mut());
}
#[test]
fn encode_zeroed_len_is_consitent() {
let config = *Config::default().with_zeroed_scalar_values(false);
let len = <Scalar as Element>::len(&config);
assert_eq!(Scalar::LEN, len);
let config = *Config::default().with_zeroed_scalar_values(true);
let len = <Scalar as Element>::len(&config);
assert_eq!(0, len);
}