summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorsiddharth <s@ricketyspace.net>2022-01-17 18:20:29 -0500
committersiddharth <s@ricketyspace.net>2022-01-17 18:20:29 -0500
commit78ceded6e90699a5da5297d2a6cf908ad9bf6c4c (patch)
tree5927450ba38c81625223ea9e44f496d1d42d5a52 /lib
parent4e9fe3548d49c3f139fcf43c05365e4718e098d1 (diff)
lib: add StrToNum
Diffstat (limited to 'lib')
-rw-r--r--lib/str.go28
-rw-r--r--lib/str_test.go42
2 files changed, 70 insertions, 0 deletions
diff --git a/lib/str.go b/lib/str.go
index 857268d..2f6ece4 100644
--- a/lib/str.go
+++ b/lib/str.go
@@ -153,3 +153,31 @@ func StrHas(s, n string) bool {
}
return false
}
+
+// Converts a string to an integer.
+func StrToNum(s string) (int, error) {
+ var negative bool
+ var n int
+
+ if len(s) < 1 {
+ return 0, CPError{"invalid number"}
+ }
+ if s[0] == '-' {
+ negative = true
+ s = s[1:]
+ }
+ u := 1
+ for i := len(s) - 1; i >= 0; i-- {
+ b := s[i]
+ if b >= '0' && b <= '9' {
+ n += int(b-48) * u
+ u *= 10
+ } else {
+ return 0, CPError{"invalid number"}
+ }
+ }
+ if negative {
+ n *= -1
+ }
+ return n, nil
+}
diff --git a/lib/str_test.go b/lib/str_test.go
new file mode 100644
index 0000000..1b1bb60
--- /dev/null
+++ b/lib/str_test.go
@@ -0,0 +1,42 @@
+// Copyright © 2022 siddharth <s@ricketyspace.net>
+// SPDX-License-Identifier: ISC
+
+package lib
+
+import "testing"
+
+func TestStrToNum(t *testing.T) {
+ // Test 1
+ s1 := "29283329"
+ n1, err := StrToNum(s1)
+ if err != nil {
+ t.Errorf("test 1 failed: %v\n", err)
+ }
+ if n1 != 29283329 {
+ t.Errorf("test 1 failed: %v != %v\n", s1, n1)
+ }
+
+ // Test 2
+ s2 := "-83729282"
+ n2, err := StrToNum(s2)
+ if err != nil {
+ t.Errorf("test 2 failed: %v\n", err)
+ }
+ if n2 != -83729282 {
+ t.Errorf("test 2 failed: %v != %v\n", s2, n2)
+ }
+
+ // Test 3
+ s3 := "887232.2323"
+ _, err = StrToNum(s3)
+ if err == nil {
+ t.Errorf("test 3 failed\n")
+ }
+
+ // Test 4
+ s4 := "332e323"
+ _, err = StrToNum(s4)
+ if err == nil {
+ t.Errorf("test 4 failed\n")
+ }
+}