webgraph-cli 0.5.0

Command line interface for the Rust port of the WebGraph framework (http://webgraph.di.unimi.it/).
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
/*
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 */

#![doc = include_str!("../README.md")]
#![deny(unstable_features)]
#![deny(trivial_casts)]
#![deny(unconditional_recursion)]
#![deny(clippy::empty_loop)]
#![deny(unreachable_code)]
#![deny(unreachable_pub)]
#![deny(unreachable_patterns)]
#![deny(unused_macro_rules)]
#![deny(unused_doc_comments)]
#![allow(clippy::type_complexity)]

use anyhow::{Context, Result, anyhow, bail, ensure};
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use dsi_bitstream::dispatch::Codes;
use dsi_bitstream::traits::Endianness;
use epserde::deser::{Deserialize, Flags, MemCase};
use epserde::ser::Serialize;
use num_traits::{FromBytes, ToBytes};
use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use std::time::SystemTime;
use sux::bits::BitFieldVec;
use sux::utils::PrimitiveUnsignedExt;
use value_traits::slices::SliceByValue;
use webgraph::graphs::par_graphs::ParGraph;
#[cfg(target_pointer_width = "64")]
use webgraph::prelude::JavaPermutation;
use webgraph::prelude::{BvCompConf, CompFlags, DCF, DEG_CUMUL_EXTENSION, SequentialLabeling};
use webgraph::traits::{IntoParLenders, NodeLabelsLender};
use webgraph::utils::{Granularity, MemoryUsage};

macro_rules! SEQ_PROC_WARN {
    () => {"Processing the graph sequentially: for parallel processing please build the Elias–Fano offsets list using 'webgraph build ef {}'"}
}

#[cfg(not(any(feature = "le_bins", feature = "be_bins")))]
compile_error!("At least one of the features `le_bins` or `be_bins` must be enabled.");

/// Dispatches on the endianness of the graph with basename `$basename`,
/// evaluating `$body` with `$E` bound to the corresponding [`Endianness`]
/// type.
///
/// The enclosing function must return a [`Result`], as the macro returns an
/// error if the endianness cannot be read or is not supported by the binary.
///
/// [`Endianness`]: dsi_bitstream::traits::Endianness
macro_rules! dispatch_endianness {
    ($basename:expr, |$E:ident| $body:expr) => {
        match ::webgraph::prelude::get_endianness($basename)?.as_str() {
            #[cfg(feature = "be_bins")]
            e if e
                == <::dsi_bitstream::traits::BE as ::dsi_bitstream::traits::Endianness>::NAME =>
            {
                type $E = ::dsi_bitstream::traits::BE;
                $body
            }
            #[cfg(feature = "le_bins")]
            e if e
                == <::dsi_bitstream::traits::LE as ::dsi_bitstream::traits::Endianness>::NAME =>
            {
                type $E = ::dsi_bitstream::traits::LE;
                $body
            }
            e => ::anyhow::bail!("Unknown endianness: {}", e),
        }
    };
}

/// Calls [`par_comp`] dispatching on a runtime endianness string.
///
/// The macro returns a [`Result`] with the output of the call if the endianness
/// is recognized, and an error otherwise.
///
/// # Arguments
///
/// * `config` - the [`BvCompConf`] to call [`par_comp`] on;
///
/// * `graph` - an implementation of [`IntoParLenders`] with `Label = usize`;
///
/// * `endianness` - a string specifying the endianness type to use for the call;
///   it must implement `AsRef<str>`, and must be equal to the name of one of the
///   endianness types supported by the binary.
///
/// [`par_comp`]: webgraph::prelude::BvCompConf::par_comp
/// [`BvCompConf`]: webgraph::prelude::BvCompConf
/// [`IntoParLenders`]: webgraph::prelude::IntoParLenders
#[macro_export]
macro_rules! par_comp {
    ($config:expr, $graph:expr, $endianness:expr) => {
        // Dispatch to a helper function so that each endianness gets its
        // own monomorphization without the `impl Trait` reference appearing
        // in multiple arms of a single `match` (which would cause the
        // borrow checker to require `'static`).
        $crate::__par_comp_dispatch(&mut $config, $graph, $endianness.as_str())
    };
}

/// Implementation detail of [`par_comp!`]. Dispatches to the correct
/// endianness-specific [`par_comp`].
///
/// [`par_comp`]: webgraph::prelude::BvCompConf::par_comp
pub fn __par_comp_dispatch<
    PL: dsi_progress_logger::ProgressLog,
    G: for<'a> IntoParLenders<ParLender: NodeLabelsLender<'a, Label = usize>>,
>(
    config: &mut webgraph::prelude::BvCompConf<PL>,
    graph: G,
    endianness: &str,
) -> anyhow::Result<u64> {
    use dsi_bitstream::prelude::Endianness;
    #[cfg(feature = "be_bins")]
    if endianness == dsi_bitstream::prelude::BE::NAME {
        return config.par_comp::<dsi_bitstream::prelude::BE, _>(graph);
    }
    #[cfg(feature = "le_bins")]
    if endianness == dsi_bitstream::prelude::LE::NAME {
        return config.par_comp::<dsi_bitstream::prelude::LE, _>(graph);
    }
    anyhow::bail!("Unknown endianness: {}", endianness)
}

pub mod build_info {
    include!(concat!(env!("OUT_DIR"), "/built.rs"));

    pub fn version_string() -> String {
        format!(
            "{}
git info: {} {} {}
build info: built on {} for {} with {}",
            PKG_VERSION,
            GIT_VERSION.unwrap_or(""),
            GIT_COMMIT_HASH.unwrap_or(""),
            match GIT_DIRTY {
                None => "",
                Some(true) => "(dirty)",
                Some(false) => "(clean)",
            },
            BUILD_DATE,
            TARGET,
            RUSTC_VERSION
        )
    }
}

/// Enum for instantaneous codes.
///
/// It is used to implement [`ValueEnum`] here instead of in [`dsi_bitstream`].
///
/// For CLI ergonomics and compatibility, these codes must be the same as those
/// appearing in [`CompFlags::code_from_str`].​
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum PrivCode {
    Unary,
    Gamma,
    Delta,
    Omega,
    Zeta1,
    Zeta2,
    Zeta3,
    Zeta4,
    Zeta5,
    Zeta6,
    Zeta7,
    Pi1,
    Pi2,
    Pi3,
    Pi4,
}

impl From<PrivCode> for Codes {
    fn from(value: PrivCode) -> Self {
        match value {
            PrivCode::Unary => Codes::Unary,
            PrivCode::Gamma => Codes::Gamma,
            PrivCode::Delta => Codes::Delta,
            PrivCode::Omega => Codes::Omega,
            PrivCode::Zeta1 => Codes::Zeta(1),
            PrivCode::Zeta2 => Codes::Zeta(2),
            PrivCode::Zeta3 => Codes::Zeta(3),
            PrivCode::Zeta4 => Codes::Zeta(4),
            PrivCode::Zeta5 => Codes::Zeta(5),
            PrivCode::Zeta6 => Codes::Zeta(6),
            PrivCode::Zeta7 => Codes::Zeta(7),
            PrivCode::Pi1 => Codes::Pi(1),
            PrivCode::Pi2 => Codes::Pi(2),
            PrivCode::Pi3 => Codes::Pi(3),
            PrivCode::Pi4 => Codes::Pi(4),
        }
    }
}

/// Shared CLI arguments for reading files containing arcs.​
#[derive(Args, Debug)]
pub struct ArcsArgs {
    #[arg(long, default_value_t = '#')]
    /// Ignore lines that start with this symbol.​
    pub line_comment_symbol: char,

    #[arg(long, default_value_t = 0)]
    /// Number of lines to skip, ignoring comment lines.​
    pub lines_to_skip: usize,

    #[arg(long)]
    /// Maximum number of lines to parse, after skipping and ignoring comment
    /// lines.​
    pub max_arcs: Option<usize>,

    #[arg(long, default_value_t = '\t')]
    /// The column separator.​
    pub separator: char,

    #[arg(long, default_value_t = 0)]
    /// The index of the column containing the source node of an arc.​
    pub source_column: usize,

    #[arg(long, default_value_t = 1)]
    /// The index of the column containing the target node of an arc.​
    pub target_column: usize,

    #[arg(long, default_value_t = false)]
    /// Treat source and target values as string labels rather than numeric
    /// node identifiers.​
    pub labels: bool,
}

/// Parses the number of threads from a string.
///
/// This function is meant to be used with `#[arg(...,  value_parser =
/// num_threads_parser)]`.
pub fn num_threads_parser(arg: &str) -> Result<usize> {
    let num_threads = arg.parse::<usize>()?;
    ensure!(num_threads > 0, "Number of threads must be greater than 0");
    Ok(num_threads)
}

/// Shared CLI arguments for commands that specify a number of threads.​
#[derive(Args, Debug)]
pub struct NumThreadsArg {
    #[arg(short = 't', long, default_value_t = rayon::current_num_threads().max(1), value_parser = num_threads_parser)]
    /// The number of threads to use.​
    pub num_threads: usize,
}

/// Shared CLI arguments for commands that specify a granularity.​
#[derive(Args, Debug)]
pub struct GranularityArgs {
    #[arg(long, conflicts_with("node_granularity"))]
    /// The tentative number of arcs used to define the size of a parallel job
    /// (advanced option).​
    pub arc_granularity: Option<u64>,

    #[arg(long, conflicts_with("arc_granularity"))]
    /// The tentative number of nodes used to define the size of a parallel job
    /// (advanced option).​
    pub node_granularity: Option<usize>,
}

impl GranularityArgs {
    pub fn into_granularity(&self) -> Granularity {
        self.into_granularity_or(Granularity::default())
    }

    pub fn into_granularity_or(&self, default: Granularity) -> Granularity {
        match (self.arc_granularity, self.node_granularity) {
            (Some(_), Some(_)) => unreachable!(),
            (Some(arc_granularity), None) => Granularity::Arcs(arc_granularity),
            (None, Some(node_granularity)) => Granularity::Nodes(node_granularity),
            (None, None) => default,
        }
    }
}

/// Shared CLI arguments for commands that specify a memory usage.
///
/// Accepts a plain number, a number with a suffix, a percentage, or the
/// special value `auto`. If the value ends with `b` or `B` it is interpreted
/// as a number of bytes; otherwise, it is interpreted as a number of
/// elements. The available SI and NIST multipliers are k, M, G, T, P, ki,
/// Mi, Gi, Ti, and Pi. A trailing `%` interprets the value as a percentage of
/// the available memory. The value `auto` uses a non-linear formula that
/// behaves like 50% of RAM on small machines but grows sub-linearly on large
/// ones, capped at 1 TiB (256 MiB on 32-bit platforms); see
/// [`MemoryUsage::default`] for details. The default is `auto`.​
#[derive(Args, Debug)]
pub struct MemoryUsageArg {
    #[clap(short = 'm', long = "memory-usage", value_parser = memory_usage_parser, default_value = "auto")]
    /// The memory usage for batches (a number of elements with an optional
    /// SI/NIST suffix; append "b"/"B" for bytes, "%" for a percentage of
    /// available memory, or "auto" for a non-linear default).​
    pub memory_usage: MemoryUsage,
}

/// Formats for storing and loading slices of floats.​
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum FloatSliceFormat {
    /// Java-compatible format: a sequence of big-endian floats (32 or 64 bits).​
    Java,
    /// A sequence of floats (32 or 64 bits) serialized using ε-serde.​
    Epserde,
    /// ASCII format, one float per line.​
    #[default]
    Ascii,
    /// A JSON array.​
    Json,
}

impl FloatSliceFormat {
    /// Stores a slice of floats in the specified `path` using the format defined by
    /// `self`.
    ///
    /// If the result is a textual format, that is, ASCII or JSON, `precision`
    /// will be used to round the float values to the specified number of
    /// decimal digits. If `None`, [zmij] formatting will be used.
    ///
    /// [zmij]: https://crates.io/crates/zmij
    pub fn store<F>(
        &self,
        path: impl AsRef<Path>,
        values: &[F],
        precision: Option<usize>,
    ) -> Result<()>
    where
        F: ToBytes + Display + epserde::ser::Serialize + Copy + zmij::Float,
        for<'a> &'a [F]: epserde::ser::Serialize,
    {
        let path = path.as_ref();
        let path_display = path.display();
        let mut file = create_file(path)?;

        match self {
            FloatSliceFormat::Epserde => store_epserde(values, &mut file, path)?,
            FloatSliceFormat::Java => store_java(values, &mut file, path)?,
            FloatSliceFormat::Ascii => {
                log::info!("Storing in ASCII format at {}", path_display);
                let mut buf = zmij::Buffer::new();
                for word in values.iter() {
                    match precision {
                        None => writeln!(file, "{}", buf.format(*word)),
                        Some(precision) => writeln!(file, "{word:.precision$}"),
                    }
                    .with_context(|| format!("Could not write slice to {}", path_display))?;
                }
            }
            FloatSliceFormat::Json => {
                log::info!("Storing in JSON format at {}", path_display);
                let mut buf = zmij::Buffer::new();
                write!(file, "[")?;
                for word in values.iter().take(values.len().saturating_sub(1)) {
                    match precision {
                        None => write!(file, "{}, ", buf.format(*word)),
                        Some(precision) => write!(file, "{word:.precision$}, "),
                    }
                    .with_context(|| format!("Could not write slice to {}", path_display))?;
                }
                if let Some(last) = values.last() {
                    match precision {
                        None => write!(file, "{}", buf.format(*last)),
                        Some(precision) => write!(file, "{last:.precision$}"),
                    }
                    .with_context(|| format!("Could not write slice to {}", path_display))?;
                }
                write!(file, "]")?;
            }
        }

        Ok(())
    }

    /// Loads float values from the specified `path` using the format defined
    /// by `self`.
    pub fn load<F>(&self, path: impl AsRef<Path>) -> Result<Vec<F>>
    where
        F: FromBytes + FromStr + Copy + serde::de::DeserializeOwned,
        <F as FromBytes>::Bytes: for<'a> TryFrom<&'a [u8]>,
        <F as FromStr>::Err: std::error::Error + Send + Sync + 'static,
        Vec<F>: epserde::deser::Deserialize,
    {
        let path = path.as_ref();
        let path_display = path.display();

        match self {
            FloatSliceFormat::Epserde => {
                log::info!("Loading ε-serde format from {}", path_display);
                Ok(unsafe {
                    <Vec<F>>::load_full(path)
                        .with_context(|| format!("Could not load slice from {}", path_display))?
                })
            }
            FloatSliceFormat::Java => {
                log::info!("Loading Java format from {}", path_display);
                let file = std::fs::File::open(path)
                    .with_context(|| format!("Could not open {}", path_display))?;
                let file_len = file.metadata()?.len() as usize;
                let byte_size = size_of::<F>();
                ensure!(
                    file_len % byte_size == 0,
                    "File size ({}) is not a multiple of {} bytes",
                    file_len,
                    byte_size
                );
                let n = file_len / byte_size;
                let mut reader = BufReader::new(file);
                let mut result = Vec::with_capacity(n);
                let mut buf = vec![0u8; byte_size];
                for i in 0..n {
                    reader.read_exact(&mut buf).with_context(|| {
                        format!("Could not read value at index {i} from {}", path_display)
                    })?;
                    let bytes = buf.as_slice().try_into().map_err(|_| {
                        anyhow!("Could not convert bytes at index {i} in {}", path_display)
                    })?;
                    result.push(F::from_be_bytes(&bytes));
                }
                Ok(result)
            }
            FloatSliceFormat::Ascii => load_ascii(path),
            FloatSliceFormat::Json => load_json(path),
        }
    }
}

/// How to store slices of integers.​
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum IntSliceFormat {
    #[cfg(target_pointer_width = "64")]
    /// Java-compatible format: a sequence of big-endian 64-bit integers; available only on 64-bit platforms.​
    Java,
    /// A sequence of usize serialized using ε-serde.​
    Epserde,
    /// A BitFieldVec stored using ε-serde: it stores each element using
    /// ⌊log₂(max)⌋ + 1 bits, and it requires to allocate the `BitFieldVec` in RAM
    /// before serializing it.​
    BitFieldVec,
    /// ASCII format, one integer per line.​
    #[default]
    Ascii,
    /// A JSON array.​
    Json,
}

/// Loaded integer slice, returned by [`IntSliceFormat::load`].
///
/// Depending on the format, the data may be backed by a memory-mapped file
/// (Java, ε-serde, and [`BitFieldVec`]) or fully loaded into memory (ASCII,
/// JSON).
///
/// This enum implements [`SliceByValue`] with `Value = usize`, so it can
/// be used directly wherever a [`SliceByValue`] is expected. However, each
/// access goes through enum dispatch, which may be undesirable in
/// performance-critical code.
///
/// For native, dispatch-free access, match on the variants and use each
/// inner type directly—they all implement [`SliceByValue<Value = usize>`]:
///
/// ```ignore
/// match args.fmt.load(&path)? {
///     IntSlice::Owned(v) => do_transform(&v, ...),
///     IntSlice::Java(j) => do_transform(&j, ...),
///     IntSlice::Epserde(m) => do_transform(m.uncase(), ...),
///     IntSlice::BitFieldVec(m) => do_transform(m.uncase(), ...),
/// }
/// ```
///
/// This incurs one monomorphization of `do_transform` per arm; arms that
/// share the same inner type can be merged to reduce monomorphization cost.
pub enum IntSlice {
    /// Fully loaded into memory (ASCII, JSON).
    Owned(Box<[usize]>),
    #[cfg(target_pointer_width = "64")]
    /// Memory-mapped Java big-endian format (64-bit only).
    Java(JavaPermutation),
    /// Memory-mapped ε-serde serialized slice.
    Epserde(MemCase<Box<[usize]>>),
    /// Memory-mapped ε-serde serialized [`BitFieldVec`].
    BitFieldVec(MemCase<sux::bits::BitFieldVec>),
}

impl SliceByValue for IntSlice {
    type Value = usize;

    unsafe fn get_value_unchecked(&self, index: usize) -> usize {
        match self {
            IntSlice::Owned(v) => unsafe { *v.get_unchecked(index) },
            #[cfg(target_pointer_width = "64")]
            IntSlice::Java(j) => unsafe { j.get_value_unchecked(index) },
            IntSlice::Epserde(m) => unsafe { *m.uncase().get_unchecked(index) },
            IntSlice::BitFieldVec(m) => unsafe { m.uncase().get_value_unchecked(index) },
        }
    }

    fn len(&self) -> usize {
        match self {
            IntSlice::Owned(v) => v.len(),
            #[cfg(target_pointer_width = "64")]
            IntSlice::Java(j) => j.len(),
            IntSlice::Epserde(m) => m.uncase().len(),
            IntSlice::BitFieldVec(m) => m.uncase().len(),
        }
    }
}

/// Dispatches on an [`IntSlice`], binding the concrete inner
/// [`SliceByValue`] type to `$var` and evaluating `$body` for each variant.
///
/// The bound types are `&Box<[usize]>` (Owned and Epserde),
/// `&JavaPermutation` (Java, 64-bit only), and `&BitFieldVec`
/// (BitFieldVec). All bound types are `Sized`.
#[macro_export]
macro_rules! dispatch_int_slice {
    ($slice:expr, |$var:ident| $body:expr) => {
        match $slice {
            $crate::IntSlice::Owned(ref __v) => {
                let $var = __v;
                $body
            }
            #[cfg(target_pointer_width = "64")]
            $crate::IntSlice::Java(ref __j) => {
                let $var = __j;
                $body
            }
            $crate::IntSlice::Epserde(ref __m) => {
                let $var = __m.uncase();
                $body
            }
            $crate::IntSlice::BitFieldVec(ref __m) => {
                let $var = __m.uncase();
                $body
            }
        }
    };
}

impl IntSliceFormat {
    /// Stores a slice of `usize` in the specified `path` using the format
    /// defined by `self`.
    ///
    /// `max` is the maximum value of the slice. If it is not provided, it will
    /// be computed from the data.
    pub fn store(&self, path: impl AsRef<Path>, data: &[usize], max: Option<usize>) -> Result<()> {
        let mut buf = create_file(path.as_ref())?;

        debug_assert_eq!(
            max,
            max.map(|_| { data.iter().copied().max().unwrap_or(0) }),
            "The wrong maximum value was provided for the slice"
        );

        match self {
            IntSliceFormat::Epserde => store_epserde(data, &mut buf, path.as_ref())?,
            IntSliceFormat::BitFieldVec => {
                log::info!(
                    "Storing in BitFieldVec format at {}",
                    path.as_ref().display()
                );
                let max = max.unwrap_or_else(|| {
                    data.iter()
                        .copied()
                        .max()
                        .unwrap_or_else(|| panic!("Empty slice"))
                });
                let bit_width = max.bit_len() as usize;
                log::info!("Using {} bits per element", bit_width);
                let mut bit_field_vec = BitFieldVec::with_capacity(bit_width, data.len());
                bit_field_vec.extend(data.iter().copied());

                unsafe {
                    bit_field_vec.store(&path).with_context(|| {
                        format!("Could not write slice to {}", path.as_ref().display())
                    })
                }?;
            }
            #[cfg(target_pointer_width = "64")]
            IntSliceFormat::Java => store_java(data, &mut buf, path.as_ref())?,
            IntSliceFormat::Ascii => {
                log::info!("Storing in ASCII format at {}", path.as_ref().display());
                for word in data.iter() {
                    writeln!(buf, "{}", word).with_context(|| {
                        format!("Could not write slice to {}", path.as_ref().display())
                    })?;
                }
            }
            IntSliceFormat::Json => {
                log::info!("Storing in JSON format at {}", path.as_ref().display());
                serde_json::to_writer(&mut buf, data).with_context(|| {
                    format!("Could not write slice to {}", path.as_ref().display())
                })?;
            }
        };

        Ok(())
    }

    /// Loads integer values from the specified `path` using the format defined
    /// by `self`, returning an [`IntSlice`].
    ///
    /// The ε-serde-based formats (Epserde, BitFieldVec) and the Java format
    /// use memory mapping; ASCII and JSON are fully loaded into memory.
    pub fn load(&self, path: impl AsRef<Path>) -> Result<IntSlice> {
        let path = path.as_ref();
        let path_display = path.display();

        match self {
            IntSliceFormat::Epserde => {
                log::info!("Loading ε-serde format from {}", path_display);
                let mem_case = unsafe {
                    <Box<[usize]>>::mmap(path, Flags::RANDOM_ACCESS)
                        .with_context(|| format!("Could not load slice from {}", path_display))?
                };
                Ok(IntSlice::Epserde(mem_case))
            }
            IntSliceFormat::BitFieldVec => {
                log::info!("Loading BitFieldVec format from {}", path_display);
                let mem_case = unsafe {
                    <BitFieldVec>::mmap(path, Flags::RANDOM_ACCESS)
                        .with_context(|| format!("Could not load slice from {}", path_display))?
                };
                Ok(IntSlice::BitFieldVec(mem_case))
            }
            #[cfg(target_pointer_width = "64")]
            IntSliceFormat::Java => {
                log::info!("Loading Java format from {}", path_display);
                let perm = JavaPermutation::mmap(path, mmap_rs::MmapFlags::RANDOM_ACCESS)
                    .with_context(|| format!("Could not load slice from {}", path_display))?;
                Ok(IntSlice::Java(perm))
            }
            IntSliceFormat::Ascii => Ok(IntSlice::Owned(load_ascii(path)?.into())),
            IntSliceFormat::Json => Ok(IntSlice::Owned(load_json(path)?.into())),
        }
    }
}

/// Creates a buffered file at `path`, creating also its parent directories.
fn create_file(path: &Path) -> Result<BufWriter<File>> {
    create_parent_dir(path)?;
    let file = File::create(path)
        .with_context(|| format!("Could not create slice at {}", path.display()))?;
    Ok(BufWriter::new(file))
}

/// Stores a slice using ε-serde.
fn store_epserde<T>(values: &[T], file: &mut BufWriter<File>, path: &Path) -> Result<()>
where
    for<'a> &'a [T]: Serialize,
{
    log::info!("Storing in ε-serde format at {}", path.display());
    unsafe { values.serialize(file) }
        .with_context(|| format!("Could not write slice to {}", path.display()))?;
    Ok(())
}

/// Stores a slice in Java format (big-endian values).
fn store_java<T: ToBytes>(values: &[T], file: &mut BufWriter<File>, path: &Path) -> Result<()> {
    log::info!("Storing in Java format at {}", path.display());
    for value in values {
        file.write_all(value.to_be_bytes().as_ref())
            .with_context(|| format!("Could not write slice to {}", path.display()))?;
    }
    Ok(())
}

/// Loads values from an ASCII file containing one value per line, skipping
/// empty lines.
fn load_ascii<T: FromStr>(path: &Path) -> Result<Vec<T>>
where
    T::Err: Display,
{
    log::info!("Loading ASCII format from {}", path.display());
    let file = File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
    BufReader::new(file)
        .lines()
        .enumerate()
        .filter(|(_, line)| line.as_ref().map_or(true, |l| !l.trim().is_empty()))
        .map(|(i, line)| {
            let line = line
                .with_context(|| format!("Error reading line {} of {}", i + 1, path.display()))?;
            line.trim()
                .parse::<T>()
                .map_err(|e| anyhow!("Error parsing line {} of {}: {}", i + 1, path.display(), e))
        })
        .collect()
}

/// Loads values from a JSON array.
fn load_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Vec<T>> {
    log::info!("Loading JSON format from {}", path.display());
    let file = File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
    serde_json::from_reader(BufReader::new(file))
        .with_context(|| format!("Could not parse JSON from {}", path.display()))
}

/// Parses a batch size.
///
/// This function accepts `auto` (which uses the non-linear default from
/// [`MemoryUsage::default`]), a number (possibly followed by a SI or NIST
/// multiplier k, M, G, T, P, ki, Mi, Gi, Ti, or Pi), or a percentage
/// (followed by a `%`) that is interpreted as a percentage of the physical
/// RAM. If the value ends with a `b` or `B` it is interpreted as a number of
/// bytes, otherwise as a number of elements.
pub fn memory_usage_parser(arg: &str) -> anyhow::Result<MemoryUsage> {
    const PREF_SYMS: [(&str, u64); 10] = [
        ("ki", 1 << 10),
        ("mi", 1 << 20),
        ("gi", 1 << 30),
        ("ti", 1 << 40),
        ("pi", 1 << 50),
        ("k", 1E3 as u64),
        ("m", 1E6 as u64),
        ("g", 1E9 as u64),
        ("t", 1E12 as u64),
        ("p", 1E15 as u64),
    ];
    let arg = arg.trim().to_ascii_lowercase();
    ensure!(!arg.is_empty(), "empty string");

    if arg == "auto" {
        return Ok(MemoryUsage::default());
    }

    if arg.ends_with('%') {
        let perc = arg[..arg.len() - 1].parse::<f64>()?;
        ensure!((0.0..=100.0).contains(&perc), "percentage out of range");
        return Ok(MemoryUsage::from_perc(perc));
    }

    let num_digits = arg
        .chars()
        .take_while(|c| c.is_ascii_digit() || *c == '.')
        .count();

    let number = arg[..num_digits].parse::<f64>()?;
    let suffix = &arg[num_digits..].trim();

    if suffix.is_empty() {
        let value = number as usize;
        ensure!(value > 0, "batch size must be greater than zero");
        return Ok(MemoryUsage::BatchSize(value));
    }

    let prefix = suffix.strip_suffix('b').unwrap_or(suffix);
    let multiplier = PREF_SYMS
        .iter()
        .find(|(x, _)| *x == prefix)
        .map(|(_, m)| m)
        .ok_or(anyhow!("invalid suffix {}", suffix))?;

    let value = (number * (*multiplier as f64)) as usize;
    ensure!(value > 0, "batch size must be greater than zero");

    if suffix.ends_with('b') {
        Ok(MemoryUsage::MemorySize(value))
    } else {
        Ok(MemoryUsage::BatchSize(value))
    }
}

/// Parses the value of `--max-ref-count`: a nonnegative integer, or -1 for
/// an infinite recursion depth.
pub fn max_ref_count_parser(arg: &str) -> anyhow::Result<isize> {
    let value = arg.parse::<isize>()?;
    ensure!(
        value >= -1,
        "the maximum reference count must be nonnegative, or -1 for infinite recursion depth"
    );
    Ok(value)
}

/// Shared CLI arguments for compression.​
#[derive(Args, Debug, Clone)]
pub struct CompressArgs {
    /// The endianness of the graph to write [default: same as source].​
    #[clap(short = 'E', long)]
    pub endianness: Option<String>,

    /// The compression window.​
    #[clap(short = 'w', long, default_value_t = 7)]
    pub compression_window: usize,
    /// The minimum interval length.​
    #[clap(short = 'i', long, default_value_t = 4)]
    pub min_interval_length: usize,
    /// The maximum recursion depth for references (-1 for infinite recursion depth).​
    #[clap(short = 'r', long, default_value_t = 3, allow_hyphen_values = true, value_parser = max_ref_count_parser)]
    pub max_ref_count: isize,

    #[arg(value_enum)]
    #[clap(long, default_value = "gamma")]
    /// The code to use for outdegrees.​
    pub outdegrees: PrivCode,

    #[arg(value_enum)]
    #[clap(long, default_value = "unary")]
    /// The code to use for reference offsets.​
    pub references: PrivCode,

    #[arg(value_enum)]
    #[clap(long, default_value = "gamma")]
    /// The code to use for blocks.​
    pub blocks: PrivCode,

    #[arg(value_enum)]
    #[clap(long, default_value = "zeta3")]
    /// The code to use for residuals.​
    pub residuals: PrivCode,

    /// Use Zuckerli's reference selection algorithm (slower, more memory,
    /// but better compression and decoding speed).​
    #[clap(long)]
    pub bvgraphz: bool,

    /// Number of nodes per chunk with --bvgraphz.​
    #[clap(long, default_value = "10000")]
    pub chunk_size: usize,
}

impl CompressArgs {
    /// Returns a [`BvCompConf`] writing a graph with basename `dst` using the
    /// compression parameters specified by these arguments.
    pub fn bv_comp_conf(&self, dst: impl AsRef<Path>) -> BvCompConf {
        let conf = BvCompConf::new(dst).comp_flags(self.into());
        if self.bvgraphz {
            conf.chunk_size(self.chunk_size)
        } else {
            conf
        }
    }

    /// Returns the name of the endianness of the graph to write: the one
    /// specified by these arguments, if any, or that of `E`.
    pub fn target_endianness<E: Endianness>(&self) -> String {
        self.endianness.clone().unwrap_or_else(|| E::NAME.into())
    }
}

impl From<CompressArgs> for CompFlags {
    fn from(value: CompressArgs) -> Self {
        (&value).into()
    }
}

impl From<&CompressArgs> for CompFlags {
    fn from(value: &CompressArgs) -> Self {
        CompFlags {
            outdegrees: value.outdegrees.into(),
            references: value.references.into(),
            blocks: value.blocks.into(),
            intervals: PrivCode::Gamma.into(),
            residuals: value.residuals.into(),
            min_interval_length: value.min_interval_length,
            compression_window: value.compression_window,
            max_ref_count: match value.max_ref_count {
                -1 => usize::MAX,
                max_ref_count => {
                    assert!(
                        max_ref_count >= 0,
                        "max_ref_count cannot be negative, except for -1, which means infinite recursion depth, but got {}",
                        max_ref_count
                    );
                    value.max_ref_count as usize
                }
            },
        }
    }
}

/// Creates a [`ThreadPool`] with the given number of threads.
///
/// [`ThreadPool`]: rayon::ThreadPool
pub fn get_thread_pool(num_threads: usize) -> rayon::ThreadPool {
    let thread_pool = rayon::ThreadPoolBuilder::new()
        .num_threads(num_threads)
        .build()
        .expect("Failed to create thread pool");
    log::info!("Using {} threads", thread_pool.current_num_threads());
    thread_pool
}

/// Creates all parent directories of the given file path.
pub fn create_parent_dir(file_path: impl AsRef<Path>) -> Result<()> {
    // ensure that the dst directory exists
    if let Some(parent_dir) = file_path.as_ref().parent() {
        std::fs::create_dir_all(parent_dir).with_context(|| {
            format!(
                "Failed to create the directory {:?}",
                parent_dir.to_string_lossy()
            )
        })?;
    }
    Ok(())
}

/// Computes cutpoints for splitting a graph into `num_parts` chunks for
/// parallel compression.
///
/// If `use_dcf` is true, loads the DCF file for the given basename and uses
/// [`dcf_cutpoints`] to balance by arc count. Otherwise, falls back to
/// [`uniform_cutpoints`] by node count.
///
/// [`dcf_cutpoints`]: webgraph::traits::split::dcf_cutpoints
/// [`uniform_cutpoints`]: webgraph::traits::split::uniform_cutpoints
pub fn cutpoints(
    basename: &Path,
    num_nodes: usize,
    num_arcs: Option<u64>,
    use_dcf: bool,
    num_parts: usize,
) -> Result<Vec<usize>> {
    use webgraph::traits::split::{dcf_cutpoints, uniform_cutpoints};

    if use_dcf {
        let num_arcs = num_arcs.context("The number of arcs is required to use the DCF")?;
        let dcf = load_dcf(basename, num_nodes, num_arcs)?;
        let cutpoints = dcf_cutpoints(dcf.uncase(), num_parts);
        log::info!(
            "Using DCF-based splitting into {} parts",
            cutpoints.len() - 1
        );
        Ok(cutpoints.into_vec())
    } else {
        let dcf_path = basename.with_extension(DEG_CUMUL_EXTENSION);
        if dcf_path.exists() {
            log::warn!(
                "A DCF (degree cumulative function) file exists at {}; consider using --dcf for better load balancing",
                dcf_path.display()
            );
        } else {
            log::warn!(
                "No DCF (degree cumulative function) file found; consider building one with `webgraph build dcf {}` for better load balancing",
                basename.display()
            );
        }
        Ok(uniform_cutpoints(num_nodes, num_parts).collect())
    }
}

/// Wraps a graph in a [`ParGraph`] splitting it into `num_parts` parts using
/// the [cutpoints] computed for the graph with given basename.
///
/// [`ParGraph`]: webgraph::graphs::par_graphs::ParGraph
/// [cutpoints]: cutpoints
pub fn par_graph<G: SequentialLabeling>(
    graph: G,
    basename: &Path,
    use_dcf: bool,
    num_parts: usize,
) -> Result<ParGraph<G>> {
    let cutpoints = cutpoints(
        basename,
        graph.num_nodes(),
        graph.get_num_arcs(),
        use_dcf,
        num_parts,
    )?;
    Ok(ParGraph::with_cutpoints(graph, cutpoints))
}

/// Memory-maps the degree cumulative function (DCF) of the graph with given
/// basename, checking that it is consistent with the given number of nodes and
/// arcs.
pub fn load_dcf(basename: &Path, num_nodes: usize, num_arcs: u64) -> Result<MemCase<DCF>> {
    let dcf_path = basename.with_extension(DEG_CUMUL_EXTENSION);
    ensure!(
        dcf_path.exists(),
        "DCF file {} does not exist; build it with `webgraph build dcf {}`",
        dcf_path.display(),
        basename.display()
    );
    let dcf = unsafe { DCF::mmap(&dcf_path, Flags::RANDOM_ACCESS) }
        .with_context(|| format!("Could not load the DCF from {}", dcf_path.display()))?;
    let values = dcf.uncase();
    ensure!(
        values.len() == num_nodes + 1,
        "DCF has {} entries, expected {} (num_nodes + 1)",
        values.len(),
        num_nodes + 1
    );
    ensure!(values.index_value(0) == 0, "DCF does not start with 0");
    ensure!(
        values.index_value(num_nodes) == num_arcs,
        "DCF ends with {}, expected {} (num_arcs)",
        values.index_value(num_nodes),
        num_arcs
    );
    Ok(dcf)
}

/// Parses a duration from a string.
/// For compatibility with Java, if no suffix is given, it is assumed to be in milliseconds.
/// You can use suffixes, the available ones are:
/// - `s` for seconds
/// - `m` for minutes
/// - `h` for hours
/// - `d` for days
///
/// Example: `1d2h3m4s567` this is parsed as: 1 day, 2 hours, 3 minutes, 4 seconds, and 567 milliseconds.
fn parse_duration(value: &str) -> Result<Duration> {
    if value.is_empty() {
        bail!("Empty duration string, if you want every 0 milliseconds use `0`.");
    }
    let mut duration = Duration::from_secs(0);
    let mut acc = String::new();
    for c in value.chars() {
        if c.is_ascii_digit() {
            acc.push(c);
        } else if c.is_whitespace() {
            continue;
        } else {
            let dur = acc.parse::<u64>()?;
            match c {
                's' => duration += Duration::from_secs(dur),
                'm' => duration += Duration::from_secs(dur * 60),
                'h' => duration += Duration::from_secs(dur * 60 * 60),
                'd' => duration += Duration::from_secs(dur * 60 * 60 * 24),
                _ => return Err(anyhow!("Invalid duration suffix: {}", c)),
            }
            acc.clear();
        }
    }
    if !acc.is_empty() {
        let dur = acc.parse::<u64>()?;
        duration += Duration::from_millis(dur);
    }
    Ok(duration)
}

/// Initializes the `env_logger` logger with a custom format including
/// timestamps with elapsed time since initialization.
pub fn init_env_logger() -> Result<()> {
    use jiff::SpanRound;
    use jiff::fmt::friendly::{Designator, Spacing, SpanPrinter};

    let mut builder =
        env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"));

    let start = std::time::Instant::now();
    let printer = SpanPrinter::new()
        .spacing(Spacing::None)
        .designator(Designator::Compact);
    let span_round = SpanRound::new()
        .largest(jiff::Unit::Day)
        .smallest(jiff::Unit::Millisecond)
        .days_are_24_hours();

    builder.format(move |buf, record| {
        let Ok(ts) = jiff::Timestamp::try_from(SystemTime::now()) else {
            return Err(std::io::Error::other("Failed to get timestamp"));
        };
        let style = buf.default_level_style(record.level());
        let elapsed = start.elapsed();
        let span = jiff::Span::new()
            .seconds(elapsed.as_secs() as i64)
            .milliseconds(elapsed.subsec_millis() as i64);
        let span = span.round(span_round).expect("Failed to round span");
        writeln!(
            buf,
            "{} {} {style}{}{style:#} [{:?}] {} - {}",
            ts.strftime("%F %T%.3f"),
            printer.span_to_string(&span),
            record.level(),
            std::thread::current().id(),
            record.target(),
            record.args()
        )
    });
    builder.init();
    Ok(())
}

/// Shared CLI arguments for commands that use a log interval.​
#[derive(Args, Debug, Clone)]
pub struct LogIntervalArg {
    #[arg(long, value_parser = parse_duration, default_value = "10s")]
    /// How often to log progress (default: 10s). Supported suffixes: "s"
    /// (seconds), "m" (minutes), "h" (hours), "d" (days). Without a suffix,
    /// the value is interpreted as milliseconds. Example: "1d2h3m4s567" means
    /// 1 day + 2 hours + 3 minutes + 4 seconds + 567 milliseconds.​
    pub log_interval: Duration,
}

#[derive(Subcommand, Debug)]
pub enum SubCommands {
    #[command(subcommand)]
    Analyze(analyze::SubCommands),
    #[command(subcommand)]
    Bench(bench::SubCommands),
    #[command(subcommand)]
    Build(build::SubCommands),
    #[command(subcommand)]
    Check(check::SubCommands),
    #[command(subcommand)]
    From(from::SubCommands),
    #[command(subcommand)]
    Perm(perm::SubCommands),
    #[command(subcommand)]
    Run(run::SubCommands),
    #[command(subcommand)]
    Seq(seq::SubCommands),
    #[command(subcommand)]
    To(to::SubCommands),
    #[command(subcommand)]
    Transform(transform::SubCommands),
}

#[derive(Parser, Debug)]
#[command(name = "webgraph", version=build_info::version_string(), max_term_width = 100, after_help = include_str!("common_env.txt"))]
/// WebGraph tools to build, convert, modify, and analyze graphs.​
pub struct Cli {
    #[command(subcommand)]
    pub command: SubCommands,
}

pub mod dist;
pub mod rank;
pub mod sccs;

pub mod analyze;
pub mod bench;
pub mod build;
pub mod check;
pub mod from;
pub mod perm;
pub mod run;
pub mod seq;
pub mod to;
pub mod transform;

/// The entry point of the command-line interface.
pub fn cli_main<I, T>(args: I) -> Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    timed(|| match Cli::parse_from(args).command {
        SubCommands::Analyze(args) => analyze::main(args),
        SubCommands::Bench(args) => bench::main(args),
        SubCommands::Build(args) => build::main(args, Cli::command()),
        SubCommands::Check(args) => check::main(args),
        SubCommands::From(args) => from::main(args),
        SubCommands::Perm(args) => perm::main(args),
        SubCommands::Run(args) => run::main(args),
        SubCommands::Seq(args) => seq::main(args),
        SubCommands::To(args) => to::main(args),
        SubCommands::Transform(args) => transform::main(args),
    })
}

