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
//! Iterate over a collection of bits.
//!
//! # Usage
//!
//! This crate is available [on crates.io][crate] and can be used by adding the
//! following to your project's `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! bit_collection = "0.2.3"
//! ```
//!
//! and this to your crate root:
//!
//! ```
//! #[macro_use]
//! extern crate bit_collection;
//! # fn main() {}
//! ```
//!
//! # `#[bit]` Attribute
//!
//! The `#[bit]` attribute is composed of three parts, two of which are optional
//! in some cases. The components can be provided in any order.
//!
//! ## Type:
//!
//! The type used to represent individual bits. This part is required.
//!
//! ```rust,ignore
//! #[bit(Type, ...)]
//! ```
//!
//! ## Mask:
//! A mask indicating the valid bits of the collection. This should be a
//! constant expression.
//!
//! If not provided, the mask is assumed to have all bits set (i.e. `!0`).
//!
//! [`BitCollection::FULL`][FULL] returns this value.
//!
//! **Attention:** Please read the section on [safety](#safety) to ensure
//! that this is used in a _correct_ and _safe_ manner.
//!
//! ```rust,ignore
//! #[bit(..., mask = "0b11", ...)]
//! ```
//!
//! ## Retriever:
//! The suffix for retrieving the inner integer value of the bit type. It
//! expands to `$value.$retr`. Because of this, the provided retriever must be
//! visible where the derive is located.
//!
//! If not provided, the bit type is assumed to be an `enum` that can be
//! casted to an integer.
//!
//! ```rust,ignore
//! #[bit(..., retr = "inner", ...)]
//! ```
//!
//! ## Iterator:
//! The iterator for a given [`BitCollection`]. If [`BitIter`] isn't imported
//! as-is, this option allows for specifying its module path.
//!
//! ```rust,ignore
//! extern crate bit_collection as bc;
//!
//! #[bit(..., iter = "bc::BitIter", ...)]
//! ```
//!
//! # Examples
//!
//! In computer chess, one popular way of representing the occupants of a board
//! is through a [`Bitboard`][bitboard] type. In this type, each individual bit
//! is a square on a chess board.
//!
//! ```
//! # include!("../templates/imports.rs");
//! #[derive(Copy, Clone)]
//! pub struct Square(u8);
//!
//! /// A set of sixty-four `Square`s.
//! #[bit(Square, mask = "!0", retr = "0")]
//! #[derive(BitCollection)]
//! pub struct Bitboard(u64);
//!
//! # fn main() {}
//! ```
//!
//! We can also represent castle rights this way.
//!
//! ```
//! # include!("../templates/imports.rs");
//! #[derive(Copy, Clone)]
//! pub enum CastleRight {
//!     WhiteKingside,
//!     BlackKingside,
//!     WhiteQueenside,
//!     BlackQueenside,
//! }
//!
//! /// A set of `CastleRight`s.
//! #[bit(CastleRight, mask = "0b1111")]
//! #[derive(BitCollection)]
//! pub struct CastleRights {
//!     bits: u8
//! }
//!
//! fn iterate_over(rights: CastleRights) {
//!     for right in rights {
//!         match right {
//!             CastleRight::WhiteKingside  => { /* ... */ },
//!             CastleRight::BlackKingside  => { /* ... */ },
//!             CastleRight::WhiteQueenside => { /* ... */ },
//!             CastleRight::BlackQueenside => { /* ... */ },
//!         }
//!     }
//! }
//!
//! # fn main() {}
//! ```
//!
//! # Safety
//! This crate makes certain assumptions that, if unmet, may have unsafe and
//! unexpected results.
//!
//! The [`mask`](#mask) option for [`#[bit]`](#bit-attribute) _must_ have the
//! correct bits set. It _must not_ have bits set that correspond to invalid
//! instances of the bit type.
//!
//! Similarly, the bit type must be defined such that corresponding bit patterns
//! from `mask` provide legitimate values. Ask yourself, do `1 << item` and its
//! reversal (undo) operations, `pop_{lsb,msb}`, make sense in terms of the
//! provided mask?
//!
//! [crate]: https://crates.io/crates/bit_collection
//! [`BitCollection`]: trait.BitCollection.html
//! [`BitIter`]: struct.BitIter.html
//! [FULL]: trait.BitCollection.html#associatedconstant.FULL
//! [bitboard]: https://chessprogramming.wikispaces.com/Bitboards

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
extern crate core;

