flashbang/message/attributes/
nonce.rs

1use super::*;
2
3/// The NONCE attribute.
4///
5/// See [RFC8489 Section 14.10](https://datatracker.ietf.org/doc/html/rfc8489#section-14.10) for more details.
6#[derive(Clone, PartialEq)]
7pub struct Nonce {
8    nonce: String,
9}
10
11impl Nonce {
12    pub fn new(nonce: impl ToString) -> Self {
13        Self {
14            nonce: nonce.to_string(), // TODO: validate nonce construction
15        }
16    }
17}
18
19impl Attribute for Nonce {
20    const TY: u16 = 0x0015;
21    const SIZE: usize = 0;
22
23    fn encode(&self, buf: &mut [u8], offset: usize) {
24        let bytes = self.nonce.as_bytes();
25        let len = bytes.len();
26        buf[offset..(offset + len)].copy_from_slice(bytes);
27    }
28
29    fn decode(buf: &[u8], meta: &AttributeMeta) -> Self {
30        let nonce = std::str::from_utf8(&buf[meta.offset..(meta.offset + meta.len)])
31            .unwrap()
32            .into();
33
34        Self { nonce }
35    }
36
37    fn size(&self) -> usize {
38        self.nonce.len()
39    }
40}