This commit is contained in:
parent
31c5ed614c
commit
bac5986425
61 changed files with 2745 additions and 0 deletions
22
src/sizeof/Signed.go
Normal file
22
src/sizeof/Signed.go
Normal file
|
@ -0,0 +1,22 @@
|
|||
package sizeof
|
||||
|
||||
import "math"
|
||||
|
||||
// Signed tells you how many bytes are needed to encode this signed number.
|
||||
func Signed[T int | int8 | int16 | int32 | int64](number T) int {
|
||||
x := int64(number)
|
||||
|
||||
switch {
|
||||
case x >= math.MinInt8 && x <= math.MaxInt8:
|
||||
return 1
|
||||
|
||||
case x >= math.MinInt16 && x <= math.MaxInt16:
|
||||
return 2
|
||||
|
||||
case x >= math.MinInt32 && x <= math.MaxInt32:
|
||||
return 4
|
||||
|
||||
default:
|
||||
return 8
|
||||
}
|
||||
}
|
21
src/sizeof/Signed_test.go
Normal file
21
src/sizeof/Signed_test.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package sizeof_test
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"git.urbach.dev/cli/q/src/sizeof"
|
||||
"git.urbach.dev/go/assert"
|
||||
)
|
||||
|
||||
func TestSigned(t *testing.T) {
|
||||
assert.Equal(t, sizeof.Signed(0), 1)
|
||||
assert.Equal(t, sizeof.Signed(math.MinInt8), 1)
|
||||
assert.Equal(t, sizeof.Signed(math.MaxInt8), 1)
|
||||
assert.Equal(t, sizeof.Signed(math.MinInt16), 2)
|
||||
assert.Equal(t, sizeof.Signed(math.MaxInt16), 2)
|
||||
assert.Equal(t, sizeof.Signed(math.MinInt32), 4)
|
||||
assert.Equal(t, sizeof.Signed(math.MaxInt32), 4)
|
||||
assert.Equal(t, sizeof.Signed(math.MinInt64), 8)
|
||||
assert.Equal(t, sizeof.Signed(math.MaxInt64), 8)
|
||||
}
|
22
src/sizeof/Unsigned.go
Normal file
22
src/sizeof/Unsigned.go
Normal file
|
@ -0,0 +1,22 @@
|
|||
package sizeof
|
||||
|
||||
import "math"
|
||||
|
||||
// Unsigned tells you how many bytes are needed to encode this unsigned number.
|
||||
func Unsigned[T uint | uint8 | uint16 | uint32 | uint64 | int | int8 | int16 | int32 | int64](number T) int {
|
||||
x := uint64(number)
|
||||
|
||||
switch {
|
||||
case x <= math.MaxUint8:
|
||||
return 1
|
||||
|
||||
case x <= math.MaxUint16:
|
||||
return 2
|
||||
|
||||
case x <= math.MaxUint32:
|
||||
return 4
|
||||
|
||||
default:
|
||||
return 8
|
||||
}
|
||||
}
|
19
src/sizeof/Unsigned_test.go
Normal file
19
src/sizeof/Unsigned_test.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package sizeof_test
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"git.urbach.dev/cli/q/src/sizeof"
|
||||
"git.urbach.dev/go/assert"
|
||||
)
|
||||
|
||||
func TestUnsigned(t *testing.T) {
|
||||
assert.Equal(t, sizeof.Unsigned(0), 1)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint8), 1)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint8+1), 2)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint16), 2)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint16+1), 4)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint32), 4)
|
||||
assert.Equal(t, sizeof.Unsigned(math.MaxUint32+1), 8)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue