| 1 |
package stringutil |
| 2 |
|
| 3 |
// Wrap builds a byte slice from strs, wrapping on word boundaries before max chars |
| 4 |
func Wrap(max int, strs ...string) []byte { |
| 5 |
input := make([]byte, 0) |
| 6 |
output := make([]byte, 0) |
| 7 |
for _, s := range strs { |
| 8 |
input = append(input, []byte(s)...) |
| 9 |
} |
| 10 |
if len(input) < max { |
| 11 |
// Doesn't need to be wrapped |
| 12 |
return input |
| 13 |
} |
| 14 |
ls := -1 // Last seen space index |
| 15 |
lw := -1 // Last written byte index |
| 16 |
ll := 0 // Length of current line |
| 17 |
for i := 0; i < len(input); i++ { |
| 18 |
ll++ |
| 19 |
switch input[i] { |
| 20 |
case ' ', '\t': |
| 21 |
ls = i |
| 22 |
} |
| 23 |
if ll >= max { |
| 24 |
if ls >= 0 { |
| 25 |
output = append(output, input[lw+1:ls]...) |
| 26 |
output = append(output, '\r', '\n', ' ') |
| 27 |
lw = ls // Jump over the space we broke on |
| 28 |
ll = 1 // Count leading space above |
| 29 |
// Rewind |
| 30 |
i = lw + 1 |
| 31 |
ls = -1 |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
return append(output, input[lw+1:]...) |
| 36 |
} |