| 1 |
// Package strutil provides various utilities for manipulating strings |
| 2 |
package strutil |
| 3 |
|
| 4 |
import ( |
| 5 |
"bytes" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
// PadRight returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character. |
| 10 |
func PadRight(str string, length int, pad byte) string { |
| 11 |
if len(str) >= length { |
| 12 |
return str |
| 13 |
} |
| 14 |
buf := bytes.NewBufferString(str) |
| 15 |
for i := 0; i < length-len(str); i++ { |
| 16 |
buf.WriteByte(pad) |
| 17 |
} |
| 18 |
return buf.String() |
| 19 |
} |
| 20 |
|
| 21 |
// PadLeft returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character. |
| 22 |
func PadLeft(str string, length int, pad byte) string { |
| 23 |
if len(str) >= length { |
| 24 |
return str |
| 25 |
} |
| 26 |
var buf bytes.Buffer |
| 27 |
for i := 0; i < length-len(str); i++ { |
| 28 |
buf.WriteByte(pad) |
| 29 |
} |
| 30 |
buf.WriteString(str) |
| 31 |
return buf.String() |
| 32 |
} |
| 33 |
|
| 34 |
// Resize resizes the string with the given length. It ellipses with '...' when the string's length exceeds |
| 35 |
// the desired length or pads spaces to the right of the string when length is smaller than desired |
| 36 |
func Resize(s string, length uint) string { |
| 37 |
n := int(length) |
| 38 |
if len(s) == n { |
| 39 |
return s |
| 40 |
} |
| 41 |
// Pads only when length of the string smaller than len needed |
| 42 |
s = PadRight(s, n, ' ') |
| 43 |
if len(s) > n { |
| 44 |
b := []byte(s) |
| 45 |
var buf bytes.Buffer |
| 46 |
for i := 0; i < n-3; i++ { |
| 47 |
buf.WriteByte(b[i]) |
| 48 |
} |
| 49 |
buf.WriteString("...") |
| 50 |
s = buf.String() |
| 51 |
} |
| 52 |
return s |
| 53 |
} |
| 54 |
|
| 55 |
// PrettyTime returns the string representation of the duration. It rounds the time duration to a second and returns a "---" when duration is 0 |
| 56 |
func PrettyTime(t time.Duration) string { |
| 57 |
if t == 0 { |
| 58 |
return "---" |
| 59 |
} |
| 60 |
return (t - (t % time.Second)).String() |
| 61 |
} |