diff --git a/pkg/string/pascalString.lua b/pkg/string/pascalString.lua new file mode 100644 index 0000000..4dc760b --- /dev/null +++ b/pkg/string/pascalString.lua @@ -0,0 +1,21 @@ +local pack = require("pkg.string.pack") + +---Converts `str` into pascal string +---@param str string +---@param align? number pad result string with 0 to make result length to be multiple of `align` +---@param max_length? number max length of result string +---@return string +local toPascalString = function(str, align, max_length) + if type(max_length) == "number" then + str = str:sub(1, max_length - 1) + end + if type(align) ~= "number" then + align = 1 + end + + local tail_0_num = align - 1 - #str % align + + return pack.u8(#str) .. str .. ("\x00"):rep(tail_0_num) +end + +return toPascalString diff --git a/pkg/string/pascalString_test.lua b/pkg/string/pascalString_test.lua new file mode 100644 index 0000000..430c47a --- /dev/null +++ b/pkg/string/pascalString_test.lua @@ -0,0 +1,56 @@ +local test = require("lib.test").test +local describe = require("lib.test").describe +local expect = require("lib.test").expect +local toPascalString = require("pkg.string.pascalString") + +describe("pascalString", function() + describe("no align", function() + test("empty", function() + expect(toPascalString("")):toBe("\x00") + end) + + test("non-empty", function() + expect(toPascalString("abc")):toBe("\x03abc") + end) + end) + + describe("2-align", function() + test("empty", function() + expect(toPascalString("", 2)):toBe("\x00\x00") + end) + + test("odd length", function() + expect(toPascalString("abc", 2)):toBe("\x03abc") + end) + + test("even length", function() + expect(toPascalString("abcd", 2)):toBe("\x04abcd\x00") + end) + end) + + describe("4-align", function() + test("empty", function() + expect(toPascalString("", 4)):toBe("\x00\x00\x00\x00") + end) + + test("length mod 4 = 1", function() + expect(toPascalString("a", 4)):toBe("\x01a\x00\x00") + end) + + test("length mod 4 = 2", function() + expect(toPascalString("ab", 4)):toBe("\x02ab\x00") + end) + + test("length mod 4 = 3", function() + expect(toPascalString("abc", 4)):toBe("\x03abc") + end) + + test("length mod 4 = 0", function() + expect(toPascalString("abcd", 4)):toBe("\x04abcd\x00\x00\x00") + end) + end) + + test("over max length", function() + expect(toPascalString("abcdefg", 4, 4)):toBe("\x03abc") + end) +end) diff --git a/pkg/test.lua b/pkg/test.lua index 04afb39..d839b86 100644 --- a/pkg/test.lua +++ b/pkg/test.lua @@ -5,5 +5,6 @@ describe("pkg", function() require("pkg.string.split_test") require("pkg.string.packBits_test") require("pkg.string.pack_test") + require("pkg.string.pascalString_test") end) end)