use core::borrow::{Borrow, BorrowMut};
use core::cmp::Ordering;
use core::iter::FromIterator;
use core::ops;

// Reexport derive macro.
#[allow(unused_imports)]
#[macro_use]
extern crate bit_collection_derive;
#[doc(hidden)]
pub use bit_collection_derive::*;

/// A type that represents a collection of bits that can be iterated over.
pub trait BitCollection: From<<Self as IntoIterator>::Item>
    + From<BitIter<Self>>
    + IntoIterator<IntoIter=BitIter<Self>>
    + FromIterator<<Self as IntoIterator>::Item>
    + Extend<<Self as IntoIterator>::Item>
    + ops::Not<Output=Self>
    + ops::BitAnd<Output=Self>
    + ops::BitAndAssign
    + ops::BitOr<Output=Self>
    + ops::BitOrAssign
    + ops::BitXor<Output=Self>
    + ops::BitXorAssign
    + ops::Sub<Output=Self>
    + ops::SubAssign
{
    /// A full instance with all bits set.
    const FULL: Self;

    /// An empty instance with no bits set.
    const EMPTY: Self;

    /// Returns the number of bits set in `self`.
    ///
    /// If checking whether `self` has zero, one, or multiple bits set, use
    /// [`quantity`](#method.quantity).
    fn len(&self) -> usize;

    /// Returns whether `self` is empty.
    fn is_empty(&self) -> bool;

    /// Returns whether `self` has multiple bits set.
    fn has_multiple(&self) -> bool;

    /// Returns the quantity of bits set.
    ///
    /// For an exact measurement of the number of bits set, use
    /// [`len`](#tymethod.len).
    ///
    /// This is much more optimal than matching [`len`](#tymethod.len) against
    /// `0`, `1`, and `_`.
    #[inline]
    fn quantity(&self) -> Quantity {
        use self::Quantity::*;
        if self.is_empty() {
            None
        } else if self.has_multiple() {
            Multiple
        } else {
            Single
        }
    }

    /// Returns `self` as an iterator over itself.
    ///
    /// # Examples
    ///
    /// This method is useful for partially iterating over a `BitCollection`
    /// in-place, and thus mutating it.
    ///
    /// ```
    /// # include!("../templates/imports.rs");
    /// # include!("../templates/castle_rights.rs");
    /// # fn main() {
    /// let mut rights = CastleRights::FULL;
    /// assert_eq!(rights.len(), 4);
    ///
    /// for right in rights.as_iter().take(3) { /* ... */ }
    /// assert_eq!(rights.len(), 1);
    /// # }
    /// ```
    #[inline]
    fn as_iter(&mut self) -> &mut BitIter<Self> {
        unsafe { &mut *(self as *mut _ as *mut _) }
    }

    /// Converts `self` into the only bit set.
    #[inline]
    fn into_bit(mut self) -> Option<Self::Item> {
        let bit = self.pop_lsb();
        if self.is_empty() { bit } else { None }
    }

    /// Returns the least significant bit in `self` if `self` is not empty.
    #[inline]
    fn lsb(&self) -> Option<Self::Item> {
        if self.is_empty() { None } else {
            unsafe { Some(self.lsb_unchecked()) }
        }
    }

    /// Returns the most significant bit in `self` if `self` is not empty.
    #[inline]
    fn msb(&self) -> Option<Self::Item> {
        if self.is_empty() { None } else {
            unsafe { Some(self.msb_unchecked()) }
        }
    }

    /// Returns the least significant bit in `self` without checking whether
    /// `self` is empty.
    unsafe fn lsb_unchecked(&self) -> Self::Item;

    /// Returns the most significant bit in `self` without checking whether
    /// `self` is empty.
    unsafe fn msb_unchecked(&self) -> Self::Item;

    /// Removes the least significant bit from `self`.
    fn remove_lsb(&mut self);

    /// Removes the most significant bit from `self`.
    fn remove_msb(&mut self);

    /// Removes the least significant bit from `self` and returns it.
    fn pop_lsb(&mut self) -> Option<Self::Item>;

    /// Removes the most significant bit from `self` and returns it.
    fn pop_msb(&mut self) -> Option<Self::Item>;

    /// Returns whether `self` contains the value.
    fn contains<T: Into<Self>>(&self, T) -> bool;

    /// Returns the result of removing the value from `self`.
    #[inline]
    fn removing<T: Into<Self>>(self, other: T) -> Self {
        self - other.into()
    }

    /// Returns the result of inserting the value into `self`.
    #[inline]
    fn inserting<T: Into<Self>>(self, other: T) -> Self {
        self | other.into()
    }

    /// Returns the result of toggling the bits of the value in `self`.
    #[inline]
    fn toggling<T: Into<Self>>(self, other: T) -> Self {
        self ^ other.into()
    }

    /// Returns the result of intersecting the bits of the value with `self`.
    #[inline]
    fn intersecting<T: Into<Self>>(self, other: T) -> Self {
        self & other.into()
    }

    /// Returns the result of setting the bits of the value in `self` based on
    /// `condition`.
    #[inline]
    fn setting<T: Into<Self>>(self, other: T, condition: bool) -> Self {
        if condition {
            self.inserting(other)
        } else {
            self.removing(other)
        }
    }

    /// Removes the value from `self`.
    #[inline]
    fn remove<T: Into<Self>>(&mut self, other: T) -> &mut Self {
        *self -= other.into();
        self
    }

    /// Inserts the value into `self`.
    #[inline]
    fn insert<T: Into<Self>>(&mut self, other: T) -> &mut Self {
        *self |= other.into();
        self
    }

    /// Toggles bits of the value in `self`.
    #[inline]
    fn toggle<T: Into<Self>>(&mut self, other: T) -> &mut Self {
        *self ^= other.into();
        self
    }

    /// Intersects the bits of the value with `self`.
    #[inline]
    fn intersect<T: Into<Self>>(&mut self, other: T) -> &mut Self {
        *self &= other.into();
        self
    }

    /// Sets the bits of the value in `self` based on `condition`.
    #[inline]
    fn set<T: Into<Self>>(&mut self, other: T, condition: bool) -> &mut Self {
        if condition {
            self.insert(other)
        } else {
            self.remove(other)
        }
    }
}

