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
use crate::const_utils::{low_bit_mask_u64, min_usize};

use std::{
    fmt::{self, Debug},
    iter::ExactSizeIterator,
    marker::PhantomData,
};

/// An array of 64 binary enums.
#[must_use = "BoolArray is returned by value by every mutating method."]
#[derive(StableAbi, PartialEq, Eq)]
#[repr(transparent)]
pub struct BoolArray<T> {
    bits: u64,
    _marker: PhantomData<T>,
}

impl<T> Copy for BoolArray<T> {}
impl<T> Clone for BoolArray<T> {
    fn clone(&self) -> Self {
        Self {
            bits: self.bits,
            _marker: PhantomData,
        }
    }
}

/// An array with whether the ith field of a prefix-type
/// is accessible through its accessor method.
pub type FieldAccessibility = BoolArray<IsAccessible>;

/// An array with whether the ith field in the prefix of a prefix-type
/// is conditional,which means whether it has the
/// `#[sabi(accessible_if=" expression ")]` attribute applied to it.
pub type FieldConditionality = BoolArray<IsConditional>;

impl<T> BoolArray<T> {
    /// Creates a BoolArray where the first `count` elements are truthy.
    #[inline]
    pub const fn with_count(count: usize) -> Self {
        Self {
            bits: low_bit_mask_u64(count as u32),
            _marker: PhantomData,
        }
    }

    /// Creates a BoolArray from a u64.
    #[inline]
    pub const fn from_u64(bits: u64) -> Self {
        Self {
            bits,
            _marker: PhantomData,
        }
    }

    /// Creates a BoolArray where all elements are falsy.
    #[inline]
    pub const fn empty() -> Self {
        Self {
            bits: 0,
            _marker: PhantomData,
        }
    }

    #[inline]
    const fn index_to_bits(index: usize) -> u64 {
        let index = index as u32;
        [0, 1u64.wrapping_shl(index)][(index <= 63) as usize]
    }

    /// Truncates self so that only the first `length` elements are truthy.
    pub const fn truncated(mut self, length: usize) -> Self {
        let mask = Self::with_count(length).bits();
        self.bits &= mask;
        self
    }

    /// Converts this array to its underlying representation
    #[inline]
    pub const fn bits(self) -> u64 {
        self.bits
    }

    /// An iterator over the first `count` elements of the array.
    pub const fn iter_count(self, count: usize) -> BoolArrayIter<T> {
        BoolArrayIter {
            count: min_usize(64, count),
            bits: self.bits(),
            _marker: PhantomData,
        }
    }

    /// Whether this array is equal to `other` up to the `count` element.
    pub fn is_compatible(self, other: Self, count: usize) -> bool {
        let all_accessible = Self::with_count(count);
        let implication = (!self.bits | other.bits) & all_accessible.bits;
        println!(
            "self:{:b}\nother:{:b}\nall_accessible:{:b}\nimplication:{:b}",
            self.bits, other.bits, all_accessible.bits, implication,
        );
        implication == all_accessible.bits
    }
}

impl FieldAccessibility {
    /// Queries whether the field at the `index` position is accessible.
    #[inline]
    pub const fn is_accessible(self, index: usize) -> bool {
        let bits = Self::index_to_bits(index);
        (self.bits & bits) != 0
    }

    /// Sets the accessibility of a field based on `cond`,
    /// on IsAccessible::Yes the field becomes accessible,
    /// on IsAccessible::No the field becomes inaccessible.
    #[inline]
    pub const fn set_accessibility(mut self, index: usize, cond: IsAccessible) -> Self {
        let bits = Self::index_to_bits(index);
        self.bits = [self.bits & !bits, self.bits | bits][cond as usize];
        self
    }
}

impl FieldConditionality {
    /// Queries whether the field at the `index` position is conditional.
    #[inline]
    pub const fn is_conditional(self, index: usize) -> bool {
        let bits = Self::index_to_bits(index);
        (self.bits & bits) != 0
    }

    /// Sets the conditionality of a field based on `cond`,
    /// on IsConditional::Yes the field becomes conditional,
    /// on IsConditional::No the field becomes unconditional.
    #[inline]
    pub const fn set_conditionality(mut self, index: usize, cond: IsConditional) -> Self {
        let bits = Self::index_to_bits(index);
        self.bits = [self.bits & !bits, self.bits | bits][cond as usize];
        self
    }
}

impl<T> Debug for BoolArray<T>
where
    T: BooleanEnum,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter_count(64)).finish()
    }
}

////////////////////////////////////////////////////////////////////////////////

/// A trait for enums with two variants where one is `truthy` and the other one is `falsy`.
pub trait BooleanEnum: Debug {
    /// The custom name of this type.
    const NAME: &'static str;

    /// Constructs this type from a boolean
    fn from_bool(b: bool) -> Self;
}

////////////////////////////////////////////////////////////////////////////////

/// Whether a field is accessible.
#[derive(StableAbi, Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum IsAccessible {
    No = 0,
    Yes = 1,
}

