Skip to content

Commit

Permalink
feat: add pkg.string.pascalString
Browse files Browse the repository at this point in the history
  • Loading branch information
Tsukina-7mochi committed Nov 24, 2024
1 parent 7abe138 commit abf0934
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
21 changes: 21 additions & 0 deletions pkg/string/pascalString.lua
Original file line number Diff line number Diff line change
@@ -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
56 changes: 56 additions & 0 deletions pkg/string/pascalString_test.lua
Original file line number Diff line number Diff line change
@@ -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)
1 change: 1 addition & 0 deletions pkg/test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit abf0934

Please sign in to comment.