Debian Codegraph @

third_party/rust/clubcard/src/clubcard.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 use crate::query::Queryable;
6 use serde::{Deserialize, Serialize};
7 use std::collections::BTreeMap;
8 use std::fmt;
9 use std::mem::size_of;
10
11 #[derive(PartialEq, Eq)]
12 pub enum Membership {
13 Member,
14 Nonmember,
15 NotInUniverse,
16 NoData,
17 }
18
19 impl From<bool> for Membership {
20 fn from(b: bool) -> Membership {
21 match b {
22 true => Membership::Member,
23 false => Membership::Nonmember,
24 }
25 }
26 }
27
28 /// Metadata needed to compute membership in a clubcard.
29 #[derive(Default, Serialize, Deserialize)]
30 pub struct ClubcardIndexEntry {
31 /// Description of the hash function h.
32 pub approx_filter_m: usize,
33 /// Description of the hash function g.
34 pub exact_filter_m: usize,
35 /// The number of columns in X.
36 pub approx_filter_rank: usize,
37 /// An offset t such that [0^t || h(u)] * X = h(u) * Xi, where i is the block identifier.
38 pub approx_filter_offset: usize,
39 /// An offset t such that [0^t || g(u)] * Y = g(u) * Yi, where i is the block identifier.
40 pub exact_filter_offset: usize,
41 /// Whether to invert the output of queries to this block.
42 pub inverted: bool,
43 /// A list of elements of Ui \ Ri that are not correctly encoded by this block.
44 pub exceptions: Vec<Vec<u8>>,
45 }
46
47 /// Lookup table from block identifiers to block metadata.
48 pub type ClubcardIndex = BTreeMap</* block id */ Vec<u8>, ClubcardIndexEntry>;
49
50 /// A queryable Clubcard
51 #[derive(Serialize, Deserialize)]
52 pub struct Clubcard<const W: usize, UniverseMetadata, PartitionMetadata> {
53 /// Metadata for determining whether a Queryable is in the encoded universe.
54 pub(crate) universe: UniverseMetadata,
55 /// Metadata for determining the block to which a Queryable belongs.
56 pub(crate) partition: PartitionMetadata,
57 /// Lookup table for per-block metadata.
58 pub(crate) index: ClubcardIndex,
59 /// The matrix X
60 pub(crate) approx_filter: Vec<Vec<u64>>,
61 /// The matrix Y
62 pub(crate) exact_filter: Vec<u64>,
63 }
64
65 impl<const W: usize, UniverseMetadata, PartitionMetadata> fmt::Display
66 for Clubcard<W, UniverseMetadata, PartitionMetadata>
67 {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 let approx_size = 8 * self.approx_filter.iter().map(|x| x.len()).sum::<usize>();
70 let exact_size = 8 * self.exact_filter.len();
71 let exceptions = self
72 .index
73 .values()
74 .map(|meta| meta.exceptions.len())
75 .sum::<usize>();
76 writeln!(
77 f,
78 "Clubcard of size {} ({} + {}) with {} exceptions",
79 approx_size + exact_size,
80 approx_size,
81 exact_size,
82 exceptions
83 )
84 }
85 }
86
87 impl<const W: usize, UniverseMetadata, PartitionMetadata>
88 Clubcard<W, UniverseMetadata, PartitionMetadata>
89 {
90 /// Perform a membership query without checking whether the item is in the universe.
91 /// The result is undefined if the item is not in the universe. The result is also
92 /// undefined if U's implementation of AsQuery differs from T's.
93 pub fn unchecked_contains<T>(&self, item: &T) -> bool
94 where
95 T: Queryable<W, PartitionMetadata = PartitionMetadata>,
96 {
97 let Some(meta) = self.index.get(item.block()) else {
98 return false;
99 };
100
101 let result = (|| {
102 // All queries evaluate to 0 on an empty filter, but logically
103 // such a filter does not include anything. So we handle it as a
104 // special case.
105 if meta.approx_filter_m == 0 {
106 return false;
107 }
108
109 // Check if h(item) * X is 0
110 let approx_query = item.as_approx_query(meta);
111 for i in 0..meta.approx_filter_rank {
112 if approx_query.eval(&self.approx_filter[i]) != 0 {
113 return false;
114 }
115 }
116
117 // Check if g(item) * X is 0
118 let exact_query = item.as_exact_query(meta);
119 if exact_query.eval(&self.exact_filter) != 0 {
120 return false;
121 }
122
123 for exception in &meta.exceptions {
124 if exception == item.discriminant() {
125 return false;
126 }
127 }
128 true
129 })();
130
131 result ^ meta.inverted
132 }
133
134 /// Check that the item is in the appropriate universe, and then perform a membership query.
135 pub fn contains<T>(&self, item: &T) -> Membership
136 where
137 T: Queryable<W, UniverseMetadata = UniverseMetadata, PartitionMetadata = PartitionMetadata>,
138 {
139 if !item.in_universe(&self.universe) {
140 return Membership::NotInUniverse;
141 };
142
143 if !self.index.contains_key(item.block()) {
144 return Membership::NoData;
145 };
146
147 self.unchecked_contains(item).into()
148 }
149
150 pub fn universe(&self) -> &UniverseMetadata {
151 &self.universe
152 }
153
154 pub fn partition(&self) -> &PartitionMetadata {
155 &self.partition
156 }
157
158 pub fn index(&self) -> &ClubcardIndex {
159 &self.index
160 }
161 }
162
163 /// Helper trait for (approximate) heap memory usage analysis in Firefox
164 pub trait ApproximateSizeOf {
165 fn approximate_size_of(&self) -> usize
166 where
167 Self: Sized,
168 {
169 size_of::<Self>()
170 }
171 }
172
173 impl ApproximateSizeOf for () {}
174
175 impl ApproximateSizeOf for ClubcardIndex {
176 fn approximate_size_of(&self) -> usize {
177 size_of::<ClubcardIndex>() + self.len() * size_of::<ClubcardIndexEntry>()
178 }
179 }
180
181 impl<const W: usize, UniverseMetadata, PartitionMetadata> ApproximateSizeOf
182 for Clubcard<W, UniverseMetadata, PartitionMetadata>
183 where
184 UniverseMetadata: ApproximateSizeOf,
185 PartitionMetadata: ApproximateSizeOf,
186 {
187 fn approximate_size_of(&self) -> usize {
188 self.universe.approximate_size_of()
189 + self.partition.approximate_size_of()
190 + self.index.approximate_size_of()
191 + size_of::<Vec<Vec<u8>>>()
192 + 8 * self.approx_filter.iter().map(|x| x.len()).sum::<usize>()
193 + size_of::<Vec<u8>>()
194 + 8 * self.exact_filter.len()
195 }
196 }