podman

Форк
0
357 строк · 9.6 Кб
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
/*
18
Package goutils provides utility functions to manipulate strings in various ways.
19
The code snippets below show examples of how to use goutils. Some functions return
20
errors while others do not, so usage would vary as a result.
21

22
Example:
23

24
    package main
25

26
    import (
27
        "fmt"
28
        "github.com/aokoli/goutils"
29
    )
30

31
    func main() {
32

33
        // EXAMPLE 1: A goutils function which returns no errors
34
        fmt.Println (goutils.Initials("John Doe Foo")) // Prints out "JDF"
35

36

37

38
        // EXAMPLE 2: A goutils function which returns an error
39
        rand1, err1 := goutils.Random (-1, 0, 0, true, true)
40

41
        if err1 != nil {
42
            fmt.Println(err1) // Prints out error message because -1 was entered as the first parameter in goutils.Random(...)
43
        } else {
44
            fmt.Println(rand1)
45
        }
46
    }
47
*/
48
package goutils
49

50
import (
51
	"bytes"
52
	"strings"
53
	"unicode"
54
)
55

56
// VERSION indicates the current version of goutils
57
const VERSION = "1.0.0"
58

59
/*
60
Wrap wraps a single line of text, identifying words by ' '.
61
New lines will be separated by '\n'. Very long words, such as URLs will not be wrapped.
62
Leading spaces on a new line are stripped. Trailing spaces are not stripped.
63

64
Parameters:
65
    str - the string to be word wrapped
66
    wrapLength - the column (a column can fit only one character) to wrap the words at, less than 1 is treated as 1
67

68
Returns:
69
    a line with newlines inserted
70
*/
71
func Wrap(str string, wrapLength int) string {
72
	return WrapCustom(str, wrapLength, "", false)
73
}
74

75
/*
76
WrapCustom wraps a single line of text, identifying words by ' '.
77
Leading spaces on a new line are stripped. Trailing spaces are not stripped.
78

79
Parameters:
80
    str - the string to be word wrapped
81
    wrapLength - the column number (a column can fit only one character) to wrap the words at, less than 1 is treated as 1
82
    newLineStr - the string to insert for a new line, "" uses '\n'
83
    wrapLongWords - true if long words (such as URLs) should be wrapped
84

85
Returns:
86
    a line with newlines inserted
87
*/
88
func WrapCustom(str string, wrapLength int, newLineStr string, wrapLongWords bool) string {
89

90
	if str == "" {
91
		return ""
92
	}
93
	if newLineStr == "" {
94
		newLineStr = "\n" // TODO Assumes "\n" is seperator. Explore SystemUtils.LINE_SEPARATOR from Apache Commons
95
	}
96
	if wrapLength < 1 {
97
		wrapLength = 1
98
	}
99

100
	inputLineLength := len(str)
101
	offset := 0
102

103
	var wrappedLine bytes.Buffer
104

105
	for inputLineLength-offset > wrapLength {
106

107
		if rune(str[offset]) == ' ' {
108
			offset++
109
			continue
110
		}
111

112
		end := wrapLength + offset + 1
113
		spaceToWrapAt := strings.LastIndex(str[offset:end], " ") + offset
114

115
		if spaceToWrapAt >= offset {
116
			// normal word (not longer than wrapLength)
117
			wrappedLine.WriteString(str[offset:spaceToWrapAt])
118
			wrappedLine.WriteString(newLineStr)
119
			offset = spaceToWrapAt + 1
120

121
		} else {
122
			// long word or URL
123
			if wrapLongWords {
124
				end := wrapLength + offset
125
				// long words are wrapped one line at a time
126
				wrappedLine.WriteString(str[offset:end])
127
				wrappedLine.WriteString(newLineStr)
128
				offset += wrapLength
129
			} else {
130
				// long words aren't wrapped, just extended beyond limit
131
				end := wrapLength + offset
132
				index := strings.IndexRune(str[end:len(str)], ' ')
133
				if index == -1 {
134
					wrappedLine.WriteString(str[offset:len(str)])
135
					offset = inputLineLength
136
				} else {
137
					spaceToWrapAt = index + end
138
					wrappedLine.WriteString(str[offset:spaceToWrapAt])
139
					wrappedLine.WriteString(newLineStr)
140
					offset = spaceToWrapAt + 1
141
				}
142
			}
143
		}
144
	}
145

146
	wrappedLine.WriteString(str[offset:len(str)])
147

148
	return wrappedLine.String()
149

150
}
151

152
/*
153
Capitalize capitalizes all the delimiter separated words in a string. Only the first letter of each word is changed.
154
To convert the rest of each word to lowercase at the same time, use CapitalizeFully(str string, delimiters ...rune).
155
The delimiters represent a set of characters understood to separate words. The first string character
156
and the first non-delimiter character after a delimiter will be capitalized. A "" input string returns "".
157
Capitalization uses the Unicode title case, normally equivalent to upper case.
158

159
Parameters:
160
    str - the string to capitalize
161
    delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter
162

163
Returns:
164
    capitalized string
165
*/
166
func Capitalize(str string, delimiters ...rune) string {
167

168
	var delimLen int
169

170
	if delimiters == nil {
171
		delimLen = -1
172
	} else {
173
		delimLen = len(delimiters)
174
	}
175

176
	if str == "" || delimLen == 0 {
177
		return str
178
	}
179

180
	buffer := []rune(str)
181
	capitalizeNext := true
182
	for i := 0; i < len(buffer); i++ {
183
		ch := buffer[i]
184
		if isDelimiter(ch, delimiters...) {
185
			capitalizeNext = true
186
		} else if capitalizeNext {
187
			buffer[i] = unicode.ToTitle(ch)
188
			capitalizeNext = false
189
		}
190
	}
191
	return string(buffer)
192

193
}
194

