Repository navigation
Expand file tree
/
Copy pathbase.rs
More file actions
228 lines (214 loc) · 6.64 KB
/
Copy pathbase.rs
File metadata and controls
228 lines (214 loc) · 6.64 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//! Shared directed topology and exact per-profile road and turn costs.
use crate::{
storage,
table::{self, Table},
};
use serde::{Deserialize, Serialize};
type Result<T> = std::result::Result<T, String>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Width {
U8,
U16,
U32,
U64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Column {
pub width: Width,
pub values: Table,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Topology {
pub first: Table,
pub head: Table,
/// The narrowest width that holds every position within an outgoing range. The runtime
/// builds the reverse arcs from `first` and `head` and stores their offsets at this width.
pub offsets: Width,
}
impl Topology {
pub fn tables(&self) -> [&Table; 2] {
[&self.first, &self.head]
}
}
impl Width {
pub fn bytes(self) -> usize {
match self {
Width::U8 => 1,
Width::U16 => 2,
Width::U32 => 4,
Width::U64 => 8,
}
}
/// The narrowest width whose all-ones sentinel no finite value up to `max` collides with.
pub fn holding(max: u64) -> Self {
if max < u8::MAX as u64 {
Width::U8
} else if max < u16::MAX as u64 {
Width::U16
} else if max < u32::MAX as u64 {
Width::U32
} else {
Width::U64
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Weights {
pub road_costs: Column,
pub turns: Column,
}
impl Weights {
pub fn tables(&self) -> [&Table; 2] {
[&self.road_costs.values, &self.turns.values]
}
}
/// All-ones values represent absent costs. A finite value never shares that encoding. The
/// values are read twice: once for the width, once to write them.
pub fn write_column(
values: impl IntoIterator<Item = u64, IntoIter: Clone>,
write: &mut impl FnMut(&[u8]) -> Result<String>,
) -> Result<Column> {
let mut values = values.into_iter();
let (mut len, mut max) = (0usize, 0);
for value in values.clone() {
len += 1;
if value != u64::MAX {
max = max.max(value);
}
}
let width = Width::holding(max);
let mut blocks = Vec::new();
let mut page = Vec::with_capacity(len.min(table::ENTRIES));
loop {
page.clear();
page.extend(values.by_ref().take(table::ENTRIES));
if page.is_empty() {
break;
}
let bytes = match width {
Width::U8 => storage::encode(&page.iter().map(|&v| v as u8).collect::<Vec<_>>())?,
Width::U16 => storage::encode(&page.iter().map(|&v| v as u16).collect::<Vec<_>>())?,
Width::U32 => storage::encode(&page.iter().map(|&v| v as u32).collect::<Vec<_>>())?,
Width::U64 => storage::encode(&page)?,
};
blocks.push(write(&bytes)?);
}
Ok(Column {
width,
values: Table { len: u32::try_from(len).map_err(|_| "Column exceeds u32")?, blocks, pages: None },
})
}
pub fn write_weights(
road_costs: impl IntoIterator<Item = u64, IntoIter: Clone>,
turns: impl IntoIterator<Item = u64, IntoIter: Clone>,
mut write: impl FnMut(&[u8]) -> Result<String>,
) -> Result<Weights> {
Ok(Weights { road_costs: write_column(road_costs, &mut write)?, turns: write_column(turns, &mut write)? })
}
/// The arcs of `road` are `head[first[road]..first[road + 1]]`, ascending without repeats. Turn
/// costs use this arc order.
pub fn write_topology(first: &[u32], head: &[u32], mut write: impl FnMut(&[u8]) -> Result<String>) -> Result<Topology> {
let roads = first.len().saturating_sub(1);
let ordered = first
.windows(2)
.all(|w| head.get(w[0] as usize..w[1] as usize).is_some_and(|arcs| arcs.windows(2).all(|p| p[0] < p[1])));
if roads == 0 || roads >= u32::MAX as usize || first[0] != 0 || first[roads] as usize != head.len() || !ordered {
return Err("Invalid base graph dimensions or arc order".into());
}
if head.iter().any(|&to| to as usize >= roads) {
return Err("Base arc outside road graph".into());
}
let widest = first.windows(2).map(|w| w[1] - w[0]).max().unwrap_or(0);
Ok(Topology {
first: Table::write(first, &mut write)?,
head: Table::write(head, &mut write)?,
offsets: Width::holding(widest.saturating_sub(1) as u64),
})
}
pub enum Numbers {
U8(Vec<u8>),
U16(Vec<u16>),
U32(Vec<u32>),
U64(Vec<u64>),
}
impl Numbers {
pub fn len(&self) -> usize {
match self {
Self::U8(v) => v.len(),
Self::U16(v) => v.len(),
Self::U32(v) => v.len(),
Self::U64(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, index: usize) -> u64 {
match self {
Self::U8(v) => {
if v[index] == u8::MAX {
u64::MAX
} else {
v[index] as u64
}
}
Self::U16(v) => {
if v[index] == u16::MAX {
u64::MAX
} else {
v[index] as u64
}
}
Self::U32(v) => {
if v[index] == u32::MAX {
u64::MAX
} else {
v[index] as u64
}
}
Self::U64(v) => v[index],
}
}
}
impl Topology {
pub fn valid(&self, roads: u32) -> bool {
roads.checked_add(1).is_some_and(|n| self.first.len == n) && self.tables().iter().all(|t| t.valid())
}
}
impl Weights {
pub fn valid(&self, graph: &Topology, roads: u32) -> bool {
self.road_costs.values.len == roads
&& self.turns.values.len == graph.head.len
&& self.tables().iter().all(|t| t.valid())
}
}
pub struct Graph {
pub first: Vec<u32>,
pub head: Vec<u32>,
pub reverse_first: Vec<u32>,
pub reverse_tail: Vec<u32>,
pub reverse_offsets: Numbers,
}
impl Graph {
pub fn reverse_arc(&self, index: usize) -> usize {
self.first[self.reverse_tail[index] as usize] as usize + self.reverse_offsets.get(index) as usize
}
pub fn nodes(&self) -> usize {
self.first.len() - 1
}
}
pub struct Costs {
pub roads: Numbers,
pub turns: std::sync::Arc<Numbers>,
}
impl Costs {
pub fn arc(&self, graph: &Graph, arc: usize) -> u64 {
let road = self.roads.get(graph.head[arc] as usize);
let turn = self.turns.get(arc);
if road == u64::MAX || turn == u64::MAX {
u64::MAX
} else {
road + turn
}
}
}