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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//! Compressed Sparse Row adjacency representation.
//!
//! For node i, its neighbors are `targets[offsets[i]..offsets[i+1]]`.
//! Uses u32 for both offsets and targets (max ~4B nodes/edges per table).
/// Compressed Sparse Row adjacency structure.
///
/// Stores a directed graph in two flat arrays: `offsets` (one per node + 1
/// sentinel) and `targets` (concatenated neighbor lists). This layout is
/// cache-friendly for forward traversal and has O(1) neighbor access.
#[derive(Debug, Clone)]
pub struct CsrAdjacency {
/// One entry per node plus a trailing sentinel.
/// `offsets[i]..offsets[i+1]` is the range in `targets` for node `i`.
offsets: Vec<u32>,
/// Concatenated target node offsets, grouped by source.
targets: Vec<u32>,
/// Optional per-edge auxiliary data, parallel to `targets`.
/// For backward CSRs, stores the corresponding forward CSR position.
edge_data: Option<Vec<u32>>,
}
impl CsrAdjacency {
/// Builds a CSR from pre-sorted `(src, dst)` pairs.
///
/// The input **must** be sorted by `src` (ties broken arbitrarily).
/// `num_nodes` is the total number of source nodes, nodes beyond the
/// highest `src` in `edges` are treated as having zero out-degree.
///
/// # Panics
///
/// Panics if `edges` is not sorted by source.
#[must_use]
pub fn from_sorted_edges(num_nodes: usize, edges: &[(u32, u32)]) -> Self {
assert!(
edges.windows(2).all(|w| w[0].0 <= w[1].0),
"edges must be sorted by source"
);
let mut offsets = vec![0u32; num_nodes + 1];
// Count edges per source.
for &(src, _) in edges {
offsets[src as usize + 1] += 1;
}
// Prefix sum.
for i in 1..offsets.len() {
offsets[i] += offsets[i - 1];
}
let targets: Vec<u32> = edges.iter().map(|&(_, dst)| dst).collect();
Self {
offsets,
targets,
edge_data: None,
}
}
/// Sets optional per-edge auxiliary data parallel to `targets`.
///
/// # Panics
///
/// Panics if `data.len()` does not equal `self.targets.len()`.
pub fn set_edge_data(&mut self, data: Vec<u32>) {
assert_eq!(
data.len(),
self.targets.len(),
"edge_data length must equal targets length"
);
self.edge_data = Some(data);
}
/// Returns `true` if per-edge auxiliary data has been set.
#[must_use]
pub fn has_edge_data(&self) -> bool {
self.edge_data.is_some()
}
/// Returns the auxiliary data for the edge at the given CSR position.
///
/// Returns `None` if no edge data has been set, or if the position is
/// out of bounds.
#[must_use]
pub fn edge_data_at(&self, position: usize) -> Option<u32> {
self.edge_data.as_ref()?.get(position).copied()
}
/// Returns the number of nodes in this CSR.
#[must_use]
pub fn num_nodes(&self) -> usize {
// offsets has num_nodes + 1 entries.
self.offsets.len().saturating_sub(1)
}
/// Returns the total number of edges in this CSR.
#[must_use]
pub fn num_edges(&self) -> usize {
self.targets.len()
}
/// Returns the neighbors (target offsets) of the given node.
///
/// Returns an empty slice if `node_offset` is out of range.
#[inline]
#[must_use]
pub fn neighbors(&self, node_offset: u32) -> &[u32] {
let i = node_offset as usize;
if i + 1 >= self.offsets.len() {
return &[];
}
let start = self.offsets[i] as usize;
let end = self.offsets[i + 1] as usize;
&self.targets[start..end]
}
/// Returns the out-degree of the given node.
///
/// Returns 0 if `node_offset` is out of range.
#[inline]
#[must_use]
pub fn degree(&self, node_offset: u32) -> usize {
self.neighbors(node_offset).len()
}
/// Finds the source node for a given CSR position via binary search.
///
/// The CSR position is an index into `targets`. This method returns the
/// node offset `i` such that `offsets[i] <= position < offsets[i+1]`.
/// Returns `None` if `position` is out of range.
#[must_use]
pub fn source_for_position(&self, position: u32) -> Option<u32> {
if position as usize >= self.targets.len() {
return None;
}
// Binary search: find the last offset <= position.
// offsets is monotonically non-decreasing with len = num_nodes + 1.
let num_nodes = self.num_nodes();
let mut lo = 0usize;
let mut hi = num_nodes;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if self.offsets[mid + 1] <= position {
lo = mid + 1;
} else {
hi = mid;
}
}
// reason: CSR position index fits u32
#[allow(clippy::cast_possible_truncation)]
Some(lo as u32)
}
/// Returns the starting CSR position (index into `targets`) for the given node.
///
/// This is `offsets[node_offset]`, the index at which this node's
/// neighbor list begins in the targets array.
///
/// Returns 0 if `node_offset` is out of range.
#[inline]
#[must_use]
pub fn offset_of(&self, node_offset: u32) -> u32 {
let i = node_offset as usize;
if i >= self.offsets.len() {
return 0;
}
self.offsets[i]
}
/// Reconstructs from pre-built raw parts.
///
/// Used by section deserialization.
#[must_use]
pub fn from_raw_parts(
offsets: Vec<u32>,
targets: Vec<u32>,
edge_data: Option<Vec<u32>>,
) -> Self {
Self {
offsets,
targets,
edge_data,
}
}
/// Returns the raw offsets array.
#[must_use]
pub fn offsets(&self) -> &[u32] {
&self.offsets
}
/// Returns the raw targets array.
#[must_use]
pub fn targets(&self) -> &[u32] {
&self.targets
}
/// Returns the raw edge_data array, if set.
#[must_use]
pub fn edge_data(&self) -> Option<&[u32]> {
self.edge_data.as_deref()
}
/// Serializes this CSR to a byte buffer.
pub fn write_to(&self, buf: &mut Vec<u8>) {
// offsets
write_usize_as_u32(buf, self.offsets.len());
for &o in &self.offsets {
buf.extend_from_slice(&o.to_le_bytes());
}
// targets
write_usize_as_u32(buf, self.targets.len());
for &t in &self.targets {
buf.extend_from_slice(&t.to_le_bytes());
}
// edge_data
match &self.edge_data {
Some(ed) => {
buf.push(1);
write_usize_as_u32(buf, ed.len());
for &d in ed {
buf.extend_from_slice(&d.to_le_bytes());
}
}
None => buf.push(0),
}
}
/// Deserializes a CSR from a byte buffer at the given offset.
///
/// # Errors
///
/// Returns an error string if data is truncated.
pub fn read_from(data: &[u8], pos: &mut usize) -> Result<Self, &'static str> {
let offsets_len = read_u32_le(data, pos)? as usize;
let mut offsets = Vec::with_capacity(offsets_len);
for _ in 0..offsets_len {
offsets.push(read_u32_le(data, pos)?);
}
let targets_len = read_u32_le(data, pos)? as usize;
let mut targets = Vec::with_capacity(targets_len);
for _ in 0..targets_len {
targets.push(read_u32_le(data, pos)?);
}
let has_edge_data = *data.get(*pos).ok_or("truncated edge_data flag")?;
*pos += 1;
let edge_data = if has_edge_data == 1 {
let ed_len = read_u32_le(data, pos)? as usize;
let mut ed = Vec::with_capacity(ed_len);
for _ in 0..ed_len {
ed.push(read_u32_le(data, pos)?);
}
Some(ed)
} else {
None
};
Ok(Self::from_raw_parts(offsets, targets, edge_data))
}
/// Returns the approximate heap memory usage in bytes.
#[must_use]
pub fn memory_bytes(&self) -> usize {
self.offsets.len() * std::mem::size_of::<u32>()
+ self.targets.len() * std::mem::size_of::<u32>()
+ self
.edge_data
.as_ref()
.map_or(0, |d| d.len() * std::mem::size_of::<u32>())
}
}
fn write_usize_as_u32(buf: &mut Vec<u8>, v: usize) {
let n = u32::try_from(v).expect("value exceeds u32::MAX in CSR serialization");
buf.extend_from_slice(&n.to_le_bytes());
}
fn read_u32_le(data: &[u8], pos: &mut usize) -> Result<u32, &'static str> {
if *pos + 4 > data.len() {
return Err("truncated u32");
}
let v = u32::from_le_bytes([data[*pos], data[*pos + 1], data[*pos + 2], data[*pos + 3]]);
*pos += 4;
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_csr() {
// 3 nodes, edges: 0->1, 0->2, 1->2
let edges = vec![(0u32, 1u32), (0, 2), (1, 2)];
let csr = CsrAdjacency::from_sorted_edges(3, &edges);
assert_eq!(csr.num_nodes(), 3);
assert_eq!(csr.num_edges(), 3);
// Node 0: neighbors [1, 2]
assert_eq!(csr.neighbors(0), &[1, 2]);
assert_eq!(csr.degree(0), 2);
// Node 1: neighbors [2]
assert_eq!(csr.neighbors(1), &[2]);
assert_eq!(csr.degree(1), 1);
// Node 2: no neighbors
assert_eq!(csr.neighbors(2), &[] as &[u32]);
assert_eq!(csr.degree(2), 0);
}
#[test]
fn test_source_for_position() {
// 3 nodes, edges: 0->1, 0->2, 1->2
// CSR targets: [1, 2, 2]
// offsets: [0, 2, 3, 3]
// position 0 -> source 0 (0->1)
// position 1 -> source 0 (0->2)
// position 2 -> source 1 (1->2)
let edges = vec![(0u32, 1u32), (0, 2), (1, 2)];
let csr = CsrAdjacency::from_sorted_edges(3, &edges);
assert_eq!(csr.source_for_position(0), Some(0));
assert_eq!(csr.source_for_position(1), Some(0));
assert_eq!(csr.source_for_position(2), Some(1));
// Out of range.
assert_eq!(csr.source_for_position(3), None);
assert_eq!(csr.source_for_position(100), None);
}
#[test]
fn test_empty_graph() {
// 0 nodes, 0 edges.
let csr = CsrAdjacency::from_sorted_edges(0, &[]);
assert_eq!(csr.num_nodes(), 0);
assert_eq!(csr.num_edges(), 0);
assert_eq!(csr.source_for_position(0), None);
assert_eq!(csr.memory_bytes(), 4); // 1 offset entry (sentinel)
}
}