podman

Форк
0
240 строк · 6.3 Кб
1
/*
2
Copyright 2014 Alexander Okoli
3

4
Licensed under the Apache License, Version 2.0 (the "License");
5
you may not use this file except in compliance with the License.
6
You may obtain a copy of the License at
7

8
    http://www.apache.org/licenses/LICENSE-2.0
9

10
Unless required by applicable law or agreed to in writing, software
11
distributed under the License is distributed on an "AS IS" BASIS,
12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16

17
package goutils
18

19
import (
20
	"bytes"
21
	"fmt"
22
	"strings"
23
	"unicode"
24
)
25

26
// Typically returned by functions where a searched item cannot be found
27
const INDEX_NOT_FOUND = -1
28

29
/*
30
Abbreviate abbreviates a string using ellipses. This will turn  the string "Now is the time for all good men" into "Now is the time for..."
31

32
Specifically, the algorithm is as follows:
33

34
    - If str is less than maxWidth characters long, return it.
35
    - Else abbreviate it to (str[0:maxWidth - 3] + "...").
36
    - If maxWidth is less than 4, return an illegal argument error.
37
    - In no case will it return a string of length greater than maxWidth.
38

39
Parameters:
40
    str -  the string to check
41
    maxWidth - maximum length of result string, must be at least 4
42

43
Returns:
44
    string - abbreviated string
45
    error - if the width is too small
46
*/
47
func Abbreviate(str string, maxWidth int) (string, error) {
48
	return AbbreviateFull(str, 0, maxWidth)
49
}
50

51
/*
52
AbbreviateFull abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "...is the time for..."
53
This function works like Abbreviate(string, int), but allows you to specify a "left edge" offset. Note that this left edge is not
54
necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear
55
somewhere in the result.
56
In no case will it return a string of length greater than maxWidth.
57

58
Parameters:
59
    str - the string to check
60
    offset - left edge of source string
61
    maxWidth - maximum length of result string, must be at least 4
62

63
Returns:
64
    string - abbreviated string
65
    error - if the width is too small
66
*/
67
func AbbreviateFull(str string, offset int, maxWidth int) (string, error) {
68
	if str == "" {
69
		return "", nil
70
	}
71
	if maxWidth < 4 {
72
		err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width is 4")
73
		return "", err
74
	}
75
	if len(str) <= maxWidth {
76
		return str, nil
77
	}
78
	if offset > len(str) {
79
		offset = len(str)
80
	}
81
	if len(str)-offset < (maxWidth - 3) { // 15 - 5 < 10 - 3 =  10 < 7
82
		offset = len(str) - (maxWidth - 3)
83
	}
84
	abrevMarker := "..."
85
	if offset <= 4 {
86
		return str[0:maxWidth-3] + abrevMarker, nil // str.substring(0, maxWidth - 3) + abrevMarker;
87
	}
88
	if maxWidth < 7 {
89
		err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width with offset is 7")
90
		return "", err
91
	}
92
	if (offset + maxWidth - 3) < len(str) { // 5 + (10-3) < 15 = 12 < 15
93
		abrevStr, _ := Abbreviate(str[offset:len(str)], (maxWidth - 3))
94
		return abrevMarker + abrevStr, nil // abrevMarker + abbreviate(str.substring(offset), maxWidth - 3);
95
	}
96
	return abrevMarker + str[(len(str)-(maxWidth-3)):len(str)], nil // abrevMarker + str.substring(str.length() - (maxWidth - 3));
97
}
98

99
/*
100
DeleteWhiteSpace deletes all whitespaces from a string as defined by unicode.IsSpace(rune).
101
It returns the string without whitespaces.
102

103
Parameter:
104
    str - the string to delete whitespace from, may be nil
105

106
Returns:
107
    the string without whitespaces
108
*/
109
func DeleteWhiteSpace(str string) string {
110
	if str == "" {
111
		return str
112
	}
113
	sz := len(str)
114
	var chs bytes.Buffer
115
	count := 0
116
	for i := 0; i < sz; i++ {
117
		ch := rune(str[i])
118
		if !unicode.IsSpace(ch) {
119
			chs.WriteRune(ch)
120
			count++
121
		}
122
	}
123
	if count == sz {
124
		return str
125
	}
126
	return chs.String()
127
}
128

129
/*
130
IndexOfDifference compares two strings, and returns the index at which the strings begin to differ.
131

132
Parameters:
133
    str1 - the first string
134
    str2 - the second string
135

136
Returns:
137
    the index where str1 and str2 begin to differ; -1 if they are equal
138
*/
139
func IndexOfDifference(str1 string, str2 string) int {
140
	if str1 == str2 {
141
		return INDEX_NOT_FOUND
142
	}
143
	if IsEmpty(str1) || IsEmpty(str2) {
144
		return 0
145
	}
146
	var i int
147
	for i = 0; i < len(str1) && i < len(str2); i++ {
148
		if rune(str1[i]) != rune(str2[i]) {
149
			break
150
		}
151
	}
152
	if i < len(str2) || i < len(str1) {
153
		return i
154
	}
155
	return INDEX_NOT_FOUND
156
}
157

158
/*
159
IsBlank checks if a string is whitespace or empty (""). Observe the following behavior:
160

161
    goutils.IsBlank("")        = true
162
    goutils.IsBlank(" ")       = true
163
    goutils.IsBlank("bob")     = false
164
    goutils.IsBlank("  bob  ") = false
165

166
Parameter:
167
    str - the string to check
168

169
Returns:
170
    true - if the string is whitespace or empty ("")
171
*/
172
func IsBlank(str string) bool {
173
	strLen := len(str)
174
	if str == "" || strLen == 0 {
175
		return true
176
	}
177
	for i := 0; i < strLen; i++ {
178
		if unicode.IsSpace(rune(str[i])) == false {
179
			return false
180
		}
181
	}
182
	return true
183
}
184

185
/*
186
IndexOf returns the index of the first instance of sub in str, with the search beginning from the
187
index start point specified. -1 is returned if sub is not present in str.
188

189
An empty string ("") will return -1 (INDEX_NOT_FOUND). A negative start position is treated as zero.
190
A start position greater than the string length returns -1.
191

192
Parameters:
193
    str - the string to check
194
    sub - the substring to find
195
    start - the start position; negative treated as zero
196

197
Returns:
198
    the first index where the sub string was found  (always >= start)
199
*/
200
func IndexOf(str string, sub string, start int) int {
201

202
	if start < 0 {
203
		start = 0
204
	}
205

206
	if len(str) < start {
207
		return INDEX_NOT_FOUND
208
	}
209

210
	if IsEmpty(str) || IsEmpty(sub) {
211
		return INDEX_NOT_FOUND
212
	}
213

214
	partialIndex := strings.Index(str[start:len(str)], sub)
215
	if partialIndex == -1 {
216
		return INDEX_NOT_FOUND
217
	}
218
	return partialIndex + start
219
}
220

221
// IsEmpty checks if a string is empty (""). Returns true if empty, and false otherwise.
222
func IsEmpty(str string) bool {
223
	return len(str) == 0
224
}
225

226
// Returns either the passed in string, or if the string is empty, the value of defaultStr.
227
func DefaultString(str string, defaultStr string) string {
228
	if IsEmpty(str) {
229
		return defaultStr
230
	}
231
	return str
232
}
233

234
// Returns either the passed in string, or if the string is whitespace, empty (""), the value of defaultStr.
235
func DefaultIfBlank(str string, defaultStr string) string {
236
	if IsBlank(str) {
237
		return defaultStr
238
	}
239
	return str
240
}
241

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.