Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/humanize/v1" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "5000000ugnot"
humanize.gno
// Package humanize formats numbers for people rather than machines, as a pure,
// reusable package: byte sizes, thousands separators, ordinals, pluralisation
// and block-height "durations".
//
// Everything is integer-only. There are no floats here on purpose: gno has no
// float determinism guarantees worth relying on for consensus output, and a
// rendered value that differs between nodes would be a consensus bug. One
// decimal place is produced by scaling by 10 and taking a remainder.
//
// Durations are expressed in BLOCKS, not seconds. There is no wall clock on
// chain, so "about 2 hours" is a lie dressed as precision; this package says
// "~1200 blocks" and lets the caller decide what that means on their chain.
//
// A live demo of this package is at
// [r/moul/x/daily/humanizedemo](/r/nym-moultest123/x/daily/humanizedemo/v0).
package humanize
import (
"strconv"
"strings"
)
// Bytes renders n bytes with SI-ish binary units and one decimal place.
// Negative input is rendered with a leading minus rather than rejected.
func Bytes(n int64) string {
neg := n < 0
if neg {
n = -n
}
const unit = 1024
if n < unit {
s := strconv.FormatInt(n, 10) + " B"
if neg {
return "-" + s
}
return s
}
units := []string{"KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
div := int64(unit)
i := 0
for n/div >= unit && i < len(units)-1 {
div *= unit
i++
}
// one decimal place without floats: scale by 10, then split
scaled := n * 10 / div
whole, freq := scaled/10, scaled%10
s := strconv.FormatInt(whole, 10)
if freq != 0 {
s += "." + strconv.FormatInt(freq, 10)
}
s += " " + units[i]
if neg {
return "-" + s
}
return s
}
// Comma inserts thousands separators: 1234567 -> "1,234,567".
func Comma(n int64) string {
// The magnitude goes through uint64 rather than -n: -n on math.MinInt64 is
// math.MinInt64 again, so FormatInt emits its own sign and the neg branch
// below prepended a second one. v0 returned "--9,223,372,036,854,775,808".
neg := n < 0
var m uint64
if neg {
m = uint64(-(n+1)) + 1
} else {
m = uint64(n)
}
s := strconv.FormatUint(m, 10)
var b strings.Builder
for i, c := range []byte(s) {
if i > 0 && (len(s)-i)%3 == 0 {
b.WriteByte(',')
}
b.WriteByte(c)
}
if neg {
return "-" + b.String()
}
return b.String()
}
// Ordinal renders 1 -> "1st", 2 -> "2nd", 11 -> "11th".
//
// The teens are the trap: 11/12/13 take "th" despite ending in 1/2/3, so the
// 11–13 case must be checked before the last digit.
func Ordinal(n int64) string {
s := strconv.FormatInt(n, 10)
a := n
if a < 0 {
a = -a
}
if a%100 >= 11 && a%100 <= 13 {
return s + "th"
}
switch a % 10 {
case 1:
return s + "st"
case 2:
return s + "nd"
case 3:
return s + "rd"
}
return s + "th"
}
// Plural returns "1 block" / "2 blocks", using plural when given, else word+"s".
func Plural(n int64, word, plural string) string {
if n == 1 || n == -1 {
return strconv.FormatInt(n, 10) + " " + word
}
if plural == "" {
plural = word + "s"
}
return strconv.FormatInt(n, 10) + " " + plural
}
// Blocks renders a block count at a coarse magnitude — deliberately vague,
// because a block count is not a wall-clock duration.
func Blocks(n int64) string {
switch {
case n < 0:
return "in the past"
case n == 0:
return "now"
case n < 10:
return Plural(n, "block", "")
case n < 1000:
return "~" + Comma(n/10*10) + " blocks"
default:
return "~" + Comma(n/100*100) + " blocks"
}
}
// Truncate shortens s to at most max runes, appending "…" when it cut.
// Counts RUNES, not bytes, so a multi-byte string is not sliced mid-character.
func Truncate(s string, max int) string {
if max <= 0 {
return ""
}
r := []rune(s)
if len(r) <= max {
return s
}
if max == 1 {
return "…"
}
return string(r[:max-1]) + "…"
}
humanize_test.gno
package humanize
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestBytes(t *testing.T) {
cases := []struct {
in int64
want string
}{
{0, "0 B"},
{999, "999 B"},
{1023, "1023 B"},
{1024, "1 KiB"},
{1536, "1.5 KiB"},
{1048576, "1 MiB"},
{1572864, "1.5 MiB"},
{1073741824, "1 GiB"},
{-1536, "-1.5 KiB"},
{-10, "-10 B"},
}
for _, c := range cases {
uassert.Equal(t, c.want, Bytes(c.in))
}
}
func TestComma(t *testing.T) {
cases := []struct {
in int64
want string
}{
{0, "0"}, {1, "1"}, {999, "999"}, {1000, "1,000"},
{1234567, "1,234,567"}, {-1234567, "-1,234,567"},
}
for _, c := range cases {
uassert.Equal(t, c.want, Comma(c.in))
}
}
// The teens are the trap: 11/12/13 take "th" despite ending in 1/2/3.
func TestOrdinalTeens(t *testing.T) {
cases := []struct {
in int64
want string
}{
{1, "1st"}, {2, "2nd"}, {3, "3rd"}, {4, "4th"},
{11, "11th"}, {12, "12th"}, {13, "13th"},
{21, "21st"}, {22, "22nd"}, {23, "23rd"},
{111, "111th"}, {112, "112th"}, {113, "113th"},
{101, "101st"}, {0, "0th"},
}
for _, c := range cases {
uassert.Equal(t, c.want, Ordinal(c.in))
}
}
func TestPlural(t *testing.T) {
uassert.Equal(t, "1 block", Plural(1, "block", ""))
uassert.Equal(t, "2 blocks", Plural(2, "block", ""))
uassert.Equal(t, "0 blocks", Plural(0, "block", ""))
uassert.Equal(t, "2 mice", Plural(2, "mouse", "mice"))
uassert.Equal(t, "-1 block", Plural(-1, "block", ""))
}
func TestBlocks(t *testing.T) {
uassert.Equal(t, "now", Blocks(0))
uassert.Equal(t, "1 block", Blocks(1))
uassert.Equal(t, "9 blocks", Blocks(9))
uassert.Equal(t, "~10 blocks", Blocks(15))
uassert.Equal(t, "~1,200 blocks", Blocks(1234))
uassert.Equal(t, "in the past", Blocks(-5))
}
// Truncate counts runes, so multi-byte text is never cut mid-character.
func TestTruncateCountsRunes(t *testing.T) {
uassert.Equal(t, "hello", Truncate("hello", 10))
uassert.Equal(t, "hell…", Truncate("hello!", 5))
uassert.Equal(t, "…", Truncate("hello", 1))
uassert.Equal(t, "", Truncate("hello", 0))
uassert.Equal(t, "éé", Truncate("éé", 2))
uassert.Equal(t, "é…", Truncate("ééé", 2)) // not sliced mid-rune
}
// TestCommaSurvivesTheInt64Minimum pins the defect v0 shipped. -n on
// math.MinInt64 is math.MinInt64, so FormatInt emitted its own sign and the
// neg branch prepended a second: v0 returned
// "--9,223,372,036,854,775,808". Break the mag split and this goes red.
func TestCommaSurvivesTheInt64Minimum(t *testing.T) {
const minInt64 = -9223372036854775808
uassert.Equal(t, "-9,223,372,036,854,775,808", Comma(minInt64))
uassert.Equal(t, "9,223,372,036,854,775,807", Comma(9223372036854775807))
}
// TestCommaNeverDoublesTheSign is the invariant behind it, stated so a future
// rewrite cannot reintroduce the shape without failing.
func TestCommaNeverDoublesTheSign(t *testing.T) {
const minInt64 = -9223372036854775808
for _, n := range []int64{0, 1, -1, 999, -1000, 1234567, -1234567, minInt64} {
s := Comma(n)
if strings.HasPrefix(s, "--") || strings.Contains(s, "-,") {
t.Errorf("Comma(%d) = %q", n, s)
}
if (n < 0) != strings.HasPrefix(s, "-") {
t.Errorf("Comma(%d) = %q, sign disagrees with the input", n, s)
}
}
}