Search Apps Documentation Source Content File Folder Download Copy Actions Download

utils.gno

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