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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use ic_stable_structures::{memory_manager::VirtualMemory, Memory};

use ic_cdk::api::stable::WASM_PAGE_SIZE_IN_BYTES;

use crate::{
    error::Error,
    runtime::{structure_helpers::grow_memory, types::ChunkSize},
};

use super::types::{FileChunkPtr, DEFAULT_FILE_CHUNK_SIZE_V2};

// index for the first u64 containing chunk pointers
const FIRST_PTR_IDX: u64 = 16; // lower numbers are reserved

// index containing the chunk size used
const CHUNK_SIZE_IDX: u64 = 1;
// index containing the total number of chunks used
const AVAILABLE_CHUNKS_LEN_IDX: u64 = 2;
// index containing the next address to use, when there are no reusable indices available
const MAX_PTR_IDX: u64 = 3;

pub struct ChunkPtrAllocator<M: Memory> {
    v2_available_chunks: VirtualMemory<M>,
    v2_chunk_size: usize,
}

impl<M: Memory> ChunkPtrAllocator<M> {
    pub fn new(v2_available_chunks: VirtualMemory<M>) -> Result<ChunkPtrAllocator<M>, Error> {
        // init avaiable chunks
        if v2_available_chunks.size() == 0 {
            v2_available_chunks.grow(1);

            // write the magic marker
            let b = [b'A', b'L', b'O', b'1', 0, 0, 0, 0];
            v2_available_chunks.write(0, &b);

            v2_available_chunks.write(8, &0u64.to_le_bytes());
            v2_available_chunks.write(16, &0u64.to_le_bytes());
            v2_available_chunks.write(24, &0u64.to_le_bytes());
        } else {
            // check the marker
            let mut b = [0u8; 4];
            v2_available_chunks.read(0, &mut b);

            if b != *b"ALO1" {
                return Err(Error::InvalidMagicMarker);
            }
        }

        let mut allocator = ChunkPtrAllocator {
            v2_available_chunks,
            v2_chunk_size: 0,
        };

        // init chunk size
        let mut chunk_size = allocator.read_u64(CHUNK_SIZE_IDX) as usize;

        if chunk_size == 0 {
            chunk_size = DEFAULT_FILE_CHUNK_SIZE_V2;
        }

        // initialize chunk size from the stored data or use default
        allocator.set_chunk_size(chunk_size).unwrap();

        Ok(allocator)
    }

    fn read_u64(&self, index: u64) -> u64 {
        let mut b = [0u8; 8];
        self.v2_available_chunks.read(index * 8, &mut b);

        u64::from_le_bytes(b)
    }

    fn write_u64(&self, index: u64, value: u64) {
        // we only need to start checking the size at certain index
        if index + 8 >= WASM_PAGE_SIZE_IN_BYTES / 8 {
            grow_memory(&self.v2_available_chunks, index * 8 + 8);
        }

        self.v2_available_chunks
            .write(index * 8, &value.to_le_bytes());
    }

    fn get_len(&self) -> u64 {
        self.read_u64(AVAILABLE_CHUNKS_LEN_IDX)
    }

    fn set_len(&self, new_len: u64) {
        self.write_u64(AVAILABLE_CHUNKS_LEN_IDX, new_len);
    }

    fn get_next_max_ptr(&self) -> u64 {
        let ret = self.read_u64(MAX_PTR_IDX);

        // store the next max pointer
        self.write_u64(MAX_PTR_IDX, ret + self.chunk_size() as u64);

        ret
    }

    fn get_ptr(&self, index: u64) -> u64 {
        self.read_u64(FIRST_PTR_IDX + index)
    }

    fn set_ptr(&self, index: u64, value: u64) {
        self.write_u64(FIRST_PTR_IDX + index, value);
    }

    #[cfg(test)]
    pub fn available_ptrs(&self) -> Vec<u64> {
        let mut res = Vec::new();

        for i in 0..self.get_len() {
            res.push(self.get_ptr(i));
        }

        res
    }

