Validate To Binary byte length

This commit is contained in:
Deepak kudi 2026-06-04 13:07:29 +05:30
parent 72ca1aeec7
commit 59551fcbc1
4 changed files with 42 additions and 2 deletions

View File

@ -9,6 +9,7 @@
import Utils from "../Utils.mjs";
import OperationError from "../errors/OperationError.mjs";
export const MAX_BINARY_PADDING = 65536;
/**
* Convert a byte array into a binary string.
@ -32,6 +33,10 @@ export function toBinary(data, delim="Space", padding=8) {
if (data === undefined || data === null)
throw new OperationError("Unable to convert to binary: Empty input data enocuntered");
padding = Number(padding);
if (!Number.isFinite(padding) || padding < 0 || Math.round(padding) !== padding || padding > MAX_BINARY_PADDING)
throw new OperationError(`Byte length must be an integer between 0 and ${MAX_BINARY_PADDING}`);
delim = Utils.charRep(delim);
let output = "";
@ -77,4 +82,3 @@ export function fromBinary(data, delim="Space", byteLen=8) {
}
return output;
}

View File

@ -7,7 +7,7 @@
import Operation from "../Operation.mjs";
import Utils from "../Utils.mjs";
import {BIN_DELIM_OPTIONS} from "../lib/Delim.mjs";
import {toBinary} from "../lib/Binary.mjs";
import {MAX_BINARY_PADDING, toBinary} from "../lib/Binary.mjs";
/**
* To Binary operation
@ -35,6 +35,8 @@ class ToBinary extends Operation {
{
"name": "Byte Length",
"type": "number",
"min": 1,
"max": MAX_BINARY_PADDING,
"value": 8
}
];

View File

@ -178,6 +178,7 @@ import "./tests/TakeNthBytes.mjs";
import "./tests/Template.mjs";
import "./tests/TextEncodingBruteForce.mjs";
import "./tests/TextIntegerConverter.mjs";
import "./tests/ToBinary.mjs";
import "./tests/ToFromInsensitiveRegex.mjs";
import "./tests/TranslateDateTimeFormat.mjs";
import "./tests/Typex.mjs";

View File

@ -0,0 +1,33 @@
/**
* To Binary tests
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2026
* @license Apache-2.0
*/
import TestRegister from "../../lib/TestRegister.mjs";
TestRegister.addTests([
{
name: "To Binary: custom byte length",
input: "hello",
expectedOutput: "01101000 01100101 01101100 01101100 01101111",
recipeConfig: [
{
"op": "To Binary",
"args": ["Space", 8]
}
]
},
{
name: "To Binary: byte length too large",
input: "hello",
expectedOutput: "Byte length must be an integer between 0 and 65536",
recipeConfig: [
{
"op": "To Binary",
"args": ["Space", "8111111111111111111"]
}
]
}
]);