|
1 | 1 | package easygen |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
4 | 6 | "regexp" |
5 | 7 | "strings" |
6 | 8 | ) |
|
10 | 12 | rec *regexp.Regexp |
11 | 13 | ) |
12 | 14 |
|
| 15 | +//////////////////////////////////////////////////////////////////////////// |
| 16 | +// Normal String Function Definitions |
| 17 | + |
| 18 | +// Taken/adapted from hugo tpl/strings/strings.go |
| 19 | + |
| 20 | +// Substr extracts parts of a string, beginning at the character at the specified |
| 21 | +// position, and returns the specified number of characters. |
| 22 | +// |
| 23 | +// It normally takes two parameters: start and length. |
| 24 | +// It can also take one parameter: start, i.e. length is omitted, in which case |
| 25 | +// the substring starting from start until the end of the string will be returned. |
| 26 | +// |
| 27 | +// To extract characters from the end of the string, use a negative start number. |
| 28 | +// |
| 29 | +// In addition, borrowing from the extended behavior described at http://php.net/substr, |
| 30 | +// if length is given and is negative, then that many characters will be omitted from |
| 31 | +// the end of string. |
| 32 | +func Substr(a string, nums ...interface{}) (string, error) { |
| 33 | + var start, length int |
| 34 | + |
| 35 | + asRunes := []rune(a) |
| 36 | + |
| 37 | + switch len(nums) { |
| 38 | + case 0: |
| 39 | + return "", errors.New("too less arguments") |
| 40 | + case 1: |
| 41 | + start = nums[0].(int) |
| 42 | + length = len(asRunes) |
| 43 | + case 2: |
| 44 | + start = nums[0].(int) |
| 45 | + length = nums[1].(int) |
| 46 | + default: |
| 47 | + return "", errors.New("too many arguments") |
| 48 | + } |
| 49 | + |
| 50 | + if start < -len(asRunes) { |
| 51 | + start = 0 |
| 52 | + } |
| 53 | + if start > len(asRunes) { |
| 54 | + return "", fmt.Errorf("start position out of bounds for %d-byte string", len(a)) |
| 55 | + } |
| 56 | + |
| 57 | + var s, e int |
| 58 | + if start >= 0 && length >= 0 { |
| 59 | + s = start |
| 60 | + e = start + length |
| 61 | + } else if start < 0 && length >= 0 { |
| 62 | + s = len(asRunes) + start |
| 63 | + e = len(asRunes) + start + length + 1 |
| 64 | + } else if start >= 0 && length < 0 { |
| 65 | + s = start |
| 66 | + e = len(asRunes) + length |
| 67 | + } else { |
| 68 | + s = len(asRunes) + start |
| 69 | + e = len(asRunes) + length |
| 70 | + } |
| 71 | + |
| 72 | + if s > e { |
| 73 | + return "", fmt.Errorf("calculated start position greater than end position: %d > %d", s, e) |
| 74 | + } |
| 75 | + if e > len(asRunes) { |
| 76 | + e = len(asRunes) |
| 77 | + } |
| 78 | + |
| 79 | + return string(asRunes[s:e]), nil |
| 80 | +} |
| 81 | + |
13 | 82 | //////////////////////////////////////////////////////////////////////////// |
14 | 83 | // Regexp Function Definitions |
15 | 84 |
|
|
0 commit comments