    fn push_ptr(&self, chunk_ptr: FileChunkPtr) {
        let len = self.get_len();

        self.set_ptr(len, chunk_ptr);

        self.set_len(len + 1);
    }

    fn pop_ptr(&self) -> Option<FileChunkPtr> {
        let mut len = self.get_len();

        if len == 0 {
            return None;
        }

        len -= 1;

        let ptr = self.get_ptr(len);

        self.set_len(len);

        Some(ptr)
    }

    pub fn set_chunk_size(&mut self, new_size: usize) -> Result<(), Error> {
        // new size must be one of the available values

        if !ChunkSize::VALUES
            .iter()
            .any(|size| *size as usize == new_size)
        {
            return Err(Error::IncompatibleChunkSize);
        }

        // we can only set chunk size, if there are no chunks stored in the database, or the chunk size is not changed
        let cur_size = self.read_u64(CHUNK_SIZE_IDX);

        if cur_size == new_size as u64 {
            self.v2_chunk_size = new_size;
            return Ok(());
        }

        if self.read_u64(MAX_PTR_IDX) == 0 {
            // overwrite the new chunk size
            self.write_u64(CHUNK_SIZE_IDX, new_size as u64);
            self.v2_chunk_size = new_size;
            return Ok(());
        }

        Err(Error::IncompatibleChunkSize)
    }

    pub fn chunk_size(&self) -> usize {
        self.v2_chunk_size
    }

    pub fn allocate(&mut self) -> FileChunkPtr {
        // try to take from the available chunks
        if let Some(ptr) = self.pop_ptr() {
            return ptr;
        }

        // if there are no available chunks, take the next max known pointer
        self.get_next_max_ptr()
    }

    #[cfg(test)]
    fn check_free(&self, ptr: FileChunkPtr) {
        if ptr % self.chunk_size() as u64 != 0 {
            panic!(
                "Pointer released {} must be a multiple of FILE_CHUNK_SIZE!",
                ptr
            );
        }

        if self.read_u64(MAX_PTR_IDX) <= ptr {
            panic!("Address {} was never allocated!", ptr);
        }

        for p in self.available_ptrs() {
            if p == ptr {
                panic!("Second free of address {}", ptr);
            }
        }
    }

    pub fn free(&mut self, ptr: FileChunkPtr) {
        #[cfg(test)]
        self.check_free(ptr);

        self.push_ptr(ptr);
    }
}

#[cfg(test)]
mod tests {
    use ic_stable_structures::{
        memory_manager::{MemoryId, MemoryManager},
        Memory,
    };

    use crate::storage::types::FileSize;

    use crate::test_utils::new_vector_memory;

    use super::*;

    #[test]
    fn chunk_allocator_allocations() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();
        let chunk_size = DEFAULT_FILE_CHUNK_SIZE_V2;

