Debian Codegraph @

third_party/rust/clubcard/examples/uint_no_partition/main.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /// Compress a set of u32 integers and output the (approximate) size of compressed bytes.
6 /// # Arguments
7 ///
8 /// * `filepath` - The input file containing integers in range [0, max(a_i)].
9 /// ```txt
10 /// a_1 \n
11 /// ...
12 /// a_n \n
13 /// ```
14 /// The universe size will be the maximum value of the input file.
15 ///
16 /// # Usage
17 ///
18 /// To run this example, use the following command:
19 /// ```bash
20 /// cargo run --features builder --example uint_no_partition
21 /// ```
22 ///
23
24 use clubcard::*;
25 use sha2::{Digest, Sha256};
26 use std::cmp::max;
27 use std::collections::HashSet;
28 use std::{env, fs, io, process};
29 use std::io::BufRead;
30 use clubcard::builder::{ApproximateRibbon, ClubcardBuilder, ExactRibbon};
31
32 struct Universe {
33 bound: u32,
34 }
35 const W: usize = 4;
36 const BLOCK: [u8; 0] = [];
37
38 struct Int {
39 val: [u8; 4], // u32
40 included: bool, // whether it's in the subset
41 }
42
43 impl Int {
44 fn new(num: u32, included: bool) -> Int {
45 Int {
46 val: num.to_le_bytes(),
47 included,
48 }
49 }
50 }
51
52 impl ApproximateSizeOf for Universe {}
53
54 impl AsQuery<W> for Int {
55 fn as_query(&self, m: usize) -> Equation<W> {
56 let mut digest = [0u8; 32];
57 let mut hasher = Sha256::new();
58 hasher.update(&self.val);
59 hasher.finalize_into((&mut digest).into());
60
61 let mut a = [0u64; W]; // block of columns
62 for (i, x) in digest
63 .chunks_exact(8)
64 .map(|x| TryInto::<[u8; 8]>::try_into(x).unwrap())
65 .map(u64::from_le_bytes)
66 .enumerate()
67 {
68 a[i] = x;
69 }
70
71 a[0] |= 1;
72 let s = (a[W - 1] as usize) % max(1, m); //
73 let b = if self.included { 0 } else { 1 };
74 Equation::inhomogeneous(s, a, b)
75 }
76
77 fn block(&self) -> &[u8] {
78 &BLOCK
79 }
80
81 fn discriminant(&self) -> &[u8] {
82 &self.val
83 }
84 }
85
86 impl Filterable<W> for Int {
87 fn included(&self) -> bool {
88 self.included
89 }
90 }
91
92 impl Queryable<W> for Int {
93 type UniverseMetadata = Universe;
94 type PartitionMetadata = ();
95
96 fn in_universe(&self, meta: &Self::UniverseMetadata) -> bool {
97 u32::from_le_bytes(self.val) < meta.bound
98 }
99 }
100
101 // Parse the file into a set of integers, return the hash set and maximum element + 1 in set
102 fn parse_args() -> (u32, HashSet<u32>) {
103 let args: Vec<String> = env::args().collect();
104
105 if args.len() < 2 {
106 println!("Please specify the name of input file.");
107 process::exit(1);
108 }
109 let file_path = &args[1];
110 let file = fs::File::open(file_path).expect("Error opening the file.");
111 let mut lines = io::BufReader::new(file).lines();
112
113 let mut numbers = HashSet::new();
114 let mut max_val = 0;
115
116 while let Some(Ok(line)) = lines.next() {
117 let number = line.trim().parse::<u32>().expect("Failed to parse 32-bit integer");
118 if number > max_val {
119 max_val = number;
120 }
121 numbers.insert(number);
122 }
123
124 (max_val + 1, numbers)
125 }
126
127 fn main() {
128 let (universe_size, numbers) = parse_args();
129
130 let mut clubcard_builder = ClubcardBuilder::new();
131 let mut approx_builder = clubcard_builder.new_approx_builder(&BLOCK);
132
133 // Build approx filter
134 for num in &numbers {
135 let int = Int::new(num.clone(), true);
136 approx_builder.insert(int)
137 }
138 approx_builder.set_universe_size(universe_size.try_into().unwrap());
139 clubcard_builder.collect_approx_ribbons(vec![ApproximateRibbon::from(approx_builder)]);
140
141 // Build exact filter
142 let mut exact_builder = clubcard_builder.new_exact_builder(&BLOCK);
143 for num in 0..universe_size {
144 let int = Int::new(num.clone(), numbers.contains(&num));
145 exact_builder.insert(int);
146 }
147 clubcard_builder.collect_exact_ribbons(vec![ExactRibbon::from(exact_builder)]);
148
149 let clubcard = clubcard_builder.build::<Int>(
150 Universe { bound: universe_size },
151 (),
152 );
153
154 println!("Generated {}", clubcard);
155 println!("The size of compressed set (of {} elements) with max value {} is {} bytes.",
156 numbers.len(), universe_size - 1, clubcard.approximate_size_of());
157 }