webgraph-cli 0.5.0

Command line interface for the Rust port of the WebGraph framework (http://webgraph.di.unimi.it/).
Documentation
/*
* SPDX-FileCopyrightText: 2023 Tommaso Fontana
 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/

use crate::{LogIntervalArg, create_parent_dir};
use anyhow::{Context, Result};
use clap::Parser;
use dsi_bitstream::prelude::*;
use dsi_progress_logger::prelude::*;
use log::info;
use std::path::PathBuf;
use webgraph::prelude::*;

#[derive(Parser, Debug)]
#[command(name = "endianness", about = "Inverts the endianness of a graph in the BV format.", long_about = None, next_line_help = true)]
pub struct CliArgs {
    /// The basename of the source graph.​
    pub src: PathBuf,
    /// The basename of the destination graph.​
    pub dst: PathBuf,

    #[clap(flatten)]
    pub log_interval: LogIntervalArg,
}

macro_rules! impl_convert {
    ($args:expr, $src:ty, $dst:ty) => {{
        info!(
            "The source graph was {}-endian, converting to {}-endian",
            <$src>::NAME,
            <$dst>::NAME
        );

        let src_properties_path = $args.src.with_extension(PROPERTIES_EXTENSION);
        let dst_properties_path = $args.dst.with_extension(PROPERTIES_EXTENSION);
        let (num_nodes, num_arcs, comp_flags) = parse_properties::<$src>(&src_properties_path)?;

        let mut pl = progress_logger![
            display_memory = true,
            item_name = "node",
            expected_updates = Some(num_nodes as usize),
            log_interval = $args.log_interval.log_interval,
        ];

        let seq_graph = BvGraphSeq::with_basename(&$args.src)
            .endianness::<$src>()
            .load()
            .with_context(|| format!("Could not load graph {}", $args.src.display()))?;

        let target_graph_path = $args.dst.with_extension(GRAPH_EXTENSION);
        let writer = buf_bit_writer::from_path::<$dst, usize>(&target_graph_path)
            .with_context(|| format!("Could not create {}", target_graph_path.display()))?;
        let encoder = <DynCodesEncoder<$dst, _>>::new(writer, &comp_flags)?;

        // The offsets file contains num_nodes + 1 offsets: a leading zero
        // followed by the end of each successor list, γ-coded as gaps.
        let mut offsets_writer =
            OffsetsWriter::from_path($args.dst.with_extension(OFFSETS_EXTENSION), true)?;

        pl.start("Inverting endianness...");

        let mut iter = seq_graph
            .offset_deg_iter()
            .map_decoder(move |decoder| Converter {
                decoder,
                encoder,
                offset: 0,
            });

        let mut offset = 0;
        for _ in 0..num_nodes {
            iter.next_degree()?;
            let new_offset = iter.get_decoder().offset;
            // usize -> u64 is lossless on all supported targets
            offsets_writer.push((new_offset - offset) as u64)?;
            offset = new_offset;
            pl.light_update();
        }
        let bitstream_len = iter.get_decoder().offset;
        pl.done();
        offsets_writer.flush().context("Could not flush offsets")?;

        // Write properties after recompression so we can use the actual
        // bitstream length instead of reading a "length" property that
        // older graphs may not have.
        std::fs::write(
            &dst_properties_path,
            comp_flags.to_properties::<$dst>(&CompStats {
                num_nodes,
                num_arcs,
                written_bits: bitstream_len as u64,
                ..CompStats::default()
            })?,
        )
        .with_context(|| {
            format!(
                "Could not write properties to {}",
                dst_properties_path.display()
            )
        })?;

        Ok(())
    }};
}

pub fn main(args: CliArgs) -> Result<()> {
    create_parent_dir(&args.dst)?;

    match get_endianness(&args.src)?.as_str() {
        #[cfg(feature = "be_bins")]
        BE::NAME => impl_convert!(args, BE, LE),
        #[cfg(feature = "le_bins")]
        LE::NAME => impl_convert!(args, LE, BE),
        e => anyhow::bail!("Unknown endianness: {}", e),
    }
}