Search Apps Documentation Source Content File Folder Download Copy Actions Download

utils.gno

1.02 Kb · 49 lines
 1package emission
 2
 3import (
 4	"math"
 5	"strconv"
 6
 7	ufmt "gno.land/p/nt/ufmt/v0"
 8)
 9
10// formatInt converts various signed integer types to string representation.
11// Panics if the type is not supported.
12func formatInt(v any) string {
13	switch v := v.(type) {
14	case int32:
15		return strconv.FormatInt(int64(v), 10)
16	case int64:
17		return strconv.FormatInt(v, 10)
18	case int:
19		return strconv.Itoa(v)
20	default:
21		panic(ufmt.Sprintf("invalid type: %T", v))
22	}
23}
24
25// safeAddInt64 performs safe addition of int64 values, panicking on overflow or underflow
26func safeAddInt64(a, b int64) int64 {
27	if a > 0 && b > math.MaxInt64-a {
28		panic("int64 addition overflow")
29	}
30
31	if a < 0 && b < math.MinInt64-a {
32		panic("int64 addition underflow")
33	}
34
35	return a + b
36}
37
38// safeSubInt64 performs safe subtraction of int64 values, panicking on overflow or underflow
39func safeSubInt64(a, b int64) int64 {
40	if b > 0 && a < math.MinInt64+b {
41		panic("int64 subtraction underflow")
42	}
43
44	if b < 0 && a > math.MaxInt64+b {
45		panic("int64 subtraction overflow")
46	}
47
48	return a - b
49}