• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vigna / webgraph-rs / 19378243882

14 Nov 2025 09:34PM UTC coverage: 62.201% (+0.06%) from 62.146%
19378243882

push

github

vigna
Back to edition 2021

5251 of 8442 relevant lines covered (62.2%)

29314157.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.3
/webgraph/src/utils/batch_codec/grouped_gaps.rs
1
/*
2
 * SPDX-FileCopyrightText: 2025 Tommaso Fontana
3
 *
4
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
5
 */
6

7
use super::{BitReader, BitWriter};
8
use crate::traits::SortedIterator;
9
use crate::utils::{ArcMmapHelper, MmapHelper, Triple};
10
use crate::{
11
    traits::{BitDeserializer, BitSerializer},
12
    utils::{humanize, BatchCodec},
13
};
14

15
use std::sync::Arc;
16

17
use anyhow::{Context, Result};
18
use dsi_bitstream::prelude::*;
19
use mmap_rs::MmapFlags;
20
use rdst::*;
21

22
#[derive(Clone, Debug)]
23
/// A codec for encoding and decoding batches of triples using grouped gap compression.
24
///
25
/// This codec encodes triples of the form `(src, dst, label)` by grouping edges
26
/// with the same source node, and encoding the gaps between consecutive sources
27
/// and destinations using a specified code (default: gamma). The outdegree
28
/// (number of edges for each source) is also encoded using the specified code.
29
///
30
/// # Type Parameters
31
///
32
/// - `S`: Serializer for the labels, implementing [`BitSerializer`] for the label type.
33
/// - `D`: Deserializer for the labels, implementing [`BitDeserializer`] for the label type.
34
/// - `OUTDEGREE_CODE`: Code used for encoding outdegrees (default: [É£](dsi_bitstream::codes::gamma)).
35
/// - `SRC_CODE`: Code used for encoding source gaps (default: [É£](dsi_bitstream::codes::gamma)).
36
/// - `DST_CODE`: Code used for encoding destination gaps (default: [É£](dsi_bitstream::codes::gamma)).
37
///
38
/// # Encoding Format
39
///
40
/// 1. The batch length is written using delta coding.
41
/// 2. For each group of triples with the same source:
42
///     - The gap from the previous source is encoded.
43
///     - The outdegree (number of edges for this source) is encoded.
44
///     - For each destination:
45
///         - The gap from the previous destination is encoded.
46
///         - The label is serialized.
47
///
48
/// The bit deserializer must be [`Clone`] because we need one for each
49
/// [`GroupedGapsIterator`], and there are possible scenarios in which the
50
/// deserializer might be stateful.
51
pub struct GroupedGapsCodec<
52
    E: Endianness = NE,
53
    S: BitSerializer<E, BitWriter<E>> = (),
54
    D: BitDeserializer<E, BitReader<E>, DeserType = S::SerType> + Clone = (),
55
    const OUTDEGREE_CODE: usize = { dsi_bitstream::dispatch::code_consts::GAMMA },
56
    const SRC_CODE: usize = { dsi_bitstream::dispatch::code_consts::GAMMA },
57
    const DST_CODE: usize = { dsi_bitstream::dispatch::code_consts::DELTA },
58
> where
59
    BitReader<E>: BitRead<E>,
60
    BitWriter<E>: BitWrite<E>,
61
{
62
    /// Serializer for the labels.
63
    pub serializer: S,
64
    /// Deserializer for the labels.
65
    pub deserializer: D,
66

67
    pub _marker: core::marker::PhantomData<E>,
68
}
69

70
impl<E, S, D, const OUTDEGREE_CODE: usize, const SRC_CODE: usize, const DST_CODE: usize>
71
    GroupedGapsCodec<E, S, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
72
where
73
    E: Endianness,
74
    S: BitSerializer<E, BitWriter<E>> + Send + Sync,
75
    D: BitDeserializer<E, BitReader<E>, DeserType = S::SerType> + Send + Sync + Clone,
76
    BitReader<E>: BitRead<E>,
77
    BitWriter<E>: BitWrite<E>,
78
{
79
    /// Creates a new `GroupedGapsCodec` with the given serializer and deserializer.
80
    pub fn new(serializer: S, deserializer: D) -> Self {
×
81
        Self {
82
            serializer,
83
            deserializer,
84
            _marker: core::marker::PhantomData,
85
        }
86
    }
87
}
88

