From 663106ef6e3ee3c3a8d9231137aeccf1ddad6e1b Mon Sep 17 00:00:00 2001 From: greatroar <61184462+greatroar@users.noreply.github.com> Date: Mon, 21 Nov 2022 12:58:00 +0100 Subject: [PATCH] lib/fs: Optimize WindowsInvalidFilename (#8687) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaced strings.Split with the new strings.Cut, which doesn't allocate. name old time/op new time/op delta WindowsInvalidFilenameValid-8 154ns ± 2% 89ns ± 0% -42.09% (p=0.000 n=10+9) WindowsInvalidFilenameNUL-8 124ns ± 2% 124ns ± 1% ~ (p=0.371 n=8+10) name old alloc/op new alloc/op delta WindowsInvalidFilenameValid-8 16.0B ± 0% 0.0B -100.00% (p=0.000 n=10+10) WindowsInvalidFilenameNUL-8 19.0B ± 0% 3.0B ± 0% -84.21% (p=0.000 n=10+10) name old allocs/op new allocs/op delta WindowsInvalidFilenameValid-8 1.00 ± 0% 0.00 -100.00% (p=0.000 n=10+10) WindowsInvalidFilenameNUL-8 2.00 ± 0% 1.00 ± 0% -50.00% (p=0.000 n=10+10) --- lib/fs/util.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/fs/util.go b/lib/fs/util.go index 8e648e118..9e977cb37 100644 --- a/lib/fs/util.go +++ b/lib/fs/util.go @@ -53,9 +53,17 @@ const windowsDisallowedCharacters = (`<>:"|?*` + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") func WindowsInvalidFilename(name string) error { + // The path must not contain any disallowed characters. + if strings.ContainsAny(name, windowsDisallowedCharacters) { + return errInvalidFilenameWindowsReservedChar + } + // None of the path components should end in space or period, or be a // reserved name. - for _, part := range strings.Split(name, `\`) { + for len(name) > 0 { + part, rest, _ := strings.Cut(name, `\`) + name = rest + if part == "" { continue } @@ -69,11 +77,6 @@ func WindowsInvalidFilename(name string) error { } } - // The path must not contain any disallowed characters - if strings.ContainsAny(name, windowsDisallowedCharacters) { - return errInvalidFilenameWindowsReservedChar - } - return nil }