195
/*
196
CapitalizeFully converts all the delimiter separated words in a string into capitalized words, that is each word is made up of a
197
titlecase character and then a series of lowercase characters. The delimiters represent a set of characters understood
198
to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized.
199
Capitalization uses the Unicode title case, normally equivalent to upper case.
200

201
Parameters:
202
    str - the string to capitalize fully
203
    delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter
204

205
Returns:
206
    capitalized string
207
*/
208
func CapitalizeFully(str string, delimiters ...rune) string {
209

210
	var delimLen int
211

212
	if delimiters == nil {
213
		delimLen = -1
214
	} else {
215
		delimLen = len(delimiters)
216
	}
217

218
	if str == "" || delimLen == 0 {
219
		return str
220
	}
221
	str = strings.ToLower(str)
222
	return Capitalize(str, delimiters...)
223
}
224

225
/*
226
Uncapitalize uncapitalizes all the whitespace separated words in a string. Only the first letter of each word is changed.
227
The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter
228
character after a delimiter will be uncapitalized. Whitespace is defined by unicode.IsSpace(char).
229

230
Parameters:
231
    str - the string to uncapitalize fully
232
    delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter
233

234
Returns:
235
    uncapitalized string
236
*/
237
func Uncapitalize(str string, delimiters ...rune) string {
238

239
	var delimLen int
240

241
	if delimiters == nil {
242
		delimLen = -1
243
	} else {
244
		delimLen = len(delimiters)
245
	}
246

247
	if str == "" || delimLen == 0 {
248
		return str
249
	}
250

251
	buffer := []rune(str)
252
	uncapitalizeNext := true // TODO Always makes capitalize/un apply to first char.
253
	for i := 0; i < len(buffer); i++ {
254
		ch := buffer[i]
255
		if isDelimiter(ch, delimiters...) {
256
			uncapitalizeNext = true
257
		} else if uncapitalizeNext {
258
			buffer[i] = unicode.ToLower(ch)
259
			uncapitalizeNext = false
260
		}
261
	}
262
	return string(buffer)
263
}
264

265
/*
266
SwapCase swaps the case of a string using a word based algorithm.
267

268
Conversion algorithm:
269

270
    Upper case character converts to Lower case
271
    Title case character converts to Lower case
272
    Lower case character after Whitespace or at start converts to Title case
273
    Other Lower case character converts to Upper case
274
    Whitespace is defined by unicode.IsSpace(char).
275

276
Parameters:
277
    str - the string to swap case
278

279
Returns:
280
    the changed string
281
*/
282
func SwapCase(str string) string {
283
	if str == "" {
284
		return str
285
	}
286
	buffer := []rune(str)
287

288
	whitespace := true
289

290
	for i := 0; i < len(buffer); i++ {
291
		ch := buffer[i]
292
		if unicode.IsUpper(ch) {
293
			buffer[i] = unicode.ToLower(ch)
294
			whitespace = false
295
		} else if unicode.IsTitle(ch) {
296
			buffer[i] = unicode.ToLower(ch)
297
			whitespace = false
298
		} else if unicode.IsLower(ch) {
299
			if whitespace {
300
				buffer[i] = unicode.ToTitle(ch)
301
				whitespace = false
302
			} else {
303
				buffer[i] = unicode.ToUpper(ch)
304
			}
305
		} else {
306
			whitespace = unicode.IsSpace(ch)
307
		}
308
	}
309
	return string(buffer)
310
}
311

312
/*
313
Initials extracts the initial letters from each word in the string. The first letter of the string and all first
314
letters after the defined delimiters are returned as a new string. Their case is not changed. If the delimiters
315
parameter is excluded, then Whitespace is used. Whitespace is defined by unicode.IsSpacea(char). An empty delimiter array returns an empty string.
316

317
Parameters:
318
    str - the string to get initials from
319
    delimiters - set of characters to determine words, exclusion of this parameter means whitespace would be delimeter
320
Returns:
321
    string of initial letters
322
*/
323
func Initials(str string, delimiters ...rune) string {
324
	if str == "" {
325
		return str
326
	}
327
	if delimiters != nil && len(delimiters) == 0 {
328
		return ""
329
	}
330
	strLen := len(str)
331
	var buf bytes.Buffer
332
	lastWasGap := true
333
	for i := 0; i < strLen; i++ {
334
		ch := rune(str[i])
335

336
		if isDelimiter(ch, delimiters...) {
337
			lastWasGap = true
338
		} else if lastWasGap {
339
			buf.WriteRune(ch)
340
			lastWasGap = false
341
		}
342
	}
343
	return buf.String()
344
}
345

346
// private function (lower case func name)
347
func isDelimiter(ch rune, delimiters ...rune) bool {
348
	if delimiters == nil {
349
		return unicode.IsSpace(ch)
350
	}
351
	for _, delimiter := range delimiters {
352
		if ch == delimiter {
353
			return true
354
		}
355
	}
356
	return false
357
}
358

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

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

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

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