Merge pull request #7 from jimeh/improve-performance

This commit is contained in:
2022-12-04 23:55:21 +00:00
committed by GitHub

View File

@@ -5,6 +5,7 @@ package undent
import ( import (
"fmt" "fmt"
"io" "io"
"strings"
) )
const ( const (
@@ -20,50 +21,33 @@ func Bytes(s string) []byte {
return []byte{} return []byte{}
} }
// find line feeds
lfs := []int{}
if s[0] != lf {
lfs = append(lfs, -1)
}
for i := 0; i < len(s); i++ {
if s[i] == lf {
lfs = append(lfs, i)
}
}
// find smallest indent relative to each line-feed // find smallest indent relative to each line-feed
min := 99999999999 min := 99999999999
count := 0 count := 0
for i := 0; i < len(lfs); i++ { lfs := make([]int, 0, strings.Count(s, "\n"))
offset := lfs[i] if s[0] != lf {
end := len(s) - 1 lfs = append(lfs, -1)
if i+1 < len(lfs) { }
end = lfs[i+1]
}
if offset+1 >= end { indent := 0
continue for i := 0; i < len(s); i++ {
} if s[i] == lf {
lfs = append(lfs, i)
indent := 0 indent = 0
lineSeek: } else if indent < min {
for n := offset + 1; n < end && indent < min; n++ { switch s[i] {
switch s[n] {
case spc, tab: case spc, tab:
indent++ indent++
default: default:
break lineSeek if indent > 0 {
count++
}
if indent < min {
min = indent
}
} }
} }
if indent < min {
min = indent
}
if indent > 0 {
count++
}
} }
// extract each line without indentation // extract each line without indentation