wrapString wraps the given string within lim width in characters. Source: https://github.com/mitchellh/go-wordwrap Wrapping is currently naive and only happens at white-space. A future version of the library will implement smarter wrapping. This means that pathological cases can dramatically reach
(s string, lim uint)
| 189 | // pathological cases can dramatically reach past the limit, such as a very |
| 190 | // long word. |
| 191 | func wrapString(s string, lim uint) string { |
| 192 | // Initialize a buffer with a slightly larger size to account for breaks |
| 193 | init := make([]byte, 0, len(s)) |
| 194 | buf := bytes.NewBuffer(init) |
| 195 | |
| 196 | var current uint |
| 197 | var wordBuf, spaceBuf bytes.Buffer |
| 198 | |
| 199 | for _, char := range s { |
| 200 | if char == '\n' { |
| 201 | if wordBuf.Len() == 0 { |
| 202 | if current+uint(spaceBuf.Len()) > lim { |
| 203 | current = 0 |
| 204 | } else { |
| 205 | current += uint(spaceBuf.Len()) |
| 206 | spaceBuf.WriteTo(buf) |
| 207 | } |
| 208 | spaceBuf.Reset() |
| 209 | } else { |
| 210 | current += uint(spaceBuf.Len() + wordBuf.Len()) |
| 211 | spaceBuf.WriteTo(buf) |
| 212 | spaceBuf.Reset() |
| 213 | wordBuf.WriteTo(buf) |
| 214 | wordBuf.Reset() |
| 215 | } |
| 216 | buf.WriteRune(char) |
| 217 | current = 0 |
| 218 | } else if unicode.IsSpace(char) { |
| 219 | if spaceBuf.Len() == 0 || wordBuf.Len() > 0 { |
| 220 | current += uint(spaceBuf.Len() + wordBuf.Len()) |
| 221 | spaceBuf.WriteTo(buf) |
| 222 | spaceBuf.Reset() |
| 223 | wordBuf.WriteTo(buf) |
| 224 | wordBuf.Reset() |
| 225 | } |
| 226 | |
| 227 | spaceBuf.WriteRune(char) |
| 228 | } else { |
| 229 | |
| 230 | wordBuf.WriteRune(char) |
| 231 | |
| 232 | if current+uint(spaceBuf.Len()+wordBuf.Len()) > lim && uint(wordBuf.Len()) < lim { |
| 233 | buf.WriteRune('\n') |
| 234 | current = 0 |
| 235 | spaceBuf.Reset() |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | if wordBuf.Len() == 0 { |
| 241 | if current+uint(spaceBuf.Len()) <= lim { |
| 242 | spaceBuf.WriteTo(buf) |
| 243 | } |
| 244 | } else { |
| 245 | spaceBuf.WriteTo(buf) |
| 246 | wordBuf.WriteTo(buf) |
| 247 | } |
| 248 |
no test coverage detected