github.com/karrick/gorill@v1.10.3/newline.go (about) 1 package gorill 2 3 // newline returns a string with exactly one terminating newline character. 4 // More simple than strings.TrimRight. When input string ends with multiple 5 // newline characters, it will strip off all but first one, reusing the same 6 // underlying string bytes. When string does not end in a newline character, it 7 // returns the original string with a newline character appended. Newline 8 // characters before any non-newline characters are ignored. 9 func newline(s string) string { 10 l := len(s) 11 if l == 0 { 12 return "\n" 13 } 14 15 // While this is O(length s), it stops as soon as it finds the first non 16 // newline character in the string starting from the right hand side of the 17 // input string. Generally this only scans one or two characters and 18 // returns. 19 20 for i := l - 1; i >= 0; i-- { 21 if s[i] != '\n' { 22 if i+1 < l && s[i+1] == '\n' { 23 return s[:i+2] 24 } 25 return s[:i+1] + "\n" 26 } 27 } 28 29 return s[:1] // all newline characters, so just return the first one 30 }