foundation_core 0.0.6

Central crate for all foundation crates for the ewe-platform project
Documentation
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
466
467
468
469
470
471
472
473
474
475
476
477
use std::cell;
use std::fmt;
use std::fmt::Debug;
use std::mem::size_of;
use std::ops::{Deref, Index, RangeBounds};
use std::rc;
use std::result;
use std::vec::Drain;

#[derive(Clone, Debug, Eq, PartialEq, Copy)]
pub enum MemoryErrors {
    MemoryLimitExceededError,
}

impl fmt::Display for MemoryErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MemoryErrors::MemoryLimitExceededError => write!(f, "The memory limit has been exceeded"),
        }
    }
}

impl std::error::Error for MemoryErrors {}

type SharedMemoryLimiter = rc::Rc<cell::RefCell<MemoryLimiter>>;

type MemoryResult<T> = result::Result<T, MemoryErrors>;

#[derive(Debug, Clone)]
pub struct MemoryLimiter {
    current_usage: usize,
    max: usize,
}

impl MemoryLimiter {
    #[must_use]
    pub fn create_shared(max: usize) -> SharedMemoryLimiter {
        rc::Rc::new(cell::RefCell::new(MemoryLimiter {
            current_usage: 0,
            max,
        }))
    }

    #[must_use]
    pub fn non_shared(max: usize) -> MemoryLimiter {
        Self {
            current_usage: 0,
            max,
        }
    }

    #[inline]
    pub fn set_capacity(&mut self, new_max: usize) {
        self.max = new_max;
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.max
    }

    #[inline]
    #[must_use]
    pub fn current_usage(&self) -> usize {
        self.current_usage
    }

    /// Preallocate memory by the specified amount.
    ///
    /// # Panics
    /// Panics if the allocation exceeds the memory limit.
    #[inline]
    pub fn preallocate(&mut self, by_amount: usize) {
        self.increase_usage(by_amount)
            .expect("allocated memory size amount");
    }

    #[inline]
    pub fn decrease_usage(&mut self, by_amount: usize) {
        if self.current_usage == 0 {
            return;
        }
        self.current_usage -= by_amount;
    }

    /// Increase the current memory usage by the specified amount.
    ///
    /// # Errors
    /// Returns `MemoryErrors::MemoryLimitExceededError` if the new usage exceeds the maximum capacity.
    #[inline]
    pub fn increase_usage(&mut self, by_amount: usize) -> MemoryResult<()> {
        self.current_usage += by_amount;

        if self.current_usage > self.max {
            return Err(MemoryErrors::MemoryLimitExceededError);
        }

        Ok(())
    }
}

/// Arena provides a pre-allocated memory that can grow and wont de-allocates
/// will still being used and in the liftetime of
#[derive(Debug, Clone)]
pub struct Arena {
    limiter: SharedMemoryLimiter,
    data: Vec<u8>,
}

impl Arena {
    pub fn new(limiter: SharedMemoryLimiter, preallocate: usize) -> Self {
        limiter.borrow_mut().preallocate(preallocate);

        Self {
            limiter,
            data: Vec::with_capacity(preallocate),
        }
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.data
    }

    // shift moves the data from the starting point of the amount basically using
    // it has the starting index to copy the data to teh start of the internal memory location
    // truncating any data after copying.
    pub fn shift(&mut self, by_amount: usize) {
        self.data.copy_within(by_amount.., 0);
        self.data.truncate(self.data.len() - by_amount);
    }

    /// Initialize the arena with the provided slice.
    ///
    /// # Errors
    /// Returns an error if the new size exceeds the memory limit.
    pub fn init_with(&mut self, slice: &[u8]) -> MemoryResult<()> {
        self.data.clear();
        self.append(slice)
    }

