Add assertion decorations for various numeric types.

This commit is contained in:
László Monda
2016-04-08 22:26:00 +02:00
parent 49d0ad270b
commit f6eb819cfe
9 changed files with 48 additions and 87 deletions

View File

@@ -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;
},