]> git.lizzy.rs Git - micro.git/blob - cmd/micro/util.go
fe3f031c42e09c6660ee6284bd28d20dd71386d9
[micro.git] / cmd / micro / util.go
1 package main
2
3 import (
4         "unicode/utf8"
5 )
6
7 // Util.go is a collection of utility functions that are used throughout
8 // the program
9
10 // Count returns the length of a string in runes
11 // This is exactly equivalent to utf8.RuneCountInString(), just less characters
12 func Count(s string) int {
13         return utf8.RuneCountInString(s)
14 }
15
16 // NumOccurences counts the number of occurences of a byte in a string
17 func NumOccurences(s string, c byte) int {
18         var n int
19         for i := 0; i < len(s); i++ {
20                 if s[i] == c {
21                         n++
22                 }
23         }
24         return n
25 }
26
27 // Spaces returns a string with n spaces
28 func Spaces(n int) string {
29         var str string
30         for i := 0; i < n; i++ {
31                 str += " "
32         }
33         return str
34 }
35
36 // Min takes the min of two ints
37 func Min(a, b int) int {
38         if a > b {
39                 return b
40         }
41         return a
42 }
43
44 // Max takes the max of two ints
45 func Max(a, b int) int {
46         if a > b {
47                 return a
48         }
49         return b
50 }
51
52 // IsWordChar returns whether or not the string is a 'word character'
53 // If it is a unicode character, then it does not match
54 // Word characters are defined as [A-Za-z0-9_]
55 func IsWordChar(str string) bool {
56         if len(str) > 1 {
57                 // Unicode
58                 return false
59         }
60         c := str[0]
61         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '_')
62 }
63
64 // Contains returns whether or not a string array contains a given string
65 func Contains(list []string, a string) bool {
66         for _, b := range list {
67                 if b == a {
68                         return true
69                 }
70         }
71         return false
72 }
73
74 // Insert makes a simple insert into a string at the given position
75 func Insert(str string, pos int, value string) string {
76         return string([]rune(str)[:pos]) + value + string([]rune(str)[pos:])
77 }
78
79 // GetLeadingWhitespace returns the leading whitespace of the given string
80 func GetLeadingWhitespace(str string) string {
81         ws := ""
82         for _, c := range str {
83                 if c == ' ' || c == '\t' {
84                         ws += string(c)
85                 } else {
86                         break
87                 }
88         }
89         return ws
90 }
91
92 // IsSpaces checks if a given string is only spaces
93 func IsSpaces(str string) bool {
94         for _, c := range str {
95                 if c != ' ' {
96                         return false
97                 }
98         }
99
100         return true
101 }