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
//! [`BitSet`] methods that treat it as a set of integers specifically.
use crate::*;
impl<W: Word> BitSet<W> {
/// Whether the elements form a contiguous interval.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let mut set = set![4..=6];
/// assert_eq!(set.is_interval(), true);
/// set.remove(5);
/// assert_eq!(set.is_interval(), false);
///
/// // Empty sets and singletons are intervals.
/// assert!(set![].is_interval());
/// assert!(set![5].is_interval());
/// ```
#[inline]
pub fn is_interval(self) -> bool {
if self.is_empty() {
true
} else {
Self::BITS - (self.0.leading_zeros() + self.0.trailing_zeros()) as usize == self.len()
}
}
/// The smallest element in the set, if any.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// assert_eq!(set![].min(), None);
/// assert_eq!(set![4..=6].min(), Some(4));
/// ```
#[inline]
pub fn min(self) -> Option<Element> {
if self.is_empty() {
None
} else {
Some(self.0.trailing_zeros() as Element)
}
}
/// The largest element in the set, if any.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// assert_eq!(set![].max(), None);
/// assert_eq!(set![4..=6].max(), Some(6));
/// ```
#[inline]
pub fn max(self) -> Option<Element> {
if self.is_empty() {
None
} else {
Some(Self::MAX - self.0.leading_zeros() as Element)
}
}
/// The sum of all elements in the set.
///
/// Returns `0` for the empty set.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// assert_eq!(set![].sum(), 0);
/// assert_eq!(set![1, 2, 4, 8].sum(), 15);
/// ```
#[inline]
pub fn sum(self) -> Element {
self.iter().sum()
}
/// Ordinal position of an element in the set, counted from zero.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let set = bitset![u8; 4..=6];
/// assert_eq!(set.position(3), None);
/// assert_eq!(set.position(4), Some(0));
/// assert_eq!(set.position(6), Some(2));
/// assert_eq!(set.position(8), None);
/// ```
#[inline]
pub fn position(self, e: Element) -> Option<usize> {
if e <= Self::MAX && self.contains(e) {
Some(self.position_unchecked(e))
} else {
None
}
}
/// Ordinal position of an element assumed to be in the set, counted from zero.
///
/// # Preconditions
///
/// The caller must ensure that `e` is contained in the set.
#[inline]
pub fn position_unchecked(self, e: Element) -> usize {
debug_assert!(self.contains(e));
(self.0 & ((W::ONE << e) - W::ONE)).count_ones() as usize
}
/// Ordinal position of an element in the set, counted from one.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let set = bitset![u8; 4..=6];
/// assert_eq!(set.rank(3), None);
/// assert_eq!(set.rank(4), Some(1));
/// assert_eq!(set.rank(6), Some(3));
/// assert_eq!(set.rank(8), None);
/// ```
#[inline]
pub fn rank(self, e: Element) -> Option<usize> {
self.position(e).map(|p| p + 1)
}
/// Ordinal position of an element assumed to be in the set, counted from one.
///
/// # Preconditions
///
/// The caller must ensure that `e` is contained in the set.
#[inline]
pub fn rank_unchecked(self, e: Element) -> usize {
debug_assert!(self.contains(e));
self.position_unchecked(e) + 1
}
/// Try to add each element in `self` to each element in `other`.
///
/// # Errors
///
/// If resulting elements are not representable (above [`Self::MAX`]).
///
/// See [`Self::truncating_sumset`] for a variant that drops irrepresentable elements.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// use pibs::Error::Irrepresentable;
///
/// let a = set![2, 8];
/// let b = set![1, 5];
/// assert_eq!(a.sumset(b), Ok(set![3, 7, 9, 13]));
/// assert_eq!(a.sumset(set![]), Ok(set![]));
/// assert_eq!(a.sumset(set![0]), Ok(a));
/// assert_eq!(a.sumset(Set::full()), Err(Irrepresentable));
/// ```
#[inline]
pub fn sumset(self, other: Self) -> Result<Self, Error> {
let mut result = W::ZERO;
let (smaller, larger_word) = if self.len() < other.len() {
(self, other.0)
} else {
(other, self.0)
};
let e_max = larger_word.leading_zeros() as Element;
for e in smaller {
if e > e_max {
return Err(Error::Irrepresentable);
}
result |= larger_word << e;
}
Ok(Self(result))
}
/// Add each element in `self` to each element in `other`.
///
/// If resulting elements are not representable (above [`Self::MAX`]), they are discarded.
///
/// See [`Self::sumset`] for a checked variant.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let a = set![2, 8];
/// let b = set![1, 5];
/// assert_eq!(a.truncating_sumset(b), set![3, 7, 9, 13]);
/// assert_eq!(a.truncating_sumset(set![]), set![]);
/// assert_eq!(a.truncating_sumset(set![0]), a);
/// assert_eq!(a.truncating_sumset(Set::full()), Set::full() - set![0, 1]);
/// ```
#[inline]
pub fn truncating_sumset(self, other: Self) -> Self {
let mut result = W::ZERO;
let (smaller, larger_word) = if self.len() < other.len() {
(self, other.0)
} else {
(other, self.0)
};
for e in smaller {
result |= larger_word << e;
}
Self(result)
}
/// Sum the elements in each subset of the set and collect these sums in a new set.
///
/// # Errors
///
/// If resulting elements are not representable (above [`Self::MAX`]).
///
/// See [`Self::truncating_subset_sums`] for a variant that drops irrepresentable elements.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// use pibs::Error::Irrepresentable;
///
/// assert_eq!(set![].subset_sums(), Ok(set![0]));
/// assert_eq!(set![0].subset_sums(), Ok(set![0]));
/// assert_eq!(set![1, 2, 4, 8].subset_sums(), Ok(set![0..16]));
/// assert_eq!(set![1..=5].subset_sums(), Ok(set![0..16]));
///
/// // Overflows are checked.
/// assert_eq!(set![1, 3, 7].subset_sums(), Ok(set![0, 1, 3, 4, 7, 8, 10, 11]));
/// assert_eq!(bitset![u8; 1, 3, 7].subset_sums(), Err(Irrepresentable));
/// ```
#[inline]
pub fn subset_sums(self) -> Result<Self, Error> {
let mut result = W::ONE;
let mut e_max = result.leading_zeros() as Element;
for e in self {
if e > e_max {
return Err(Error::Irrepresentable);
}
e_max -= e;
result |= result << e;
}
Ok(Self(result))
}
/// Sum the elements in each subset of the set and collect these sums in a new set.
///
/// If resulting elements are not representable (above [`Self::MAX`]), they are discarded.
///
/// See [`Self::subset_sums`] for a checked variant.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// assert_eq!(set![].truncating_subset_sums(), set![0]);
/// assert_eq!(set![0].truncating_subset_sums(), set![0]);
/// assert_eq!(set![1, 2, 4, 8].truncating_subset_sums(), set![0..16]);
/// assert_eq!(set![1..=5].truncating_subset_sums(), set![0..16]);
///
/// // Overflows are truncated.
/// assert_eq!(set![1, 3, 7].truncating_subset_sums(), set![0, 1, 3, 4, 7, 8, 10, 11]);
/// assert_eq!(bitset![u8; 1, 3, 7].truncating_subset_sums(), bitset![u8; 0, 1, 3, 4, 7]);
/// ```
#[inline]
pub fn truncating_subset_sums(self) -> Self {
let mut result = W::ONE;
for e in self {
result |= result << e;
}
Self(result)
}
/// Try to add a number to each element in the set.
///
/// # Errors
///
/// If resulting elements are not representable (above [`Self::MAX`]).
///
/// See [`Self::truncating_map_add`] for a variant that drops irrepresentable elements.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// use pibs::Error::Irrepresentable;
///
/// let set = bitset![u8; 1..=3, 5];
/// assert_eq!(set.map_add(2), Ok(bitset![u8; 3..=5, 7]));
/// assert_eq!(set.map_add(3), Err(Irrepresentable));
/// assert_eq!(set![].map_add(usize::MAX), Ok(set![]));
/// ```
#[inline]
pub fn map_add(self, e: Element) -> Result<Self, Error> {
if self.is_empty() {
Ok(Self::new())
} else if e > self.0.leading_zeros() as Element {
Err(Error::Irrepresentable)
} else {
Ok(self.truncating_map_add(e))
}
}
/// Try to subtract a number from each element in the set.
///
/// # Errors
///
/// If resulting elements are not representable (below zero).
///
/// See [`Self::truncating_map_sub`] for a variant that drops irrepresentable elements.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// use pibs::Error::Irrepresentable;
///
/// let set = set![1..=3, 5];
/// assert_eq!(set.map_sub(1), Ok(set![0..=2, 4]));
/// assert_eq!(set.map_sub(3), Err(Irrepresentable));
/// assert_eq!(set![].map_sub(usize::MAX), Ok(set![]));
/// ```
#[inline]
pub fn map_sub(self, e: Element) -> Result<Self, Error> {
if self.is_empty() {
Ok(Self::new())
} else if e > self.0.trailing_zeros() as Element {
Err(Error::Irrepresentable)
} else {
Ok(self.truncating_map_sub(e))
}
}
/// Add a number to each element in the set.
///
/// This is the same as `self << e`.
///
/// If resulting elements are not representable (above [`Self::MAX`]), they are discarded.
///
/// See [`Self::map_add`] for a checked variant.
///
/// # Preconditions
///
/// The caller must ensure that `e <= Self::MAX`, even if `self.is_empty()`.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let set = bitset![u8; 1..=3, 5];
/// assert_eq!(set.truncating_map_add(2), bitset![u8; 3..=5, 7]);
/// assert_eq!(set.truncating_map_add(3), bitset![u8; 4..=6]);
/// ```
#[inline]
pub fn truncating_map_add(self, e: Element) -> Self {
Self::debug_bound_check(e);
Self(self.0 << e)
}
/// Subtract a number from each element in the set.
///
/// This is the same as `self >> e`.
///
/// If resulting elements are not representable (below zero), they are discarded.
///
/// See [`Self::map_sub`] for a checked variant.
///
/// # Preconditions
///
/// The caller must ensure that `e <= Self::MAX`, even if `self.is_empty()`.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let set = set![1..=3, 5];
/// assert_eq!(set.truncating_map_sub(1), set![0..=2, 4]);
/// assert_eq!(set.truncating_map_sub(3), set![0, 2]);
/// ```
#[inline]
pub fn truncating_map_sub(self, e: Element) -> Self {
Self::debug_bound_check(e);
Self(self.0 >> e)
}
/// Try to add or subtract a number to or from each element in the set.
///
/// # Errors
///
/// If resulting elements are not representable (below zero or above [`Self::MAX`]).
///
/// See [`Self::truncating_translate`] for a variant that drops irrepresentable elements.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// use pibs::Error::Irrepresentable;
///
/// let set = bitset![u8; 1..=3, 5];
/// assert_eq!(set.translate(2), Ok(bitset![u8; 3..=5, 7]));
/// assert_eq!(set.translate(-1), Ok(bitset![u8; 0..=2, 4]));
/// assert_eq!(set.translate(-2), Err(Irrepresentable));
/// assert_eq!(set![].translate(i32::MIN), Ok(set![]));
/// assert_eq!(set![].translate(i32::MAX), Ok(set![]));
/// ```
#[inline]
pub fn translate(self, add: i32) -> Result<Self, Error> {
if self.is_empty() {
Ok(Self::new())
} else if add >= 0 {
self.map_add(add.try_into().map_err(|_| Error::Irrepresentable)?)
} else {
self.map_sub(
add.unsigned_abs()
.try_into()
.map_err(|_| Error::Irrepresentable)?,
)
}
}
/// Add or subtract a number to or from each element in the set.
///
/// If resulting elements are not representable (below zero or above [`Self::MAX`]), they are
/// discarded.
///
/// See [`Self::translate`] for a checked variant.
///
/// # Preconditions
///
/// The caller must ensure that `add.unsigned_abs() <= Self::MAX`, even if `self.is_empty()`.
///
/// # Examples
///
/// ```
/// # use pibs::prelude::*;
/// let set = bitset![u8; 1..=3, 5];
/// assert_eq!(set.truncating_translate(2), bitset![u8; 3..=5, 7]);
/// assert_eq!(set.truncating_translate(-1), bitset![u8; 0..=2, 4]);
/// assert_eq!(set.truncating_translate(-2), bitset![u8; 0, 1, 3]);
/// ```
#[inline]
pub fn truncating_translate(self, add: i32) -> Self {
debug_assert!(Element::try_from(add.unsigned_abs()).is_ok());
if add >= 0 {
self.truncating_map_add(add as Element)
} else {
self.truncating_map_sub(add.unsigned_abs() as Element)
}
}
}