podman

Форк
0
248 строк · 8.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
	"fmt"
21
	"math"
22
	"math/rand"
23
	"time"
24
	"unicode"
25
)
26

27
// RANDOM provides the time-based seed used to generate random numbers
28
var RANDOM = rand.New(rand.NewSource(time.Now().UnixNano()))
29

30
/*
31
RandomNonAlphaNumeric creates a random string whose length is the number of characters specified.
32
Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)).
33

34
Parameter:
35
	count - the length of random string to create
36

37
Returns:
38
	string - the random string
39
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
40
*/
41
func RandomNonAlphaNumeric(count int) (string, error) {
42
	return RandomAlphaNumericCustom(count, false, false)
43
}
44

45
/*
46
RandomAscii creates a random string whose length is the number of characters specified.
47
Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive).
48

49
Parameter:
50
	count - the length of random string to create
51

52
Returns:
53
	string - the random string
54
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
55
*/
56
func RandomAscii(count int) (string, error) {
57
	return Random(count, 32, 127, false, false)
58
}
59

60
/*
61
RandomNumeric creates a random string whose length is the number of characters specified.
62
Characters will be chosen from the set of numeric characters.
63

64
Parameter:
65
	count - the length of random string to create
66

67
Returns:
68
	string - the random string
69
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
70
*/
71
func RandomNumeric(count int) (string, error) {
72
	return Random(count, 0, 0, false, true)
73
}
74

75
/*
76
RandomAlphabetic creates a random string whose length is the number of characters specified.
77
Characters will be chosen from the set of alphabetic characters.
78

79
Parameters:
80
	count - the length of random string to create
81

82
Returns:
83
	string - the random string
84
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
85
*/
86
func RandomAlphabetic(count int) (string, error) {
87
	return Random(count, 0, 0, true, false)
88
}
89

90
/*
91
RandomAlphaNumeric creates a random string whose length is the number of characters specified.
92
Characters will be chosen from the set of alpha-numeric characters.
93

94
Parameter:
95
	count - the length of random string to create
96

97
Returns:
98
	string - the random string
99
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
100
*/
101
func RandomAlphaNumeric(count int) (string, error) {
102
	return Random(count, 0, 0, true, true)
103
}
104

105
/*
106
RandomAlphaNumericCustom creates a random string whose length is the number of characters specified.
107
Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
108

109
Parameters:
110
	count - the length of random string to create
111
	letters - if true, generated string may include alphabetic characters
112
	numbers - if true, generated string may include numeric characters
113

114
Returns:
115
	string - the random string
116
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
117
*/
118
func RandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) {
119
	return Random(count, 0, 0, letters, numbers)
120
}
121

122
/*
123
Random creates a random string based on a variety of options, using default source of randomness.
124
This method has exactly the same semantics as RandomSeed(int, int, int, bool, bool, []char, *rand.Rand), but
125
instead of using an externally supplied source of randomness, it uses the internal *rand.Rand instance.
126

127
Parameters:
128
	count - the length of random string to create
129
	start - the position in set of chars (ASCII/Unicode int) to start at
130
	end - the position in set of chars (ASCII/Unicode int) to end before
131
	letters - if true, generated string may include alphabetic characters
132
	numbers - if true, generated string may include numeric characters
133
	chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars.
134

135
Returns:
136
	string - the random string
137
	error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
138
*/
139
func Random(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) {
140
	return RandomSeed(count, start, end, letters, numbers, chars, RANDOM)
141
}
142

143
/*
144
RandomSeed creates a random string based on a variety of options, using supplied source of randomness.
145
If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used,
146
unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively.
147
If chars is not nil, characters stored in chars that are between start and end are chosen.
148
This method accepts a user-supplied *rand.Rand instance to use as a source of randomness. By seeding a single *rand.Rand instance
149
with a fixed seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably.
150

151
Parameters:
152
	count - the length of random string to create
153
	start - the position in set of chars (ASCII/Unicode decimals) to start at
154
	end - the position in set of chars (ASCII/Unicode decimals) to end before
155
	letters - if true, generated string may include alphabetic characters
156
	numbers - if true, generated string may include numeric characters
157
	chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars.
158
	random - a source of randomness.
159

160
Returns:
161
	string - the random string
162
	error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars)
163
*/
164
func RandomSeed(count int, start int, end int, letters bool, numbers bool, chars []rune, random *rand.Rand) (string, error) {
165

166
	if count == 0 {
167
		return "", nil
168
	} else if count < 0 {
169
		err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...")
170
		return "", err
171
	}
172
	if chars != nil && len(chars) == 0 {
173
		err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty")
174
		return "", err
175
	}
176

177
	if start == 0 && end == 0 {
178
		if chars != nil {
179
			end = len(chars)
180
		} else {
181
			if !letters && !numbers {
182
				end = math.MaxInt32
183
			} else {
184
				end = 'z' + 1
185
				start = ' '
186
			}
187
		}
188
	} else {
189
		if end <= start {
190
			err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start)
191
			return "", err
192
		}
193

194
		if chars != nil && end > len(chars) {
195
			err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars))
196
			return "", err
197
		}
198
	}
199

200
	buffer := make([]rune, count)
201
	gap := end - start
202

203
	// high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319
204
	//  low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343
205

206
	for count != 0 {
207
		count--
208
		var ch rune
209
		if chars == nil {
210
			ch = rune(random.Intn(gap) + start)
211
		} else {
212
			ch = chars[random.Intn(gap)+start]
213
		}
214

215
		if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers {
216
			if ch >= 56320 && ch <= 57343 { // low surrogate range
217
				if count == 0 {
218
					count++
219
				} else {
220
					// Insert low surrogate
221
					buffer[count] = ch
222
					count--
223
					// Insert high surrogate
224
					buffer[count] = rune(55296 + random.Intn(128))
225
				}
226
			} else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial)
227
				if count == 0 {
228
					count++
229
				} else {
230
					// Insert low surrogate
231
					buffer[count] = rune(56320 + random.Intn(128))
232
					count--
233
					// Insert high surrogate
234
					buffer[count] = ch
235
				}
236
			} else if ch >= 56192 && ch <= 56319 {
237
				// private high surrogate, skip it
238
				count++
239
			} else {
240
				// not one of the surrogates*
241
				buffer[count] = ch
242
			}
243
		} else {
244
			count++
245
		}
246
	}
247
	return string(buffer), nil
248
}
249

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

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

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

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