/// Runs a command (including the parsing of its arguments), logging how long
/// it took.
fn timed(command: impl FnOnce() -> Result<()>) -> Result<()> {
    let start = std::time::Instant::now();
    command()?;
    log::info!(
        "The command took {}",
        pretty_print_elapsed(start.elapsed().as_secs_f64())
    );
    Ok(())
}

/// Pretty-prints seconds in a human-readable format.
fn pretty_print_elapsed(elapsed: f64) -> String {
    let mut result = String::new();
    let mut elapsed_seconds = elapsed as u64;
    let weeks = elapsed_seconds / (60 * 60 * 24 * 7);
    elapsed_seconds %= 60 * 60 * 24 * 7;
    let days = elapsed_seconds / (60 * 60 * 24);
    elapsed_seconds %= 60 * 60 * 24;
    let hours = elapsed_seconds / (60 * 60);
    elapsed_seconds %= 60 * 60;
    let minutes = elapsed_seconds / 60;
    //elapsed_seconds %= 60;

    match weeks {
        0 => {}
        1 => result.push_str("1 week "),
        _ => result.push_str(&format!("{} weeks ", weeks)),
    }
    match days {
        0 => {}
        1 => result.push_str("1 day "),
        _ => result.push_str(&format!("{} days ", days)),
    }
    match hours {
        0 => {}
        1 => result.push_str("1 hour "),
        _ => result.push_str(&format!("{} hours ", hours)),
    }
    match minutes {
        0 => {}
        1 => result.push_str("1 minute "),
        _ => result.push_str(&format!("{} minutes ", minutes)),
    }

    result.push_str(&format!("{:.3} seconds ({}s)", elapsed % 60.0, elapsed));
    result
}