89
impl<
90
        E: Endianness,
91
        S: BitSerializer<E, BitWriter<E>> + Default,
92
        D: BitDeserializer<E, BitReader<E>, DeserType = S::SerType> + Clone + Default,
93
        const OUTDEGREE_CODE: usize,
94
        const SRC_CODE: usize,
95
        const DST_CODE: usize,
96
    > Default for GroupedGapsCodec<E, S, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
97
where
98
    BitReader<E>: BitRead<E>,
99
    BitWriter<E>: BitWrite<E>,
100
{
101
    fn default() -> Self {
131✔
102
        Self {
103
            serializer: S::default(),
262✔
104
            deserializer: D::default(),
131✔
105
            _marker: core::marker::PhantomData,
106
        }
107
    }
108
}
109

110
#[derive(Debug, Clone, Copy)]
111
/// Statistics about the encoding performed by
112
/// [`GapsCodec`](crate::utils::gaps::GapsCodec).
113
pub struct GroupedGapsStats {
114
    /// Total number of triples encoded
115
    pub total_triples: usize,
116
    /// Number of bits used for outdegrees
117
    pub outdegree_bits: usize,
118
    /// Number of bits used for source gaps
119
    pub src_bits: usize,
120
    //// Number of bits used for destination gaps
121
    pub dst_bits: usize,
122
    /// Number of bits used for labels
123
    pub labels_bits: usize,
124
}
125

126
impl core::fmt::Display for GroupedGapsStats {
127
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
32✔
128
        write!(
32✔
129
            f,
32✔
130
            "outdegree: {}B ({:.3} bits / arc), src: {}B ({:.3} bits / arc), dst: {}B ({:.3} bits / arc), labels: {}B ({:.3} bits / arc)",
131
            humanize(self.outdegree_bits as f64 / 8.0),
64✔
132
            self.outdegree_bits as f64 / self.total_triples as f64,
32✔
133
            humanize(self.src_bits as f64 / 8.0),
64✔
134
            self.src_bits as f64 / self.total_triples as f64,
32✔
135
            humanize(self.dst_bits as f64 / 8.0),
64✔
136
            self.dst_bits as f64 / self.total_triples as f64,
32✔
137
            humanize(self.labels_bits as f64 / 8.0),
64✔
138
            self.labels_bits as f64 / self.total_triples as f64,
32✔
139
        )
140
    }
141
}
142

143
impl<E, S, D, const OUTDEGREE_CODE: usize, const SRC_CODE: usize, const DST_CODE: usize> BatchCodec
144
    for GroupedGapsCodec<E, S, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
145
where
146
    E: Endianness,
147
    S: BitSerializer<E, BitWriter<E>> + Send + Sync,
148
    D: BitDeserializer<E, BitReader<E>, DeserType = S::SerType> + Send + Sync + Clone,
149
    S::SerType: Send + Sync + Copy + 'static, // needed by radix sort
150
    BitReader<E>: BitRead<E> + CodesRead<E>,
151
    BitWriter<E>: BitWrite<E> + CodesWrite<E>,
