Add assertion decorations for various numeric types.
This commit is contained in:
@@ -1,4 +1,32 @@
|
||||
function assertUInt8(target: any, key: string) {
|
||||
return assertInteger(target, key, 0, 255);
|
||||
}
|
||||
|
||||
function assertInt8(target: any, key: string) {
|
||||
return assertInteger(target, key, -128, 127);
|
||||
}
|
||||
|
||||
function assertUInt16(target: any, key: string) {
|
||||
return assertInteger(target, key, 0, 65535);
|
||||
}
|
||||
|
||||
function assertInt16(target: any, key: string) {
|
||||
return assertInteger(target, key, -32768, 32767);
|
||||
}
|
||||
|
||||
function assertUInt32(target: any, key: string) {
|
||||
return assertInteger(target, key, 0, 4294967295);
|
||||
}
|
||||
|
||||
function assertInt32(target: any, key: string) {
|
||||
return assertInteger(target, key, -2147483648, 2147483647);
|
||||
}
|
||||
|
||||
function assertCompactLength(target: any, key: string) {
|
||||
return assertUInt16(target, key)
|
||||
}
|
||||
|
||||
function assertInteger(target: any, key: string, min: number, max: number) {
|
||||
let val = this[key];
|
||||
if (delete this[key]) {
|
||||
Object.defineProperty(target, key, {
|
||||
@@ -6,8 +34,9 @@ function assertUInt8(target: any, key: string) {
|
||||
return val;
|
||||
},
|
||||
set: function (newVal) {
|
||||
if (newVal < 0 || newVal > 255) {
|
||||
throw `Invalid ${target.constructor.name}.${key}: ${newVal} is not uint8`;
|
||||
if (newVal < min || newVal > max) {
|
||||
throw `${target.constructor.name}.${key}: ` +
|
||||
`Integer ${newVal} is outside the valid [${min}, ${max}] interval`;
|
||||
}
|
||||
val = newVal;
|
||||
},
|
||||
@@ -27,7 +56,7 @@ function assertEnum<E>(enumerated: E) {
|
||||
},
|
||||
set: function (newVal) {
|
||||
if (enumerated[newVal] === undefined) {
|
||||
throw `Invalid ${target.constructor.name}.${key}: ${newVal} is not enum`;
|
||||
throw `${target.constructor.name}.${key}: ${newVal} is not enum`;
|
||||
}
|
||||
val = newVal;
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user