test-triam-base-contract
Version:
Low level triam smart cotnract support library
88 lines (74 loc) • 1.94 kB
JavaScript
export class Storage {
constructor (_storage) {
if (_storage) {
this.storage = Object.assign ({}, _storage);
} else {
this.storage = {};
}
}
set (_name, _data) {
if (this.storage.hasOwnProperty (_name)) {
throw new Error ('storage has property' + _name);
}
this.storage[_name] = _data;
}
get (_name) {
return this.storage[_name];
}
remove (_name) {
delete this.storage[_name];
}
update (_name, _data) {
if (!this.storage.hasOwnProperty (_name)) {
throw new Error ('storage can not find property' + _name);
}
this.storage[_name] = _data;
}
save () {
let stringData = JSON.stringify (this.storage);
let ab = str2ab (stringData);
let buf = toBuffer (ab);
return buf.toString ('hex');
}
recover (_data) {
let _buf = Buffer.from (_data, 'hex');
let _ab = toArrayBuffer (_buf);
let _state = ab2str (_ab);
let loadState = JSON.parse (_state);
this.storage = Object.assign ({}, this.storage, loadState);
return this.storage;
}
has (_name) {
return this.storage.hasOwnProperty (_name);
}
show () {
return this.storage
}
}
const ab2str = function (buf) {
return String.fromCharCode.apply (null, new Uint16Array (buf));
};
const str2ab = function (str) {
let buf = new ArrayBuffer (str.length * 2); // 2 bytes for each char
let bufView = new Uint16Array (buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt (i);
}
return buf;
};
const toArrayBuffer = function (buf) {
let ab = new ArrayBuffer (buf.length);
let view = new Uint8Array (ab);
for (let i = 0; i < buf.length; ++i) {
view[i] = buf[i];
}
return ab;
};
const toBuffer = function (ab) {
let buf = new Buffer (ab.byteLength);
let view = new Uint8Array (ab);
for (let i = 0; i < buf.length; ++i) {
buf[i] = view[i];
}
return buf;
};