152
{
153
    type Label = S::SerType;
154
    type DecodedBatch = GroupedGapsIterator<E, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>;
155
    type EncodedBatchStats = GroupedGapsStats;
156

157
    fn encode_batch(
459✔
158
        &self,
159
        path: impl AsRef<std::path::Path>,
160
        batch: &mut [((usize, usize), Self::Label)],
161
    ) -> Result<(usize, Self::EncodedBatchStats)> {
162
        let start = std::time::Instant::now();
918✔
163
        Triple::cast_batch_mut(batch).radix_sort_unstable();
918✔
164
        log::debug!("Sorted {} arcs in {:?}", batch.len(), start.elapsed());
459✔
165
        self.encode_sorted_batch(path, batch)
1,836✔
166
    }
167

168
    fn encode_sorted_batch(
459✔
169
        &self,
170
        path: impl AsRef<std::path::Path>,
171
        batch: &[((usize, usize), Self::Label)],
172
    ) -> Result<(usize, Self::EncodedBatchStats)> {
173
        debug_assert!(Triple::cast_batch(batch).is_sorted(), "Batch is not sorted");
1,377✔
174
        // create a batch file where to dump
175
        let file_path = path.as_ref();
1,377✔
176
        let file = std::io::BufWriter::with_capacity(
177
            1 << 16,
459✔
178
            std::fs::File::create(file_path).with_context(|| {
1,377✔
179
                format!(
×
180
                    "Could not create BatchIterator temporary file {}",
×
181
                    file_path.display()
×
182
                )
183
            })?,
184
        );
185
        // create a bitstream to write to the file
186
        let mut stream = <BufBitWriter<E, _>>::new(<WordAdapter<usize, _>>::new(file));
1,836✔
187

188
        // prefix the stream with the length of the batch
189
        // we use a delta code since it'll be a big number most of the time
190
        stream
459✔
191
            .write_delta(batch.len() as u64)
918✔
192
            .context("Could not write length")?;
193

194
        let mut stats = GroupedGapsStats {
195
            total_triples: batch.len(),
459✔
196
            outdegree_bits: 0,
197
            src_bits: 0,
198
            dst_bits: 0,
199
            labels_bits: 0,
200
        };
201
        // dump the triples to the bitstream
202
        let mut prev_src = 0;
918✔
203
        let mut i = 0;
918✔
204
        while i < batch.len() {
4,726,460✔
205
            let ((src, _), _) = batch[i];
4,725,542✔
206
            // write the source gap as gamma
207
            stats.src_bits += ConstCode::<SRC_CODE>
2,362,771✔
208
                .write(&mut stream, (src - prev_src) as _)
7,088,313✔
209
                .with_context(|| format!("Could not write {src} after {prev_src}"))?;
2,362,771✔
210
            // figure out how many edges have this source
211
            let outdegree = batch[i..].iter().take_while(|t| t.0 .0 == src).count();
93,710,435✔
212
            // write the outdegree
213
            stats.outdegree_bits += ConstCode::<OUTDEGREE_CODE>
2,362,771✔
214
                .write(&mut stream, outdegree as _)
7,088,313✔
215
                .with_context(|| format!("Could not write outdegree {outdegree} for {src}"))?;
2,362,771✔
216

217
            // encode the destinations
218
            let mut prev_dst = 0;
4,725,542✔
219
            for _ in 0..outdegree {
2,362,771✔
220
                let ((_, dst), label) = &batch[i];
115,757,895✔
221
                // write the destination gap as gamma
222
                stats.dst_bits += ConstCode::<DST_CODE>
38,585,965✔
223
                    .write(&mut stream, (dst - prev_dst) as _)
115,757,895✔
224
                    .with_context(|| format!("Could not write {dst} after {prev_dst}"))?;
38,585,965✔
225
                // write the label
226
                stats.labels_bits += self
38,585,965✔
227
                    .serializer
38,585,965✔
228
                    .serialize(label, &mut stream)
115,757,895✔
229
                    .context("Could not serialize label")?;
38,585,965✔
230
                prev_dst = *dst;
38,585,965✔
231
                i += 1;
38,585,965✔
232
            }
233
            prev_src = src;
2,362,771✔
234
        }
235
        // flush the stream and reset the buffer
236
        stream.flush().context("Could not flush stream")?;
1,377✔
237

238
        let total_bits = stats.outdegree_bits + stats.src_bits + stats.dst_bits + stats.labels_bits;
918✔
239
        Ok((total_bits, stats))
459✔
240
    }
241

242
    fn decode_batch(&self, path: impl AsRef<std::path::Path>) -> Result<Self::DecodedBatch> {
162✔
243
        // open the file
244
        let mut stream = <BufBitReader<E, _>>::new(MemWordReader::new(ArcMmapHelper(Arc::new(
648✔
245
            MmapHelper::mmap(
162✔
246
                path.as_ref(),
324✔
247
                MmapFlags::TRANSPARENT_HUGE_PAGES | MmapFlags::SEQUENTIAL,
162✔
248
            )
249
            .with_context(|| format!("Could not mmap {}", path.as_ref().display()))?,
162✔
250
        ))));
251

252
        // read the length of the batch (first value in the stream)
253
        let len = stream.read_delta().context("Could not read length")? as usize;
648✔
254

255
        // create the iterator
256
        Ok(GroupedGapsIterator {
162✔
257
            deserializer: self.deserializer.clone(),
486✔
258
            stream,
162✔
259
            len,
162✔
260
            current: 0,
162✔
261
            src: 0,
162✔
262
            dst_left: 0,
162✔
263
            prev_dst: 0,
162✔
264
        })
265
    }
266
}
267