    /// Append data to the arena.
    ///
    /// # Errors
    /// Returns an error if the new size exceeds the memory limit.
    pub fn append(&mut self, slice: &[u8]) -> MemoryResult<()> {
        let new_len = self.data.len() + slice.len();
        let capacity = self.data.capacity();

        // if the new_length is higher than current capacity then
        // we need to grow with the difference.
        if new_len > capacity {
            let diff_size = new_len - capacity;

            // NOTE: Vec::reserve_exact is approximate and does not guarantee
            // exact capacity
            self.limiter.borrow_mut().increase_usage(diff_size)?;

            // If we pre-allocate well, this will rarely run and its better than double
            // capacity strategy to better manage memory as that could cause
            // us to exhaust memory faster
            self.data.reserve_exact(slice.len());
        }

        self.data.extend_from_slice(slice);

        Ok(())
    }
}

impl Deref for Arena {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.data.as_slice()
    }
}

impl Index<usize> for Arena {
    type Output = u8;

    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index]
    }
}

impl Drop for Arena {
    fn drop(&mut self) {
        self.limiter.borrow_mut().decrease_usage(self.data.len());
    }
}

#[must_use]
pub fn calculate_size_for<T>(by_multiple: Option<usize>) -> usize {
    if let Some(by_value) = by_multiple {
        return size_of::<T>() * by_value;
    }
    size_of::<T>()
}

/// `TypeArena<T>` provides a pre-allocated memory that can grow
/// and store a specific element of a given type.
/// It grows with usage and continuously keeps the memory
/// available for the lifetime of the `T`.
#[derive(Debug, Clone)]
pub struct TypeArena<T> {
    limiter: SharedMemoryLimiter,
    data: Vec<T>,
}

impl<T> TypeArena<T> {
    pub fn new(limiter: SharedMemoryLimiter) -> Self {
        Self {
            limiter,
            data: vec![],
        }
    }

    pub fn preallocate(limiter: SharedMemoryLimiter, multiple_of: usize) -> Self {
        let preallocate = calculate_size_for::<T>(Some(multiple_of));
        limiter.borrow_mut().preallocate(preallocate);

        Self {
            limiter,
            data: Vec::with_capacity(preallocate),
        }
    }

    /// Push an element to the arena.
    ///
    /// # Errors
    /// Returns an error if adding the element exceeds the memory limit.
    pub fn push(&mut self, element: T) -> MemoryResult<()> {
        let by_amount = calculate_size_for::<T>(None);
        self.limiter.borrow_mut().increase_usage(by_amount)?;
        self.data.push(element);
        Ok(())
    }

    #[inline]
    pub fn first_mut(&mut self) -> Option<&mut T> {
        self.data.first_mut()
    }

    #[inline]
    #[must_use]
    pub fn first(&self) -> Option<&T> {
        self.data.first()
    }

    #[inline]
    pub fn last_mut(&mut self) -> Option<&mut T> {
        self.data.last_mut()
    }

    #[inline]
    #[must_use]
    pub fn last(&self) -> Option<&T> {
        self.data.last()
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Removes and returns the last item from the `Vector`
    /// decreasing the memory usage of the `TArea<T>`,
    pub fn drain_last(&mut self) -> Option<T> {
        let by_amount = calculate_size_for::<T>(None);
        self.limiter.borrow_mut().decrease_usage(by_amount);
        self.data.pop()
    }

    /// Returns a draining iterator that removes the
    /// specified range in the underlying vector
    /// yields the removed items.
    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
    where
        R: RangeBounds<usize>,
    {
        use std::ops::Bound::{Excluded, Included, Unbounded};

        let start = match range.start_bound() {
            Included(&n) => n,
            Excluded(&n) => n + 1,
            Unbounded => 0,
        };

        let end = match range.end_bound() {
            Included(&n) => n + 1,
            Excluded(&n) => n,
            Unbounded => self.len(),
        };

        self.limiter
            .borrow_mut()
            .decrease_usage(calculate_size_for::<T>(Some(end - start)));

        self.data.drain(range)
    }
}

impl<T> Deref for TypeArena<T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.data.as_slice()
    }
}

impl<T> Index<usize> for TypeArena<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index]
    }
}

impl<T> Drop for TypeArena<T> {
    fn drop(&mut self) {
        self.limiter
            .borrow_mut()
            .decrease_usage(calculate_size_for::<T>(Some(self.data.len())));
    }
}

pub type ReferencedType<T> = rc::Rc<cell::RefCell<T>>;

