1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-12-13 11:40:29 +00:00

Merge pull request #1446 from Erb3/erb3-path-3

Add `colors.fromBlit`.
This commit is contained in:
Jonathan Coates 2023-05-17 22:47:28 +01:00 committed by GitHub
commit b91bca8830
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 7 deletions

View File

@ -351,15 +351,46 @@ for i = 0, 15 do
color_hex_lookup[2 ^ i] = string.format("%x", i)
end
--- Converts the given color to a paint/blit hex character (0-9a-f).
--
-- This is equivalent to converting floor(log_2(color)) to hexadecimal.
--
-- @tparam number color The color to convert.
-- @treturn string The blit hex code of the color.
-- @since 1.94.0
--[[- Converts the given color to a paint/blit hex character (0-9a-f).
This is equivalent to converting floor(log_2(color)) to hexadecimal.
@tparam number color The color to convert.
@treturn string The blit hex code of the color.
@usage
```lua
colors.toBlit(colors.red)
-- => "c"
```
@see colors.fromBlit
@since 1.94.0
]]
function toBlit(color)
expect(1, color, "number")
return color_hex_lookup[color] or
string.format("%x", math.floor(math.log(color) / math.log(2)))
end
--[[- Converts the given paint/blit hex character (0-9a-f) to a color.
This is equivalent to converting the hex character to a number and then 2 ^ decimal
@tparam string hex The paint/blit hex character to convert
@treturn number The color
@usage
```lua
colors.fromBlit("e")
-- => 16384
```
@see colors.toBlit
@since 1.105.0
]]
function fromBlit(hex)
expect(1, hex, "string")
if #hex ~= 1 then return nil end
local value = tonumber(hex, 16)
if not value then return nil end
return 2 ^ value
end

View File

@ -93,4 +93,18 @@ describe("The colors library", function()
expect(colors.toBlit(16385)):eq("e")
end)
end)
describe("colors.fromBlit", function()
it("validates arguments", function()
expect.error(colors.fromBlit, nil):eq("bad argument #1 (string expected, got nil)")
expect(colors.fromBlit("")):eq(nil)
expect(colors.fromBlit("not hex")):eq(nil)
end)
it("converts all colors", function()
for i = 0, 15 do
expect(colors.fromBlit(colors.toBlit(2 ^ i))):eq(2 ^ i)
end
end)
end)
end)