impl IsAccessible {
    /// Constructs an IsAccessible with a bool saying whether this is accessible.
    pub const fn new(is_accessible: bool) -> Self {
        [IsAccessible::No, IsAccessible::Yes][is_accessible as usize]
    }
    /// Describes whether this is accessible.
    pub const fn is_accessible(self) -> bool {
        self as usize != 0
    }
}

impl BooleanEnum for IsAccessible {
    const NAME: &'static str = "IsAccessible";

    fn from_bool(b: bool) -> Self {
        Self::new(b)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Whether a field is conditional,
/// whether it has a `#[sabi(accessible_if=" expression ")]` helper attribute or not.
#[derive(StableAbi, Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum IsConditional {
    No = 0,
    Yes = 1,
}

impl IsConditional {
    /// Constructs an IsConditional with a bool saying this is conditional.
    pub const fn new(is_accessible: bool) -> Self {
        [IsConditional::No, IsConditional::Yes][is_accessible as usize]
    }
    /// Describes whether this is conditional.
    pub const fn is_conditional(self) -> bool {
        self as usize != 0
    }
}

impl BooleanEnum for IsConditional {
    const NAME: &'static str = "IsConditional";

    fn from_bool(b: bool) -> Self {
        Self::new(b)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone)]
pub struct BoolArrayIter<T> {
    count: usize,
    bits: u64,
    _marker: PhantomData<T>,
}

impl<T> BoolArrayIter<T>
where
    T: BooleanEnum,
{
    #[inline]
    fn next_inner<F>(&mut self, f: F) -> Option<T>
    where
        F: FnOnce(&mut Self) -> bool,
    {
        if self.count == 0 {
            None
        } else {
            Some(T::from_bool(f(self)))
        }
    }
}
impl<T> Iterator for BoolArrayIter<T>
where
    T: BooleanEnum,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.next_inner(|this| {
            this.count -= 1;
            let cond = (this.bits & 1) != 0;
            this.bits >>= 1;
            cond
        })
    }

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

impl<T> DoubleEndedIterator for BoolArrayIter<T>
where
    T: BooleanEnum,
{
    fn next_back(&mut self) -> Option<T> {
        self.next_inner(|this| {
            this.count -= 1;
            (this.bits & (1 << this.count)) != 0
        })
    }
}

impl<T> ExactSizeIterator for BoolArrayIter<T>
where
    T: BooleanEnum,
{
    #[inline]
    fn len(&self) -> usize {
        self.count
    }
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

#[cfg(all(test, not(feature = "only_new_tests")))]
mod tests {
    use super::*;

    #[test]
    fn with_count() {
        for count in 0..=64 {
            let accessibility = BoolArray::with_count(count);

            for i in 0..64 {
                assert_eq!(
                    accessibility.is_accessible(i),
                    i < count,
                    "count={} accessibility={:b}",
                    count,
                    accessibility.bits()
                );
            }
        }
    }

    #[test]
    fn set_accessibility() {
        let mut accessibility = BoolArray::with_count(8);
        assert_eq!(0b_1111_1111, accessibility.bits());

        {
            let mut accessibility = accessibility;

            accessibility = accessibility.set_accessibility(0, IsAccessible::No);
            assert_eq!(0b_1111_1110, accessibility.bits());

            accessibility = accessibility.set_accessibility(2, IsAccessible::No);
            assert_eq!(0b_1111_1010, accessibility.bits());

            accessibility = accessibility.set_accessibility(1, IsAccessible::No);
            assert_eq!(0b_1111_1000, accessibility.bits());
        }

        accessibility = accessibility.set_accessibility(3, IsAccessible::No);
        assert_eq!(0b_1111_0111, accessibility.bits());

        accessibility = accessibility.set_accessibility(5, IsAccessible::No);
        assert_eq!(0b_1101_0111, accessibility.bits());

        accessibility = accessibility.set_accessibility(6, IsAccessible::No);
        assert_eq!(0b_1001_0111, accessibility.bits());

        accessibility = accessibility.set_accessibility(10, IsAccessible::Yes);
        assert_eq!(0b_0100_1001_0111, accessibility.bits());

        accessibility = accessibility.set_accessibility(63, IsAccessible::Yes);
        assert_eq!((1 << 63) | 0b_0100_1001_0111, accessibility.bits());
    }

    #[test]
    fn empty() {
        let accessibility = BoolArray::empty();

        for i in 0..64 {
            assert!(
                !accessibility.is_accessible(i),
                "i={} accessibility={:b}",
                i,
                accessibility.bits()
            );
        }
    }

    #[test]
    fn iter_test() {
        let iter = BoolArray::with_count(8)
            .set_accessibility(1, IsAccessible::No)
            .set_accessibility(3, IsAccessible::No)
            .iter_count(10)
            .map(IsAccessible::is_accessible);

        let expected = vec![
            true, false, true, false, true, true, true, true, false, false,
        ];
        let expected_rev = expected.iter().cloned().rev().collect::<Vec<bool>>();

        assert_eq!(iter.clone().collect::<Vec<bool>>(), expected);

        assert_eq!(iter.clone().rev().collect::<Vec<bool>>(), expected_rev);
    }
}