]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bsdconfig/share/strings.subr
Replace awk with more efficient builtins-only algo
[FreeBSD/FreeBSD.git] / usr.sbin / bsdconfig / share / strings.subr
1 if [ ! "$_STRINGS_SUBR" ]; then _STRINGS_SUBR=1
2 #
3 # Copyright (c) 2006-2013 Devin Teske
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 # 1. Redistributions of source code must retain the above copyright
10 #    notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 #    notice, this list of conditions and the following disclaimer in the
13 #    documentation and/or other materials provided with the distribution.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 # SUCH DAMAGE.
26 #
27 # $FreeBSD$
28 #
29 ############################################################ INCLUDES
30
31 BSDCFG_SHARE="/usr/share/bsdconfig"
32 . $BSDCFG_SHARE/common.subr || exit 1
33
34 ############################################################ GLOBALS
35
36 #
37 # A Literal newline (for use with f_replace_all(), or IFS, or whatever)
38 #
39 NL="
40 " # END-QUOTE
41
42 #
43 # Valid characters that can appear in an sh(1) variable name
44 #
45 # Please note that the character ranges A-Z and a-z should be avoided because
46 # these can include accent characters (which are not valid in a variable name).
47 # For example, A-Z matches any character that sorts after A but before Z,
48 # including A and Z. Although ASCII order would make more sense, that is not
49 # how it works.
50 #
51 VALID_VARNAME_CHARS="0-9ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
52
53 ############################################################ FUNCTIONS
54
55 # f_substr "$string" $start [$length]
56 #
57 # Simple wrapper to awk(1)'s `substr' function.
58 #
59 f_substr()
60 {
61         local string="$1" start="${2:-0}" len="${3:-0}"
62         echo "$string" | awk "{ print substr(\$0, $start, $len) }"
63 }
64
65 # f_snprintf $var_to_set $size $format [$arguments ...]
66 #
67 # Similar to snprintf(3), write at most $size number of bytes into $var_to_set
68 # using printf(1) syntax (`$format [$arguments ...]'). The value of $var_to_set
69 # is NULL unless at-least one byte is stored from the output.
70 #
71 f_snprintf()
72 {
73         local __funcname=f_snprintf
74         local __var_to_set="$1" __size="$2"
75         shift 2 # var_to_set size
76
77         if [ "$__size" -eq 0 ] 2> /dev/null; then
78                 setvar "$__var_to_set" ""
79                 return ${SUCCESS:-0}
80         elif [ $? -ge 2 ] || [ $__size -lt 0 ]; then
81                 setvar "$__var_to_set" ""
82                 echo "$__funcname: invalid size argument \`__size'" >&2
83                 return ${FAILURE:-1}
84         fi
85
86         local __f_snprintf_tmp
87         f_sprintf __f_snprintf_tmp "$@"
88
89         local __tmp_size=${#__f_snprintf_tmp}
90         local __trim=$(( $__tmp_size - $__size )) __trimq
91         local __tbuf __tbuf_len
92         local __mask __mask_len
93         while [ $__trim -gt 0 ]; do
94                 __tbuf="?"
95                 __tbuf_len=1
96                 if [ $__trim -le $__size ]; then
97                         while [ $__tbuf_len -lt $(( $__trim / $__tbuf_len )) ]
98                         do
99                                 __tbuf="$__tbuf?"
100                                 __tbuf_len=$(( $__tbuf_len + 1 ))
101                         done
102                         __trimq=$(( $__trim / $__tbuf_len ))
103                         __trim=$(( $__trim - $__tbuf_len * $__trimq ))
104                         while [ $__trimq -gt 0 ]; do
105                                 __f_snprintf_tmp="${__f_snprintf_tmp%$__tbuf}"
106                                 __trimq=$(( $__trimq - 1 ))
107                         done
108                 else
109                         __mask="$__f_snprintf_tmp"
110                         while [ $__tbuf_len -lt $(( $__size / $__tbuf_len )) ]
111                         do
112                                 __tbuf="$__tbuf?"
113                                 __tbuf_len=$(( $__tbuf_len + 1 ))
114                         done
115                         __trimq=$(( $__size / $__tbuf_len ))
116                         if [ $(( $__trimq * $__tbuf_len )) -ne $__size ]; then
117                                 __tbuf="$__tbuf?"
118                                 __tbuf_len=$(( $__tbuf_len + 1 ))
119                         fi
120                         __mask_len=$(( $__tmp_size - $__tbuf_len * $__trimq ))
121                         __trim=$(( $__tmp_size - $__mask_len - $__size ))
122                         while [ $__trimq -gt 0 ]; do
123                                 __mask="${__mask#$__tbuf}"
124                                 __trimq=$(( $__trimq - 1 ))
125                         done
126                         __f_snprintf_tmp="${__f_snprintf_tmp%"$__mask"}"
127                 fi
128         done
129         setvar "$__var_to_set" "$__f_snprintf_tmp"
130 }
131
132 # f_sprintf $var_to_set $format [$arguments ...]
133 #
134 # Similar to sprintf(3), write a string into $var_to_set using printf(1) syntax
135 # (`$format [$arguments ...]').
136 #
137 f_sprintf()
138 {
139         local __var_to_set="$1"
140         shift 1 # var_to_set
141         eval "$__var_to_set"=\$\( printf -- \"\$@\" \)
142 }
143
144 # f_vsnprintf $var_to_set $size $format $format_args
145 #
146 # Similar to vsnprintf(3), write at most $size number of bytes into $var_to_set
147 # using printf(1) syntax (`$format $format_args'). The value of $var_to_set is
148 # NULL unless at-least one byte is stored from the output.
149 #
150 # Example 1:
151 #
152 #       limit=7 format="%s"
153 #       format_args="'abc   123'" # 3-spaces between abc and 123
154 #       f_vsnprintf foo $limit "$format" "$format_args" # foo=[abc   1]
155 #
156 # Example 2:
157 #
158 #       limit=12 format="%s %s"
159 #       format_args="   'doghouse'      'fox'   "
160 #               # even more spaces added to illustrate escape-method
161 #       f_vsnprintf foo $limit "$format" "$format_args" # foo=[doghouse fox]
162 #
163 # Example 3:
164 #
165 #       limit=13 format="%s %s"
166 #       f_shell_escape arg1 'aaa"aaa' # arg1=[aaa"aaa] (no change)
167 #       f_shell_escape arg2 "aaa'aaa" # arg2=[aaa'\''aaa] (escaped s-quote)
168 #       format_args="'$arg1' '$arg2'" # use single-quotes to surround args
169 #       f_vsnprintf foo $limit "$format" "$format_args" # foo=[aaa"aaa aaa'a]
170 #
171 # In all of the above examples, the call to f_vsnprintf() does not change. Only
172 # the contents of $limit, $format, and $format_args changes in each example.
173 #
174 f_vsnprintf()
175 {
176         eval f_snprintf \"\$1\" \"\$2\" \"\$3\" $4
177 }
178
179 # f_vsprintf $var_to_set $format $format_args
180 #
181 # Similar to vsprintf(3), write a string into $var_to_set using printf(1)
182 # syntax (`$format $format_args').
183 #
184 f_vsprintf()
185 {
186         eval f_sprintf \"\$1\" \"\$2\" $3
187 }
188
189 # f_longest_line_length
190 #
191 # Simple wrapper to an awk(1) script to print the length of the longest line of
192 # input (read from stdin). Supports the newline escape-sequence `\n' for
193 # splitting a single line into multiple lines.
194 #
195 f_longest_line_length_awk='
196 BEGIN { longest = 0 }
197 {
198         if (split($0, lines, /\\n/) > 1)
199         {
200                 for (n in lines)
201                 {
202                         len = length(lines[n])
203                         longest = ( len > longest ? len : longest )
204                 }
205         }
206         else
207         {
208                 len = length($0)
209                 longest = ( len > longest ? len : longest )
210         }
211 }
212 END { print longest }
213 '
214 f_longest_line_length()
215 {
216         awk "$f_longest_line_length_awk"
217 }
218
219 # f_number_of_lines
220 #
221 # Simple wrapper to an awk(1) script to print the number of lines read from
222 # stdin. Supports newline escape-sequence `\n' for splitting a single line into
223 # multiple lines.
224 #
225 f_number_of_lines_awk='
226 BEGIN { num_lines = 0 }
227 {
228         num_lines += split(" "$0, unused, /\\n/)
229 }
230 END { print num_lines }
231 '
232 f_number_of_lines()
233 {
234         awk "$f_number_of_lines_awk"
235 }
236
237 # f_isinteger $arg
238 #
239 # Returns true if argument is a positive/negative whole integer.
240 #
241 f_isinteger()
242 {
243         local arg="${1#-}"
244         [ "${arg:-x}" = "${arg%[!0-9]*}" ]
245 }
246
247 # f_uriencode [$text]
248 #
249 # Encode $text for the purpose of embedding safely into a URL. Non-alphanumeric
250 # characters are converted to `%XX' sequence where XX represents the hexa-
251 # decimal ordinal of the non-alphanumeric character. If $text is missing, data
252 # is instead read from standard input.
253 #
254 f_uriencode_awk='
255 BEGIN {
256         output = ""
257         for (n = 0; n < 256; n++) pack[sprintf("%c", n)] = sprintf("%%%02x", n)
258 }
259 {
260         sline = ""
261         slen = length($0)
262         for (n = 1; n <= slen; n++) {
263                 char = substr($0, n, 1)
264                 if ( char !~ /^[[:alnum:]_]$/ ) char = pack[char]
265                 sline = sline char
266         }
267         output = output ( output ? "%0a" : "" ) sline
268 }
269 END { print output }
270 '
271 f_uriencode()
272 {
273         if [ $# -gt 0 ]; then
274                 echo "$1" | awk "$f_uriencode_awk"
275         else
276                 awk "$f_uriencode_awk"
277         fi
278 }
279
280 # f_uridecode [$text]
281 #
282 # Decode $text from a URI. Encoded characters are converted from their `%XX'
283 # sequence into original unencoded ASCII sequences. If $text is missing, data
284 # is instead read from standard input.
285 #
286 f_uridecode_awk='
287 BEGIN { for (n = 0; n < 256; n++) chr[n] = sprintf("%c", n) }
288 {
289         sline = ""
290         slen = length($0)
291         for (n = 1; n <= slen; n++)
292         {
293                 seq = substr($0, n, 3)
294                 if ( seq ~ /^%[[:xdigit:]][[:xdigit:]]$/ ) {
295                         hex = substr(seq, 2, 2)
296                         sline = sline chr[sprintf("%u", "0x"hex)]
297                         n += 2
298                 } else
299                         sline = sline substr(seq, 1, 1)
300         }
301         print sline
302 }
303 '
304 f_uridecode()
305 {
306         if [ $# -gt 0 ]; then
307                 echo "$1" | awk "$f_uridecode_awk"
308         else
309                 awk "$f_uridecode_awk"
310         fi
311 }
312
313 # f_replaceall $string $find $replace [$var_to_set]
314 #
315 # Replace all occurrences of $find in $string with $replace. If $var_to_set is
316 # either missing or NULL, the variable name is produced on standard out for
317 # capturing in a sub-shell (which is less recommended due to performance
318 # degradation).
319 #
320 # To replace newlines or a sequence containing the newline character, use $NL
321 # as `\n' is not supported.
322 #
323 f_replaceall()
324 {
325         local __left="" __right="$1"
326         local __find="$2" __replace="$3" __var_to_set="$4"
327         while :; do
328                 case "$__right" in *$__find*)
329                         __left="$__left${__right%%$__find*}$__replace"
330                         __right="${__right#*$__find}"
331                         continue
332                 esac
333                 break
334         done
335         __left="$__left${__right#*$__find}"
336         if [ "$__var_to_set" ]; then
337                 setvar "$__var_to_set" "$__left"
338         else
339                 echo "$__left"
340         fi
341 }
342
343 # f_str2varname $string [$var_to_set]
344 #
345 # Convert a string into a suitable value to be used as a variable name
346 # by converting unsuitable characters into the underscrore [_]. If $var_to_set
347 # is either missing or NULL, the variable name is produced on standard out for
348 # capturing in a sub-shell (which is less recommended due to performance
349 # degradation).
350 #
351 f_str2varname()
352 {
353         local __string="$1" __var_to_set="$2"
354         f_replaceall "$__string" "[!$VALID_VARNAME_CHARS]" "_" "$__var_to_set"
355 }
356
357 # f_shell_escape $string [$var_to_set]
358 #
359 # Escape $string for shell eval statement(s) by replacing all single-quotes
360 # with a special sequence that creates a compound string when interpolated
361 # by eval with surrounding single-quotes.
362 #
363 # For example:
364 #
365 #       foo="abc'123"
366 #       f_shell_escape "$foo" bar # bar=[abc'\''123]
367 #       eval echo \'$bar\' # produces abc'123
368 #
369 # This is helpful when processing an argument list that has to retain its
370 # escaped structure for later evaluations.
371 #
372 # WARNING: Surrounding single-quotes are not added; this is the responsibility
373 # of the code passing the escaped values to eval (which also aids readability).
374 #
375 f_shell_escape()
376 {
377         local __string="$1" __var_to_set="$2"
378         f_replaceall "$__string" "'" "'\\''" "$__var_to_set"
379 }
380
381 # f_shell_unescape $string [$var_to_set]
382 #
383 # The antithesis of f_shell_escape(), this function takes an escaped $string
384 # and expands it.
385 #
386 # For example:
387 #
388 #       foo="abc'123"
389 #       f_shell_escape "$foo" bar # bar=[abc'\''123]
390 #       f_shell_unescape "$bar" # produces abc'123
391 #
392 f_shell_unescape()
393 {
394         local __string="$1" __var_to_set="$2"
395         f_replaceall "$__string" "'\\''" "'" "$__var_to_set"
396 }
397
398 # f_expand_number $string [$var_to_set]
399 #
400 # Unformat $string into a number, optionally to be stored in $var_to_set. This
401 # function follows the SI power of two convention.
402 #
403 # The prefixes are:
404 #
405 #       Prefix  Description     Multiplier
406 #       k       kilo            1024
407 #       M       mega            1048576
408 #       G       giga            1073741824
409 #       T       tera            1099511627776
410 #       P       peta            1125899906842624
411 #       E       exa             1152921504606846976
412 #
413 # NOTE: Prefixes are case-insensitive.
414 #
415 # Upon successful completion, success status is returned; otherwise the number
416 # -1 is produced ($var_to_set set to -1 or if $var_to_set is NULL or missing)
417 # on standard output. In the case of failure, the error status will be one of:
418 #
419 #       Status  Reason
420 #       1       Given $string contains no digits
421 #       2       An unrecognized prefix was given
422 #       3       Result too large to calculate
423 #
424 f_expand_number()
425 {
426         local __string="$1" __var_to_set="$2"
427         local __cp __num __bshift __maxinput
428
429         # Remove any leading non-digits
430         __string="${__string#${__string%%[0-9]*}}"
431
432         # Store the numbers (no trailing suffix)
433         __num="${__string%%[!0-9]*}"
434
435         # Produce `-1' if string didn't contain any digits
436         if [ ! "$__num" ]; then
437                 if [ "$__var_to_set" ]; then
438                         setvar "$__var_to_set" -1
439                 else
440                         echo -1
441                 fi
442                 return 1 # 1 = "Given $string contains no digits"
443         fi
444
445         # Remove all the leading numbers from the string to get at the prefix
446         __string="${__string#"$__num"}"
447
448         #
449         # Test for invalid prefix (and determine bitshift length)
450         #
451         case "$__string" in
452         ""|[[:space:]]*) # Shortcut
453                 if [ "$__var_to_set" ]; then
454                         setvar "$__var_to_set" $__num
455                 else
456                         echo $__num
457                 fi
458                 return $SUCCESS ;;
459         [Kk]*) __bshift=10 ;;
460         [Mm]*) __bshift=20 ;;
461         [Gg]*) __bshift=30 ;;
462         [Tt]*) __bshift=40 ;;
463         [Pp]*) __bshift=50 ;;
464         [Ee]*) __bshift=60 ;;
465         *)
466                 # Unknown prefix
467                 if [ "$__var_to_set" ]; then
468                         setvar "$__var_to_set" -1
469                 else
470                         echo -1
471                 fi
472                 return 2 # 2 = "An unrecognized prefix was given"
473         esac
474
475         # Determine if the wheels fall off
476         __maxinput=$(( 0x7fffffffffffffff >> $__bshift ))
477         if [ $__num -gt $__maxinput ]; then
478                 # Input (before expanding) would exceed 64-bit signed int
479                 if [ "$__var_to_set" ]; then
480                         setvar "$__var_to_set" -1
481                 else
482                         echo -1
483                 fi
484                 return 3 # 3 = "Result too large to calculate"
485         fi
486
487         # Shift the number out and produce it
488         __num=$(( $__num << $__bshift ))
489         if [ "$__var_to_set" ]; then
490                 setvar "$__var_to_set" $__num
491         else
492                 echo $__num
493         fi
494 }
495
496 ############################################################ MAIN
497
498 f_dprintf "%s: Successfully loaded." strings.subr
499
500 fi # ! $_STRINGS_SUBR