pub type GeneratorFunc<T> = dyn Fn(&mut ArenaPool<T>) -> T;

pub trait Resettable {
    fn reset(&mut self);
}

pub trait PoolGenerator<T: Resettable> {
    fn generate(&self, pool: &mut ArenaPool<T>) -> T;
}

pub struct FnGenerator<T: Resettable> {
    handler: Box<GeneratorFunc<T>>,
}

impl<T: Resettable> FnGenerator<T> {
    pub fn new(handler: impl Fn(&mut ArenaPool<T>) -> T + 'static) -> Self {
        Self {
            handler: Box::new(handler),
        }
    }
}

impl<T: Resettable> PoolGenerator<T> for FnGenerator<T> {
    fn generate(&self, pool: &mut ArenaPool<T>) -> T {
        (self.handler)(pool)
    }
}

/// `ArenaPool` provides a single-threaded object pool which allows us to easily
/// generate a trackable and reusable set of objects that can be freely
/// allocated based on the underlying memory limits as dictated by the
/// `SharedMemoryLimiter`.
///
/// This is not thread-safe.
#[derive(Clone)]
pub struct ArenaPool<T: Resettable> {
    arena: TypeArena<T>,
    tracker: MemoryLimiter,
    limiter: SharedMemoryLimiter,
    generator: rc::Rc<dyn PoolGenerator<T>>,
}

pub type SharedArenaPool<T> = rc::Rc<cell::RefCell<ArenaPool<T>>>;

impl<T: Resettable> ArenaPool<T> {
    pub fn create_shared(
        limiter: &SharedMemoryLimiter,
        gen: impl PoolGenerator<T> + 'static,
    ) -> SharedArenaPool<T> {
        let tracker = MemoryLimiter::non_shared(limiter.borrow().capacity());
        rc::Rc::new(cell::RefCell::new(Self {
            tracker,
            generator: rc::Rc::new(gen),
            limiter: rc::Rc::clone(limiter),
            arena: TypeArena::new(rc::Rc::clone(limiter)),
        }))
    }

    pub fn new(limiter: &SharedMemoryLimiter, gen: impl PoolGenerator<T> + 'static) -> Self {
        let tracker = MemoryLimiter::non_shared(limiter.borrow().capacity());
        Self {
            tracker,
            generator: rc::Rc::new(gen),
            limiter: rc::Rc::clone(limiter),
            arena: TypeArena::new(rc::Rc::clone(limiter)),
        }
    }

    #[inline]
    #[must_use]
    pub fn remaining_allocation(&self) -> usize {
        self.limiter.borrow().capacity() - self.tracker.current_usage()
    }

    #[inline]
    #[must_use]
    pub fn allocated(&self) -> usize {
        self.tracker.current_usage()
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.limiter.borrow().capacity()
    }

    /// Deallocate an element and return it to the pool.
    ///
    /// # Panics
    /// Panics if pushing to the arena fails (should never happen under normal conditions).
    #[inline]
    pub fn deallocate(&mut self, mut elem: T) {
        self.tracker.set_capacity(self.limiter.borrow().capacity());
        elem.reset();
        self.arena.push(elem).expect("should push in element");
        self.tracker.decrease_usage(calculate_size_for::<T>(None));
    }

    /// Allocate an element from the pool.
    ///
    /// # Panics
    /// Panics if draining the last element fails (should never happen under normal conditions).
    ///
    /// # Errors
    /// Returns an error if increasing usage exceeds the memory limit.
    #[inline]
    pub fn allocate(&mut self) -> MemoryResult<T> {
        self.tracker.set_capacity(self.limiter.borrow().capacity());

        // if we have items in the arena, meaning
        // we can reuse a previous structure then pull that up and send it
        // out as return value to the requester.
        if !self.arena.is_empty() {
            self.tracker.increase_usage(calculate_size_for::<T>(None))?;

            let elem = self.arena.drain_last().expect("should have element");
            return Ok(elem);
        }

        self.tracker.increase_usage(calculate_size_for::<T>(None))?;

        let gen = self.generator.clone();
        let elem = gen.generate(self);
        Ok(elem)
    }
}