/// An iterator over the bits of a [`BitCollection`](trait.BitCollection.html).
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct BitIter<C: BitCollection>(pub C);

impl<C: BitCollection> From<C> for BitIter<C> {
    #[inline(always)]
    fn from(bits: C) -> Self { BitIter(bits) }
}

impl<C: BitCollection> AsRef<C> for BitIter<C> {
    #[inline(always)]
    fn as_ref(&self) -> &C { &self.0 }
}

impl<C: BitCollection> AsMut<C> for BitIter<C> {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut C { &mut self.0 }
}

impl<C: BitCollection> Borrow<C> for BitIter<C> {
    #[inline(always)]
    fn borrow(&self) -> &C { self.as_ref() }
}

impl<C: BitCollection> BorrowMut<C> for BitIter<C> {
    #[inline(always)]
    fn borrow_mut(&mut self) -> &mut C { self.as_mut() }
}

impl<C: BitCollection> Iterator for BitIter<C> {
    type Item = C::Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop_lsb()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }

    #[inline]
    fn count(self) -> usize {
        self.len()
    }

    #[inline]
    fn last(self) -> Option<Self::Item> {
        self.0.msb()
    }
}

impl<C: BitCollection> DoubleEndedIterator for BitIter<C> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.pop_msb()
    }
}

impl<C: BitCollection> ExactSizeIterator for BitIter<C> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

/// How many bits are set in a [`BitCollection`](trait.BitCollection.html) as
/// returned by [`quantity`](trait.BitCollection.html#method.quantity).
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum Quantity {
    // NOTE: The variant order is optimized for the quantity method
    /// Multiple bits set.
    Multiple,
    /// Single bit set.
    Single,
    /// No bits set.
    None,
}

impl PartialOrd for Quantity {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }

    #[inline]
    fn lt(&self, other: &Self) -> bool { (*self as usize) > (*other as usize) }

    #[inline]
    fn gt(&self, other: &Self) -> bool { (*self as usize) < (*other as usize) }

    #[inline]
    fn le(&self, other: &Self) -> bool { (*self as usize) >= (*other as usize) }

    #[inline]
    fn ge(&self, other: &Self) -> bool { (*self as usize) <= (*other as usize) }
}

impl Ord for Quantity {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        use Ordering::*;
        match (*self as usize).cmp(&(*other as usize)) {
            Equal => Equal,
            Greater => Less,
            Less => Greater,
        }
    }
}