268
#[derive(Clone, Debug)]
269
/// An iterator over triples encoded with gaps, this is returned by [`GroupedGapsCodec`].
270
pub struct GroupedGapsIterator<
271
    E: Endianness = NE,
272
    D: BitDeserializer<E, BitReader<E>> = (),
273
    const OUTDEGREE_CODE: usize = { dsi_bitstream::dispatch::code_consts::GAMMA },
274
    const SRC_CODE: usize = { dsi_bitstream::dispatch::code_consts::GAMMA },
275
    const DST_CODE: usize = { dsi_bitstream::dispatch::code_consts::GAMMA },
276
> where
277
    BitReader<E>: BitRead<E>,
278
    BitWriter<E>: BitWrite<E>,
279
{
280
    /// Deserializer for the labels
281
    deserializer: D,
282
    /// Bitstream to read from
283
    stream: BitReader<E>,
284
    /// Length of the iterator (number of triples)
285
    len: usize,
286
    /// Current position in the iterator
287
    current: usize,
288
    /// Current source node
289
    src: usize,
290
    /// Number of destinations left for the current source
291
    dst_left: usize,
292
    /// Previous destination node
293
    prev_dst: usize,
294
}
295

296
unsafe impl<
297
        E: Endianness,
298
        D: BitDeserializer<E, BitReader<E>>,
299
        const OUTDEGREE_CODE: usize,
300
        const SRC_CODE: usize,
301
        const DST_CODE: usize,
302
    > SortedIterator for GroupedGapsIterator<E, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
303
where
304
    BitReader<E>: BitRead<E> + CodesRead<E>,
305
    BitWriter<E>: BitWrite<E> + CodesWrite<E>,
306
{
307
}
308

309
impl<
310
        E: Endianness,
311
        D: BitDeserializer<E, BitReader<E>>,
312
        const OUTDEGREE_CODE: usize,
313
        const SRC_CODE: usize,
314
        const DST_CODE: usize,
315
    > Iterator for GroupedGapsIterator<E, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
316
where
317
    BitReader<E>: BitRead<E> + CodesRead<E>,
318
    BitWriter<E>: BitWrite<E> + CodesWrite<E>,
319
{
320
    type Item = ((usize, usize), D::DeserType);
321
    fn next(&mut self) -> Option<Self::Item> {
67,942,779✔
322
        if self.current >= self.len {
67,942,779✔
323
            return None;
151✔
324
        }
325
        if self.dst_left == 0 {
67,942,628✔
326
            // read a new source
327
            let src_gap = ConstCode::<SRC_CODE>.read(&mut self.stream).ok()?;
20,350,085✔
328
            self.src += src_gap as usize;
4,070,017✔
329
            // read the outdegree
330
            self.dst_left = ConstCode::<OUTDEGREE_CODE>.read(&mut self.stream).ok()? as usize;
16,280,068✔
331
            self.prev_dst = 0;
4,070,017✔
332
        }
333

334
        let dst_gap = ConstCode::<DST_CODE>.read(&mut self.stream).ok()?;
339,713,140✔
335
        let label = self.deserializer.deserialize(&mut self.stream).ok()?;
339,713,140✔
336
        self.prev_dst += dst_gap as usize;
67,942,628✔
337
        self.current += 1;
67,942,628✔
338
        self.dst_left -= 1;
67,942,628✔
339
        Some(((self.src, self.prev_dst), label))
67,942,628✔
340
    }
341

342
    fn size_hint(&self) -> (usize, Option<usize>) {
×
343
        (self.len(), Some(self.len()))
×
344
    }
345
}
346

347
impl<
348
        E: Endianness,
349
        D: BitDeserializer<E, BitReader<E>>,
350
        const OUTDEGREE_CODE: usize,
351
        const SRC_CODE: usize,
352
        const DST_CODE: usize,
353
    > ExactSizeIterator for GroupedGapsIterator<E, D, OUTDEGREE_CODE, SRC_CODE, DST_CODE>
354
where
355
    BitReader<E>: BitRead<E> + CodesRead<E>,
356
    BitWriter<E>: BitWrite<E> + CodesWrite<E>,
357
{
358
    fn len(&self) -> usize {
×
359
        self.len - self.current
×
360
    }
361
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc