"use strict";
// Copyright 2017-2020 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("@polkadot/util");
const Compact_1 = __importDefault(require("../codec/Compact"));
const Raw_1 = __importDefault(require("../codec/Raw"));
/**
 * @name Bytes
 * @description
 * A Bytes wrapper for Vec<u8>. The significant difference between this and a normal Uint8Array
 * is that this version allows for length-encoding. (i.e. it is a variable-item codec, the same
 * as what is found in [[Text]] and [[Vec]])
 */
class Bytes extends Raw_1.default {
    constructor(registry, value) {
        super(registry, Bytes.decodeBytes(value));
    }
    /** @internal */
    static decodeBytes(value) {
        if (Array.isArray(value) || util_1.isString(value)) {
            return util_1.u8aToU8a(value);
        }
        else if (!(value instanceof Raw_1.default) && util_1.isU8a(value)) {
            // We are ensuring we are not a Rawv instance. In the case of a Raw we already have gotten
            // rid of the length, i.e. new Bytes(new Bytes(...)) will work as expected
            return Bytes.decodeBytesU8a(value);
        }
        return value;
    }
    /** @internal */
    static decodeBytesU8a(value) {
        if (!value.length) {
            return new Uint8Array();
        }
        // handle all other Uint8Array inputs, these do have a length prefix
        const [offset, length] = Compact_1.default.decodeU8a(value);
        const total = offset + length.toNumber();
        util_1.assert(total <= value.length, `Bytes: required length less than remainder, expected at least ${total}, found ${value.length}`);
        return value.subarray(offset, total);
    }
    /**
     * @description The length of the value when encoded as a Uint8Array
     */
    get encodedLength() {
        return this.length + Compact_1.default.encodeU8a(this.length).length;
    }
    /**
     * @description Returns the base runtime type name for this instance
     */
    toRawType() {
        return 'Bytes';
    }
    /**
     * @description Encodes the value as a Uint8Array as per the SCALE specifications
     * @param isBare true when the value has none of the type-specific prefixes (internal)
     */
    toU8a(isBare) {
        return isBare
            ? super.toU8a(isBare)
            : Compact_1.default.addLengthPrefix(this);
    }
}
exports.default = Bytes;
