embed: simplify the code

Use stringslite and bytealg to simplify the code and to remove redundent
helper functions.
This commit is contained in:
apocelipes 2024-05-20 19:06:08 +08:00
parent e3d87d1932
commit e9e3bebdb4
1 changed files with 5 additions and 18 deletions

View File

@ -130,6 +130,8 @@ package embed
import ( import (
"errors" "errors"
"internal/bytealg"
"internal/stringslite"
"io" "io"
"io/fs" "io/fs"
"time" "time"
@ -185,29 +187,14 @@ type FS struct {
// comment in the FS struct above. isDir reports whether the // comment in the FS struct above. isDir reports whether the
// final trailing slash was present, indicating that name is a directory. // final trailing slash was present, indicating that name is a directory.
func split(name string) (dir, elem string, isDir bool) { func split(name string) (dir, elem string, isDir bool) {
if name[len(name)-1] == '/' { name, isDir = stringslite.CutSuffix(name, "/")
isDir = true i := bytealg.LastIndexByteString(name, '/')
name = name[:len(name)-1]
}
i := len(name) - 1
for i >= 0 && name[i] != '/' {
i--
}
if i < 0 { if i < 0 {
return ".", name, isDir return ".", name, isDir
} }
return name[:i], name[i+1:], isDir return name[:i], name[i+1:], isDir
} }
// trimSlash trims a trailing slash from name, if present,
// returning the possibly shortened name.
func trimSlash(name string) string {
if len(name) > 0 && name[len(name)-1] == '/' {
return name[:len(name)-1]
}
return name
}
var ( var (
_ fs.ReadDirFS = FS{} _ fs.ReadDirFS = FS{}
_ fs.ReadFileFS = FS{} _ fs.ReadFileFS = FS{}
@ -274,7 +261,7 @@ func (f FS) lookup(name string) *file {
idir, ielem, _ := split(files[i].name) idir, ielem, _ := split(files[i].name)
return idir > dir || idir == dir && ielem >= elem return idir > dir || idir == dir && ielem >= elem
}) })
if i < len(files) && trimSlash(files[i].name) == name { if i < len(files) && stringslite.TrimSuffix(files[i].name, "/") == name {
return &files[i] return &files[i]
} }
return nil return nil