1use crate::constants::{KEY_SIZE_BYTES, READ_CAPABILITY_URN_BYTES, REF_SIZE_BYTES};
2use std::convert::TryFrom;
3use std::convert::TryInto;
4
5pub type Reference = [u8; REF_SIZE_BYTES];
6pub type Key = [u8; KEY_SIZE_BYTES];
7
8#[derive(Copy, Clone, Debug, PartialEq)]
9pub struct ReferenceKeyPair {
10 pub reference: Reference,
11 pub key: Key,
12}
13
14pub struct BlockWithReference {
15 pub block: Vec<u8>,
16 pub reference: Reference,
17}
18
19#[repr(u8)]
20#[derive(Debug, Copy, Clone, PartialEq)]
21pub enum BlockSize {
22 Size1KiB,
23 Size32KiB,
24}
25
26const BLOCK_SIZE_1KIB: u8 = 0x0a;
27const BLOCK_SIZE_32KIB: u8 = 0x0f;
28
29impl TryFrom<u8> for BlockSize {
30 type Error = ();
31
32 fn try_from(v: u8) -> Result<Self, Self::Error> {
33 match v {
34 BLOCK_SIZE_1KIB => Ok(BlockSize::Size1KiB),
35 BLOCK_SIZE_32KIB => Ok(BlockSize::Size32KiB),
36 _ => Err(()),
37 }
38 }
39}
40
41impl Into<u8> for BlockSize {
42 fn into(self) -> u8 {
43 match self {
44 BlockSize::Size1KiB => BLOCK_SIZE_1KIB,
45 BlockSize::Size32KiB => BLOCK_SIZE_32KIB,
46 }
47 }
48}
49
50impl TryFrom<usize> for BlockSize {
51 type Error = ();
52
53 fn try_from(v: usize) -> Result<Self, Self::Error> {
54 match v {
55 1024 => Ok(BlockSize::Size1KiB),
56 32768 => Ok(BlockSize::Size32KiB),
57 _ => Err(()),
58 }
59 }
60}
61
62impl Into<usize> for BlockSize {
63 fn into(self) -> usize {
64 match self {
65 BlockSize::Size1KiB => 1024,
66 BlockSize::Size32KiB => 32768,
67 }
68 }
69}
70
71#[derive(Debug, PartialEq)]
72pub struct ReadCapability {
73 pub block_size: BlockSize,
74 pub level: u8,
75 pub root: ReferenceKeyPair,
76}
77
78impl ReadCapability {
79 pub fn to_bytes(&self) -> Vec<u8> {
80 let mut res: Vec<u8> = Vec::with_capacity(READ_CAPABILITY_URN_BYTES);
81 res.resize(READ_CAPABILITY_URN_BYTES, 0);
82 res[0] = self.block_size.into();
83 res[1] = self.level;
84 res[2..34].copy_from_slice(&self.root.reference);
85 res[34..].copy_from_slice(&self.root.key);
86 res
87 }
88
89 pub fn from_bytes(data: &[u8]) -> Option<ReadCapability> {
90 if data.len() != (REF_SIZE_BYTES + KEY_SIZE_BYTES + 2) {
91 return None;
92 }
93 match data[0].try_into() {
94 Ok(block_size) => {
95 let level = data[1];
96 let mut reference: [u8; REF_SIZE_BYTES] = Default::default();
97 let mut key: [u8; KEY_SIZE_BYTES] = Default::default();
98 key.copy_from_slice(&data[34..66]);
99 reference.copy_from_slice(&data[2..34]);
100 let root = ReferenceKeyPair { reference, key };
101 Some(ReadCapability {
102 block_size,
103 level,
104 root,
105 })
106 }
107 Err(_) => None,
108 }
109 }
110}
111
112pub type BlockStorageError = std::io::Error;
113pub type BlockStorageErrorKind = std::io::ErrorKind;
114pub type BlockStorageGetFn = dyn Fn(Reference) -> Result<Vec<u8>, BlockStorageError>;
115pub type BlockWithReferenceWriteFn = dyn Fn(BlockWithReference) -> Result<usize, BlockStorageError>;
116pub type NodeParsingError = std::io::Error;
117pub type NodeParsingErrorKind = std::io::ErrorKind;