        assert_eq!(allocator.allocate(), 0);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 3);

        allocator.free(chunk_size as FileChunkPtr * 2);

        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 4);

        assert!(allocator.available_ptrs().is_empty());

        allocator.free(chunk_size as FileChunkPtr * 2);

        // imitate canister upgrade here
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        allocator.free(chunk_size as FileChunkPtr * 3);
        allocator.free(chunk_size as FileChunkPtr);

        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 3);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 5);
    }

    #[test]
    fn chunk_allocator_allocations2() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        assert_eq!(allocator.allocate(), 0);
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr
        );
        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr);

        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr
        );
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 2
        );
        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr);

        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr
        );
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 3
        );
    }

    #[test]
    fn chunk_allocator_allocations_custom_chunk_size() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();
        let chunk_size = ChunkSize::CHUNK8K as usize;
        allocator.set_chunk_size(chunk_size).unwrap();

        assert_eq!(allocator.allocate(), 0);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 3);

        allocator.free(chunk_size as FileChunkPtr * 2);

        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 4);

        assert!(allocator.available_ptrs().is_empty());

        allocator.free(chunk_size as FileChunkPtr * 2);

        // imitate canister upgrade here
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();
        assert_eq!(allocator.chunk_size(), chunk_size);

        allocator.free(chunk_size as FileChunkPtr * 3);
        allocator.free(chunk_size as FileChunkPtr);

        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 3);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 2);
        assert_eq!(allocator.allocate(), chunk_size as FileChunkPtr * 5);
    }

    #[test]
    #[should_panic]
    fn double_release_fails() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();

        assert_eq!(allocator.allocate(), 0);
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr
        );
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 2
        );
        assert_eq!(
            allocator.allocate(),
            DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 3
        );

        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 2);
        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 3);
        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr * 2);
    }

    #[test]
    #[should_panic]
    fn unallocated_release_fails() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();

        allocator.allocate();
        allocator.free(0);
        allocator.allocate();
        allocator.free(DEFAULT_FILE_CHUNK_SIZE_V2 as FileChunkPtr);
    }

    #[test]
    #[should_panic]
    fn impossible_address_fails() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();

        allocator.allocate();
        allocator.free(120);
    }

    #[test]
    fn chunk_allocator_allocations_check_memory_grow() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let allocator_memory = memory_manager.get(MemoryId::new(1));
        let mem = allocator_memory.clone();

        assert_eq!(mem.size(), 0);
        let mut allocator = ChunkPtrAllocator::new(allocator_memory).unwrap();
        assert_eq!(mem.size(), 1);

        for _ in 0..10000 {
            allocator.allocate();
        }

        for i in 0..(65536 / 8) - 16 {
            allocator.free(i * DEFAULT_FILE_CHUNK_SIZE_V2 as FileSize);
        }

        assert_eq!(mem.size(), 1);

        allocator.free(9999 * DEFAULT_FILE_CHUNK_SIZE_V2 as FileSize);

        assert_eq!(mem.size(), 2);
    }

    #[test]
    fn wrong_custom_chunk_size_fails() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();
        let chunk_size = DEFAULT_FILE_CHUNK_SIZE_V2;

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        let res = allocator.set_chunk_size(chunk_size * 2);

        assert!(res.is_err());

        assert_eq!(allocator.chunk_size(), chunk_size);
    }

    #[test]
    fn alo1_marker_is_written() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        let memory = memory_manager.get(MemoryId::new(1));
        let mut b = [0u8; 4];

        memory.read(0, &mut b);
        assert_eq!(&b[0..4], b"ALO1");
    }

    #[test]
    fn correct_alo1_marker_is_accepted() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        let res = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1)));

        assert!(res.is_ok());
    }

    #[test]
    fn wrong_alo1_marker_is_rejected() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        let memory = memory_manager.get(MemoryId::new(1));
        let b = [0u8; 1];

        memory.write(0, &b);

        let res = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1)));

        assert!(res.is_err());
    }

    #[test]
    fn same_custom_chunk_size_succeeds() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();
        let chunk_size = DEFAULT_FILE_CHUNK_SIZE_V2 * 2;
        allocator.set_chunk_size(chunk_size).unwrap();

        assert_eq!(allocator.allocate(), 0);
        allocator.free(0);

        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();
        assert_eq!(allocator.chunk_size(), chunk_size);

        allocator.set_chunk_size(chunk_size).unwrap();

        assert_eq!(allocator.chunk_size(), chunk_size);
    }

    #[test]
    fn incorrect_size_fails() {
        let mem = new_vector_memory();
        let memory_manager = MemoryManager::init(mem);
        let mut allocator = ChunkPtrAllocator::new(memory_manager.get(MemoryId::new(1))).unwrap();

        for chunk_size in ChunkSize::VALUES.iter() {
            allocator.set_chunk_size(*chunk_size as usize).unwrap();
        }

        assert!(allocator.set_chunk_size(0).is_err());
        assert!(allocator.set_chunk_size(1).is_err());
        assert!(allocator
            .set_chunk_size(DEFAULT_FILE_CHUNK_SIZE_V2 + 1)
            .is_err());
        assert!(allocator
            .set_chunk_size(DEFAULT_FILE_CHUNK_SIZE_V2 * 3)
            .is_err());
    }
}