All files / sportident/src/storage SiBool.ts

100% Statements 23/23
100% Branches 8/8
100% Functions 6/6
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  27x 27x   27x   55x 55x   55x       46x       2x       3x       3x 1x       2x       60x 60x 10x   50x       40x 40x 40x 40x 10x   30x 30x      
import _ from 'lodash';
import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces';
import {ModifyUndefinedException, SiDataType} from './SiDataType';
 
export class SiBool extends SiDataType<boolean> implements ISiDataType<boolean> {
    constructor(
                private byteOffset: number,
                private bitOffset: number = 0,
    ) {
        super();
    }
 
    typeSpecificIsValueValid(_value: boolean): boolean {
        return true;
    }
 
    typeSpecificValueToString(value: boolean): string {
        return value ? 'true' : 'false';
    }
 
    typeSpecificValueFromString(string: string): boolean|ValueFromStringError {
        const valueByString: {[key: string]: boolean} = {
            'true': true,
            'false': false,
        };
        if (valueByString[string] === undefined) {
            return new ValueFromStringError(
                `Value for ${this.constructor.name} must be "true" or "false", not "${string}"`,
            );
        }
        return valueByString[string];
    }
 
    typeSpecificExtractFromData(data: ISiStorageData): boolean|undefined {
        const existingByte = data.get(this.byteOffset);
        if (existingByte === undefined) {
            return undefined;
        }
        return ((existingByte >> this.bitOffset) & 0x01) === 0x01;
    }
 
    typeSpecificUpdateData(data: ISiStorageData, newValue: boolean): ISiStorageData {
        const boolAsInt = newValue ? 0x01 : 0x00;
        const preservationMask = (0x01 << this.bitOffset) ^ 0xFF;
        const existingByte = data.get(this.byteOffset);
        if (existingByte === undefined) {
            throw new ModifyUndefinedException();
        }
        const newByte = (existingByte & preservationMask) | (boolAsInt << this.bitOffset);
        return data.set(this.byteOffset, newByte);
    }
}