function Mem(mem) {
this.mem = mem;
this.memL = mem.length;
this.allocated = [];
this.reg = {};
this.memerr = "Pointer is not to allocated memory";
}
Create log message.
Mem.prototype.message = function() {
'use strict';
let a = `Allocated memory: ${this.allocated}`,
l = `Length: ${this.allocated.length}`,
r = `Block registry (pointer:length): ` +
`${JSON.stringify(this.reg)}`,
v = `Stored values: ${this.mem}`;
console.log(`${a} (${l})\n${r}\n${v}\n-----`);
};
Return first free index position in memory.
Mem.prototype.next = function() {
'use strict'; let i = 0;
while (i <= this.memL) {
if (this.allocated.indexOf(i) === -1) return i;
i++;
}
};
Create a new block.
Mem.prototype.make = function(ind, lim) {
'use strict'; let block = [];
while (ind < lim && ind <= this.memL) {
if (this.allocated.indexOf(ind) === -1) block.push(ind);
ind++;
}
return block;
};
Add a block to allocated memory.
Mem.prototype.add = function(ind, block) {
'use strict'; let i, len = block.length;
for (i = 0, ind; i < len; i++, ind++) {
this.allocated.splice(ind, 0, block[i]);
}
};
Allocate a block of memory of size `size` and return `pointer` containing index of first location in allocated block.
Mem.prototype.alloc = function(size) {
'use strict';
let ind, lim, block, pointer, message,
allocL = this.allocated.length;
if (size > (this.memL - allocL)) {
throw `Out of memory (max ${this.memL})`;
};
// Create and add block.
ind = this.next();
lim = ind + size;
block = this.make(ind, lim);
pointer = block[0];
this.add(pointer, block);
// Create registry entry, log message, and return pointer.
this.reg[pointer] = size;
this.message();
return block[0];
};
Release an allocated block of memory at pointer `p`.