Skip to content

Commit

Permalink
feat: add bin, oct, hex support
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Apr 16, 2021
1 parent 5b0a5f3 commit 43122d2
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 0 deletions.
53 changes: 53 additions & 0 deletions int_fmt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package sun

import (
"fmt"

"go.starlark.net/starlark"
)

func formatInt(
thread *starlark.Thread,
b *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
f string,
) (starlark.Value, error) {
var i starlark.Int
if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &i); err != nil {
return nil, err
}

if v, ok := i.Int64(); ok {
return starlark.String(fmt.Sprintf(f, v)), nil
}

return starlark.String(fmt.Sprintf(f, i.BigInt())), nil
}

func bin(
thread *starlark.Thread,
b *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
return formatInt(thread, b, args, kwargs, "%#b")
}

func oct(
thread *starlark.Thread,
b *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
return formatInt(thread, b, args, kwargs, "%O")
}

func hex(
thread *starlark.Thread,
b *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
return formatInt(thread, b, args, kwargs, "%#x")
}
7 changes: 7 additions & 0 deletions int_fmt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package sun

import "testing"

func TestFmt(t *testing.T) {
runTestData(t, "fmt.star")
}
3 changes: 3 additions & 0 deletions module.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@ var Module = &starlarkstruct.Module{
"next": starlark.NewBuiltin("next", next),
"filter": starlark.NewBuiltin("filter", filter),
"callable": starlark.NewBuiltin("callable", callable),
"hex": starlark.NewBuiltin("hex", hex),
"oct": starlark.NewBuiltin("oct", oct),
"bin": starlark.NewBuiltin("bin", bin),
},
}
29 changes: 29 additions & 0 deletions testdata/fmt.star
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
load("assert.star", "assert")

def test_main():
assert.fails(lambda: hex([]), "want int")
assert.fails(lambda: oct([]), "want int")
assert.fails(lambda: bin([]), "want int")

tests = [(-3, '-0x3'), (-2, '-0x2'), (-1, '-0x1'), (0, '0x0'), (1, '0x1'), (2, '0x2')]
for test in tests:
assert.eq(
hex(test[0]),
test[1],
)

tests = [(-3, '-0o3'), (-2, '-0o2'), (-1, '-0o1'), (0, '0o0'), (1, '0o1'), (2, '0o2')]
for test in tests:
assert.eq(
oct(test[0]),
test[1],
)

tests = [(-3, '-0b11'), (-2, '-0b10'), (-1, '-0b1'), (0, '0b0'), (1, '0b1'), (2, '0b10')]
for test in tests:
assert.eq(
bin(test[0]),
test[1],
)

test_main()

0 comments on commit 43122d2

Please sign in to comment.