

const require_rolldown_runtime = require('../_virtual/rolldown_runtime.js');
const require_Hasher = require('../crypto/hashes/Hasher.js');
require('../crypto/hashes/index.js');
require('./buffer.js');
const require_VarintEncoder = require('./VarintEncoder.js');
let buffer_index_js = require("buffer/index.js");
buffer_index_js = require_rolldown_runtime.__toESM(buffer_index_js);

//#region src/utils/MultiHashEncoder.ts
const multiHashNameMap = {
	"sha-1": 17,
	"sha-256": 18,
	"sha-512": 19
};
const multiHashCodeMap = Object.entries(multiHashNameMap).reduce((map, [hashName, hashCode]) => ({
	...map,
	[hashCode]: hashName
}), {});
var MultiHashEncoder = class MultiHashEncoder {
	/**
	*
	* Encodes a buffer into a hash
	*
	* @param buffer the buffer that has to be encoded
	* @param hashName the hashing algorithm, 'sha-256'
	*
	* @returns a multihash
	*/
	static encode(data, hashName) {
		const hash = require_Hasher.Hasher.hash(data, hashName);
		const hashCode = multiHashNameMap[hashName];
		const hashPrefix = require_VarintEncoder.VarintEncoder.encode(hashCode);
		const hashLengthPrefix = require_VarintEncoder.VarintEncoder.encode(hash.length);
		return buffer_index_js.Buffer.concat([
			hashPrefix,
			hashLengthPrefix,
			hash
		]);
	}
	/**
	*
	* Decodes the multihash
	*
	* @param data the multihash that has to be decoded
	*
	* @returns object with the data and the hashing algorithm
	*/
	static decode(data) {
		const [hashPrefix, hashPrefixByteLength] = require_VarintEncoder.VarintEncoder.decode(data);
		const withoutHashPrefix = data.slice(hashPrefixByteLength);
		const [, lengthPrefixByteLength] = require_VarintEncoder.VarintEncoder.decode(withoutHashPrefix);
		const withoutLengthPrefix = withoutHashPrefix.slice(lengthPrefixByteLength);
		if (!multiHashCodeMap[hashPrefix]) throw new Error(`Unsupported hash code 0x${hashPrefix.toString(16)}`);
		return {
			data: buffer_index_js.Buffer.from(withoutLengthPrefix),
			hashName: multiHashCodeMap[hashPrefix]
		};
	}
	/**
	*
	* Validates if it is a valid mulithash
	*
	* @param data the multihash that needs to be validated
	*
	* @returns a boolean whether the multihash is valid
	*/
	static isValid(data) {
		try {
			MultiHashEncoder.decode(data);
			return true;
		} catch (_e) {
			return false;
		}
	}
};

//#endregion
exports.MultiHashEncoder = MultiHashEncoder;