2019-01-05 22:44:33 +00:00
|
|
|
package files
|
|
|
|
|
2019-05-07 18:02:12 +00:00
|
|
|
import (
|
2020-11-24 10:32:23 +00:00
|
|
|
"os"
|
2019-05-07 18:02:12 +00:00
|
|
|
"unicode/utf8"
|
|
|
|
)
|
|
|
|
|
2021-01-07 10:30:17 +00:00
|
|
|
func isBinary(content []byte) bool {
|
2019-05-07 18:02:12 +00:00
|
|
|
maybeStr := string(content)
|
|
|
|
runeCnt := utf8.RuneCount(content)
|
|
|
|
runeIndex := 0
|
|
|
|
gotRuneErrCnt := 0
|
|
|
|
firstRuneErrIndex := -1
|
|
|
|
|
2020-05-31 23:12:36 +00:00
|
|
|
const (
|
2019-01-05 22:44:33 +00:00
|
|
|
// 8 and below are control chars (e.g. backspace, null, eof, etc)
|
2020-05-31 23:12:36 +00:00
|
|
|
maxControlCharsCode = 8
|
|
|
|
// 0xFFFD(65533) is the "error" Rune or "Unicode replacement character"
|
|
|
|
// see https://golang.org/pkg/unicode/utf8/#pkg-constants
|
|
|
|
unicodeReplacementChar = 0xFFFD
|
|
|
|
)
|
|
|
|
|
|
|
|
for _, b := range maybeStr {
|
|
|
|
if b <= maxControlCharsCode {
|
2019-01-05 22:44:33 +00:00
|
|
|
return true
|
|
|
|
}
|
2019-05-07 18:02:12 +00:00
|
|
|
|
2020-05-31 23:12:36 +00:00
|
|
|
if b == unicodeReplacementChar {
|
|
|
|
// if it is not the last (utf8.UTFMax - x) rune
|
2019-05-07 18:02:12 +00:00
|
|
|
if runeCnt > utf8.UTFMax && runeIndex < runeCnt-utf8.UTFMax {
|
|
|
|
return true
|
2020-05-31 23:12:36 +00:00
|
|
|
}
|
|
|
|
// else it is the last (utf8.UTFMax - x) rune
|
|
|
|
// there maybe Vxxx, VVxx, VVVx, thus, we may got max 3 0xFFFD rune (assume V is the byte we got)
|
|
|
|
// for Chinese, it can only be Vxx, VVx, we may got max 2 0xFFFD rune
|
|
|
|
gotRuneErrCnt++
|
2019-05-07 18:02:12 +00:00
|
|
|
|
2020-05-31 23:12:36 +00:00
|
|
|
// mark the first time
|
|
|
|
if firstRuneErrIndex == -1 {
|
|
|
|
firstRuneErrIndex = runeIndex
|
2019-05-07 18:02:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
runeIndex++
|
|
|
|
}
|
|
|
|
|
2020-05-31 23:12:36 +00:00
|
|
|
// if last (utf8.UTFMax - x ) rune has the "error" Rune, but not all
|
2019-05-07 18:02:12 +00:00
|
|
|
if firstRuneErrIndex != -1 && gotRuneErrCnt != runeCnt-firstRuneErrIndex {
|
|
|
|
return true
|
2019-01-05 22:44:33 +00:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2020-11-24 10:32:23 +00:00
|
|
|
|
|
|
|
func IsNamedPipe(mode os.FileMode) bool {
|
|
|
|
return mode&os.ModeNamedPipe != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsSymlink(mode os.FileMode) bool {
|
|
|
|
return mode&os.ModeSymlink != 0
|
|
|
|
}
|