/********************************************************************
 * @author:      Kaven
 * @email:       kaven@wuwenkai.com
 * @website:     http://kavenblog.com
 * @file:        [Kaven-Basic] /src/libs/BitString.ts
 * @create:      2018-08-30 16:07:15.084
 * @modify:      2019-04-12 11:15:18.187
 * @version:     1.1.20
 * @times:       61
 * @lines:       422
 * @copyright:   Copyright © 2018 Kaven. All Rights Reserved.
 * @description: [description]
 * @license:
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ********************************************************************/
import { BitStringType } from "./Enums";
import { Strings } from "./Strings";
/**
 * @version 1.0.0
 * @since 1.0.5
 */
export class BitString {
    get Length() {
        return this.binStr.length;
    }
    get HEX() {
        return this.toString();
    }
    static FromBytes(...bytes) {
        let bin = Strings.Empty;
        for (const byte of bytes) {
            bin += byte.toString(2).padStart(8, "0");
        }
        return new BitString(bin);
    }
    static Initialize2d(x, y) {
        return new Array(x).fill(new BitString()).map(() => new Array(y).fill(new BitString()));
    }
    constructor(initialValue, type = BitStringType.BIN) {
        if (!initialValue) {
            this.binStr = Strings.Empty;
            return;
        }
        if (typeof initialValue === "number") {
            if (initialValue > Number.MAX_SAFE_INTEGER) {
                throw new Error(`Initial value is too big: ${initialValue} > ${Number.MAX_SAFE_INTEGER}`);
            }
            initialValue = initialValue.toString(2);
        }
        let radix;
        if (typeof type === "number") {
            radix = type;
        }
        else {
            switch (type) {
                case BitStringType.BIN:
                    radix = 2;
                    break;
                case BitStringType.HEX:
                    radix = 16;
                    break;
                default:
                    throw new Error(`Invalid BitStringType: ${type}`);
            }
        }
        if (radix === 2) {
            this.binStr = initialValue;
        }
        else if (radix === 16) {
            let temp = Strings.Empty;
            for (const val of initialValue) {
                temp += parseInt(val, radix).toString(2).padStart(4, "0");
            }
            this.binStr = temp;
        }
        else {
            // to be Refined
            this.binStr = parseInt(initialValue, radix).toString(2);
        }
    }
    /**
     * Set some bit
     * @param offset right to left, start from 1
     * @param val true or false
     */
    SetBit(offset, val) {
        if (offset < 1) {
            throw new Error(`Unexpected offset: ${offset}`);
        }
        const value = val ? "1" : "0";
        const index = this.Length - offset;
        if (index >= 0) {
            this.binStr = this.binStr.ReplaceAt(index, value);
        }
        else {
            this.binStr = value + this.binStr.padStart(offset - 1, "0");
        }
        return this;
    }
    /**
     *
     * @param offset
     * @param defaultVal
     * @since 1.1.20
     * @version 2019-04-01
     */
    GetBit(offset, defaultVal = false) {
        if (offset < 1) {
            throw new Error(`Unexpected offset: ${offset}`);
        }
        const index = this.Length - offset;
        if (index < 0) {
            return defaultVal;
        }
        return this.binStr[index] === "1";
    }
    AnyBit() {
        return this.binStr.includes("1");
    }
    toString(type = BitStringType.HEX, trim = false) {
        if (this.binStr.length === 0) {
            return Strings.Empty;
        }
        switch (type) {
            case BitStringType.BIN:
                return this.binStr;
            case BitStringType.HEX:
                const array = this.binStr.SplitByN(4);
                let hex = array.map(p => parseInt(p, 2).toString(16)).join(Strings.Empty);
                if (trim) {
                    hex = hex.TrimStart("0", hex.length);
                }
                if (hex === Strings.Empty) {
                    return "0";
                }
                return hex;
            default:
                throw new Error(`Invalid BitStringType: ${type}`);
        }
    }
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    Add(val) {
        let result = Strings.Empty;
        let carry = false;
        let i = 1;
        let j = 1;
        while (i <= this.Length || j <= val.Length || carry) {
            const a = this.GetBit(i);
            const b = val.GetBit(j);
            if (carry) {
                if (a === b) {
                    result = "1" + result;
                    carry = a;
                }
                else {
                    result = "0" + result;
                    carry = true;
                }
            }
            else {
                if (a === b) {
                    result = "0" + result;
                    carry = a;
                }
                else {
                    result = "1" + result;
                    carry = false;
                }
            }
            // Move to next digits
            i++;
            j++;
        }
        return new BitString(result);
    }
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    AND(val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        if (this.Length > val.Length) {
            val.SetLength(this.Length);
        }
        else if (this.Length < val.Length) {
            this.SetLength(val.Length);
        }
        let result = Strings.Empty;
        for (let i = 0; i < this.Length; i++) {
            result += ((this.binStr[i] === "1" && val.binStr[i]) === "1" ? "1" : "0");
        }
        return new BitString(result);
    }
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    OR(val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        let result = Strings.Empty;
        let i = 1;
        while (i <= this.Length || i <= val.Length) {
            const a = this.GetBit(i);
            const b = val.GetBit(i);
            if (a || b) {
                result = "1" + result;
            }
            else {
                result = "0" + result;
            }
            i++;
        }
        return new BitString(result);
    }
    /**
     *
     * @since 1.1.20
     * @version 2019-04-01
     */
    NOT() {
        let result = Strings.Empty;
        for (const c of this.binStr) {
            result += c === "0" ? "1" : "0";
        }
        return new BitString(result);
    }
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    XOR(val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        if (this.Length > val.Length) {
            val.SetLength(this.Length);
        }
        else if (this.Length < val.Length) {
            this.SetLength(val.Length);
        }
        let result = Strings.Empty;
        for (let i = 0; i < this.Length; i++) {
            result += this.binStr[i] !== val.binStr[i] ? "1" : "0";
        }
        return new BitString(result);
    }
    LeftShift(n) {
        const right = "0".repeat(n);
        return new BitString(this.binStr + right);
    }
    RightShift(n) {
        const left = "0".repeat(n);
        if (this.Length < n) {
            return new BitString(left);
        }
        else {
            return new BitString(left + this.binStr.substring(0, this.Length - n));
        }
    }
    LeftRotate(n, bits = 64) {
        this.SetLength(bits);
        // return this.LeftShift(n).OR(this.RightShift(bits - n)).SetLength(bits);
        return new BitString(this.binStr.substring(n) + this.binStr.substring(0, n));
    }
    RightRotate(n, bits = 64) {
        this.SetLength(bits);
        // return this.RightShift(n).OR(this.LeftShift(bits - n)).SetLength(bits);
        return this.LeftRotate(bits - n);
    }
    ToNumber() {
        return parseInt(this.binStr, 2);
    }
    ToBytes(bits) {
        if (bits) {
            this.SetLength(bits);
        }
        const byteArray = [];
        const hexArray = this.HEX.SplitByN(2);
        for (const hex of hexArray) {
            byteArray.push(parseInt(hex, 16));
        }
        return byteArray;
    }
    Reflect(bits) {
        if (bits) {
            this.SetLength(bits);
        }
        return new BitString(this.binStr.Reverse());
    }
    SetLength(bits) {
        if (this.Length > bits) {
            this.binStr = this.binStr.substring(this.Length - bits);
        }
        else if (this.AND.length < bits) {
            this.binStr = this.binStr.padStart(bits, "0");
        }
        return this;
    }
    Clone() {
        return new BitString(this.binStr);
    }
    Swap(bytes = 8) {
        this.SetLength(bytes * 8);
        const result = this.binStr.SplitByN(8).reverse().join(Strings.Empty);
        return new BitString(result);
    }
}
//# sourceMappingURL=BitString.js.map