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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use parking_lot::Mutex;
use std::{convert::TryInto, sync::Arc};
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
struct Inner {
counter: Vec<u16>,
}
#[derive(Clone, Debug)]
pub struct Generator {
current: Arc<Mutex<Inner>>,
}
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Path {
inner: Vec<u16>,
}
#[derive(Debug)]
pub enum PathError {
Format,
Length,
Range,
}
impl Inner {
fn next(&mut self) -> Vec<u16> {
let mut modified_depth = 0;
for (depth, count) in self.counter.iter_mut().enumerate().rev() {
if *count < 999 {
*count += 1;
modified_depth = depth;
break;
} else {
*count = 0;
}
}
if modified_depth == 0 {
self.counter.push(0);
}
self.counter.clone()
}
}
impl Generator {
pub fn new() -> Self {
Self::from_existing(Path { inner: vec![] })
}
pub fn from_existing(existing: Path) -> Self {
Generator {
current: Arc::new(Mutex::new(Inner {
counter: existing.inner,
})),
}
}
pub fn next(&self) -> Path {
let inner = self.current.lock().next();
Path { inner }
}
}
impl Path {
pub fn from_be_bytes(bytes: Vec<u8>) -> Result<Self, PathError> {
let inner = bytes
.chunks(2)
.map(|chunk| {
let be_bytes: [u8; 2] = chunk.try_into().map_err(|_| PathError::Length)?;
Ok(u16::from_be_bytes(be_bytes))
})
.collect::<Result<_, PathError>>()?;
Self::from_vec(inner)
}
pub fn to_be_bytes(&self) -> Vec<u8> {
self.inner
.iter()
.flat_map(|num| num.to_be_bytes())
.collect()
}
pub fn into_inner(self) -> Vec<u16> {
self.inner
}
pub fn from_vec(inner: Vec<u16>) -> Result<Self, PathError> {
if inner.is_empty() {
return Ok(Path { inner });
}
if inner.len().saturating_sub(1) != inner[0].into() {
return Err(PathError::Format);
}
for elem in inner.iter() {
if *elem > 999 {
return Err(PathError::Range);
}
}
Ok(Path { inner })
}
pub fn to_strings(&self) -> Vec<String> {
self.inner
.iter()
.map(|dir| {
if *dir > 99 {
format!("{}", dir)
} else if *dir > 9 {
format!("0{}", dir)
} else {
format!("00{}", dir)
}
})
.collect()
}
}
impl std::fmt::Display for PathError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PathError::Format => {
write!(f, "Invalid path format")
}
PathError::Length => {
write!(f, "Invalid segment length")
}
PathError::Range => {
write!(f, "Invalid segment format")
}
}
}
}
impl std::error::Error for PathError {}