format.gno
1.81 Kb · 73 lines
1package utils
2
3import (
4 "strconv"
5
6 ufmt "gno.land/p/nt/ufmt/v0"
7)
8
9// FormatInt converts any signed integer type to its base-10 string
10// representation. It accepts int8, int16, int32, int64 and int, and panics on
11// any other type.
12func FormatInt(v any) string {
13 switch v := v.(type) {
14 case int8:
15 return strconv.FormatInt(int64(v), 10)
16 case int16:
17 return strconv.FormatInt(int64(v), 10)
18 case int32:
19 return strconv.FormatInt(int64(v), 10)
20 case int64:
21 return strconv.FormatInt(v, 10)
22 case int:
23 return strconv.Itoa(v)
24 default:
25 panic(ufmt.Sprintf("invalid type for FormatInt: %T", v))
26 }
27}
28
29// FormatUint converts any unsigned integer type to its base-10 string
30// representation. It accepts uint8, uint16, uint32, uint64 and uint, and panics
31// on any other type.
32func FormatUint(v any) string {
33 switch v := v.(type) {
34 case uint8:
35 return strconv.FormatUint(uint64(v), 10)
36 case uint16:
37 return strconv.FormatUint(uint64(v), 10)
38 case uint32:
39 return strconv.FormatUint(uint64(v), 10)
40 case uint64:
41 return strconv.FormatUint(v, 10)
42 case uint:
43 return strconv.FormatUint(uint64(v), 10)
44 default:
45 panic(ufmt.Sprintf("invalid type for FormatUint: %T", v))
46 }
47}
48
49// FormatBool converts a boolean to "true" or "false".
50func FormatBool(v bool) string {
51 return strconv.FormatBool(v)
52}
53
54// Uint64ToString returns the base-10 string representation of a uint64.
55func Uint64ToString(v uint64) string {
56 return strconv.FormatUint(v, 10)
57}
58
59// Int64ToString returns the base-10 string representation of an int64.
60func Int64ToString(v int64) string {
61 return strconv.FormatInt(v, 10)
62}
63
64// SafeParseInt64 parses a base-10 string into an int64, panicking when the
65// input is not a valid int64.
66func SafeParseInt64(value string) int64 {
67 parsed, err := strconv.ParseInt(value, 10, 64)
68 if err != nil {
69 panic(err)
70 }
71
72 return parsed
73}