aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/github.com/mitchellh/go-wordwrap/wordwrap.go')
-rw-r--r--vendor/github.com/mitchellh/go-wordwrap/wordwrap.go73
1 files changed, 73 insertions, 0 deletions
diff --git a/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go b/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go
new file mode 100644
index 0000000..ac67205
--- /dev/null
+++ b/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go
@@ -0,0 +1,73 @@
1package wordwrap
2
3import (
4 "bytes"
5 "unicode"
6)
7
8// WrapString wraps the given string within lim width in characters.
9//
10// Wrapping is currently naive and only happens at white-space. A future
11// version of the library will implement smarter wrapping. This means that
12// pathological cases can dramatically reach past the limit, such as a very
13// long word.
14func WrapString(s string, lim uint) string {
15 // Initialize a buffer with a slightly larger size to account for breaks
16 init := make([]byte, 0, len(s))
17 buf := bytes.NewBuffer(init)
18
19 var current uint
20 var wordBuf, spaceBuf bytes.Buffer
21
22 for _, char := range s {
23 if char == '\n' {
24 if wordBuf.Len() == 0 {
25 if current+uint(spaceBuf.Len()) > lim {
26 current = 0
27 } else {
28 current += uint(spaceBuf.Len())
29 spaceBuf.WriteTo(buf)
30 }
31 spaceBuf.Reset()
32 } else {
33 current += uint(spaceBuf.Len() + wordBuf.Len())
34 spaceBuf.WriteTo(buf)
35 spaceBuf.Reset()
36 wordBuf.WriteTo(buf)
37 wordBuf.Reset()
38 }
39 buf.WriteRune(char)
40 current = 0
41 } else if unicode.IsSpace(char) {
42 if spaceBuf.Len() == 0 || wordBuf.Len() > 0 {
43 current += uint(spaceBuf.Len() + wordBuf.Len())
44 spaceBuf.WriteTo(buf)
45 spaceBuf.Reset()
46 wordBuf.WriteTo(buf)
47 wordBuf.Reset()
48 }
49
50 spaceBuf.WriteRune(char)
51 } else {
52
53 wordBuf.WriteRune(char)
54
55 if current+uint(spaceBuf.Len()+wordBuf.Len()) > lim && uint(wordBuf.Len()) < lim {
56 buf.WriteRune('\n')
57 current = 0
58 spaceBuf.Reset()
59 }
60 }
61 }
62
63 if wordBuf.Len() == 0 {
64 if current+uint(spaceBuf.Len()) <= lim {
65 spaceBuf.WriteTo(buf)
66 }
67 } else {
68 spaceBuf.WriteTo(buf)
69 wordBuf.WriteTo(buf)
70 }
71
72 return buf.String()
73}