micro/src/util.go

63 lines
1.2 KiB
Go
Raw Normal View History

2016-03-17 21:27:57 +00:00
package main
import (
"unicode/utf8"
)
2016-03-25 16:14:22 +00:00
// Util.go is a collection of utility functions that are used throughout
// the program
2016-03-19 00:40:00 +00:00
// Count returns the length of a string in runes
2016-03-25 16:14:22 +00:00
// This is exactly equivalent to utf8.RuneCountInString(), just less characters
2016-03-19 00:40:00 +00:00
func Count(s string) int {
2016-03-17 21:27:57 +00:00
return utf8.RuneCountInString(s)
}
2016-03-19 00:40:00 +00:00
// NumOccurences counts the number of occurences of a byte in a string
func NumOccurences(s string, c byte) int {
2016-03-17 21:27:57 +00:00
var n int
for i := 0; i < len(s); i++ {
if s[i] == c {
n++
}
}
return n
}
2016-03-25 16:14:22 +00:00
// Spaces returns a string with n spaces
func Spaces(n int) string {
2016-03-17 21:27:57 +00:00
var str string
for i := 0; i < n; i++ {
str += " "
}
return str
}
2016-03-25 16:14:22 +00:00
// Min takes the min of two ints
func Min(a, b int) int {
if a > b {
return b
}
return a
}
// Max takes the max of two ints
func Max(a, b int) int {
if a > b {
return a
}
return b
}
2016-03-28 12:43:08 +00:00
// IsWordChar returns whether or not the string is a 'word character'
// If it is a unicode character, then it does not match
// Word characters are defined as [A-Za-z0-9_]
func IsWordChar(str string) bool {
if len(str) > 1 {
// Unicode
return false
}
c := str[0]
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_')
}