github.com/sandwich-go/boost@v1.3.29/misc/goformat/util.go (about) 1 package goformat 2 3 import "bytes" 4 5 func cutSpace(b []byte) (before, middle, after []byte) { 6 i := 0 7 for i < len(b) && (b[i] == ' ' || b[i] == '\t' || b[i] == '\n') { 8 i++ 9 } 10 j := len(b) 11 for j > 0 && (b[j-1] == ' ' || b[j-1] == '\t' || b[j-1] == '\n') { 12 j-- 13 } 14 if i <= j { 15 return b[:i], b[i:j], b[j:] 16 } 17 return nil, nil, b[j:] 18 } 19 20 func matchSpace(orig []byte, src []byte) []byte { 21 before0, _, after := cutSpace(orig) 22 i := bytes.LastIndex(before0, []byte{'\n'}) 23 before1, indent := before0[:i+1], before0[i+1:] 24 _, src, _ = cutSpace(src) 25 var b bytes.Buffer 26 b.Write(before1) 27 for len(src) > 0 { 28 line := src 29 if i := bytes.IndexByte(line, '\n'); i >= 0 { 30 line, src = line[:i+1], line[i+1:] 31 } else { 32 src = nil 33 } 34 if len(line) > 0 && line[0] != '\n' { // not blank 35 b.Write(indent) 36 } 37 b.Write(line) 38 } 39 b.Write(after) 40 return b.Bytes() 41 }