-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
87 lines (76 loc) · 2.28 KB
/
validate.go
File metadata and controls
87 lines (76 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package strings
import (
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// Routines in this file are aids to validation checking
// IsASCII returns true if the string contains only ascii characters
func IsASCII(s string) bool {
// idea adapted from here:
// https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/unicode/utf8/utf8.go;l=528
for len(s) > 0 {
if len(s) >= 8 {
first32 := uint32(s[0]) | uint32(s[1])<<8 | uint32(s[2])<<16 | uint32(s[3])<<24
second32 := uint32(s[4]) | uint32(s[5])<<8 | uint32(s[6])<<16 | uint32(s[7])<<24
if (first32|second32)&0x80808080 != 0 {
return false
}
s = s[8:]
continue
}
if s[0] > unicode.MaxASCII {
return false
}
s = s[1:]
}
return true
}
// IsUTF8 returns true if the given string only contains valid UTF-8 characters
func IsUTF8(s string) bool {
return utf8.ValidString(s)
}
// IsUTF8Bytes returns true if the given byte array only contains valid UTF-8 characters
func IsUTF8Bytes(b []byte) bool {
return utf8.Valid(b)
}
// IsInt returns true if the given string is an integer.
// Allows the string to start with a + or -.
func IsInt(s string) bool {
_, err := strconv.Atoi(s)
return err == nil
}
// IsFloat returns true if the given string is a floating point number.
// Allows the string to start with a + or -.
func IsFloat(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
// StripNewlines removes all newline characters from a string.
func StripNewlines(s string) string {
s = strings.Replace(s, "\n", "", -1)
s = strings.Replace(s, "\r", "", -1)
return s
}
// StripNulls removes null characters from a string.
// Null characters are highly unusual in a string and may indicate an attempt to plant hidden information.
func StripNulls(s string) string {
s = strings.Replace(s, "\000", "", -1)
return s
}
// HasNull returns true if the given string has a null character in it.
// Null characters are highly unusual in a string, and can indicate that an attempt is being made
// to plant hidden data into storage.
func HasNull(s string) bool {
return strings.Contains(s, "\000")
}
// IsWhitespace returns true if the given string only contains whitespace characters.
func IsWhitespace(s string) bool {
for _, r := range s {
if !unicode.IsSpace(r) {
return false
}
}
return true
}