/* The MIT License (MIT) Copyright © 2020-2025 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Single-file source-code for utfate. To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath utfate.go */ package main import ( "bufio" "bytes" "encoding/binary" "errors" "io" "os" "unicode" "unicode/utf16" ) // Note: the code is avoiding using the fmt package to save hundreds of // kilobytes on the resulting executable, which is a noticeable difference. const info = ` utfate [options...] [file...] This app turns plain-text input into UTF-8. Supported input formats are - ASCII - UTF-8 - UTF-8 with a leading BOM - UTF-16 BE - UTF-16 LE - UTF-32 BE - UTF-32 LE All (optional) leading options start with either single or double-dash: -h show this help message -help show this help message ` // errNoMoreOutput is a dummy error, whose message is ignored, and which // causes the app to quit immediately and successfully var errNoMoreOutput = errors.New(`no more output`) const errorStyle = "\x1b[31m" func main() { if len(os.Args) > 1 { switch os.Args[1] { case `-h`, `--h`, `-help`, `--help`: os.Stderr.WriteString(info[1:]) return } } if err := run(os.Stdout, os.Args[1:]); isActualError(err) { os.Stderr.WriteString(errorStyle) os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\x1b[0m\n") os.Exit(1) } } func run(w io.Writer, args []string) error { bw := bufio.NewWriter(w) defer bw.Flush() for _, path := range args { if err := handleFile(bw, path); err != nil { return err } } if len(args) == 0 { return utfate(bw, os.Stdin) } return nil } func handleFile(w *bufio.Writer, name string) error { if name == `-` { return utfate(w, os.Stdin) } f, err := os.Open(name) if err != nil { return errors.New(`can't read from file named "` + name + `"`) } defer f.Close() return utfate(w, f) } // isActualError is to figure out whether not to ignore an error, and thus // show it as an error message func isActualError(err error) bool { return err != nil && err != io.EOF && err != errNoMoreOutput } func utfate(w io.Writer, r io.Reader) error { br := bufio.NewReader(r) bw := bufio.NewWriter(w) defer bw.Flush() lead, err := br.Peek(4) if err != nil { return err } if bytes.HasPrefix(lead, []byte{'\x00', '\x00', '\xfe', '\xff'}) { br.Discard(4) return utf32toUTF8(bw, br, binary.BigEndian) } if bytes.HasPrefix(lead, []byte{'\xff', '\xfe', '\x00', '\x00'}) { br.Discard(4) return utf32toUTF8(bw, br, binary.LittleEndian) } if bytes.HasPrefix(lead, []byte{'\xfe', '\xff'}) { br.Discard(2) return utf16toUTF8(bw, br, readBytePairBE) } if bytes.HasPrefix(lead, []byte{'\xff', '\xfe'}) { br.Discard(2) return utf16toUTF8(bw, br, readBytePairLE) } if bytes.HasPrefix(lead, []byte{'\xef', '\xbb', '\xbf'}) { br.Discard(3) return handleUTF8(bw, br) } return handleUTF8(bw, br) } func leadASCII(buf []byte) int { for i, b := range buf { if b < 128 { continue } return i } return len(buf) } func handleUTF8(w *bufio.Writer, r *bufio.Reader) error { for { c, _, err := r.ReadRune() if c == unicode.ReplacementChar { return errors.New(`invalid UTF-8 stream`) } if err != nil { if err == io.EOF { return nil } return err } _, err = w.WriteRune(c) if err != nil { return errNoMoreOutput } } } func fancyHandleUTF8(w *bufio.Writer, r *bufio.Reader) error { lookahead := 1 maxAhead := r.Size() / 2 for { // look ahead to check for ASCII runs ahead, err := r.Peek(lookahead) if err == io.EOF { return nil } if err != nil { return err } // copy leading ASCII runs n := leadASCII(ahead) if n > 0 { w.Write(ahead[:n]) r.Discard(n) } // adapt lookahead size if n == len(ahead) && lookahead < maxAhead { lookahead *= 2 } else if lookahead > 1 { lookahead /= 2 } if n == len(ahead) { continue } c, _, err := r.ReadRune() if c == unicode.ReplacementChar { return errors.New(`invalid UTF-8 stream`) } if err == io.EOF { return nil } if err != nil { return err } _, err = w.WriteRune(c) if err != nil { return errNoMoreOutput } } } // readPairFunc narrows source-code lines below type readPairFunc func(*bufio.Reader) (byte, byte, error) // utf16toUTF8 handles UTF-16 inputs for func utfate func utf16toUTF8(w *bufio.Writer, r *bufio.Reader, read2 readPairFunc) error { for { a, b, err := read2(r) if err == io.EOF { return nil } if err != nil { return err } c := rune(256*int(a) + int(b)) if utf16.IsSurrogate(c) { a, b, err := read2(r) if err == io.EOF { return nil } if err != nil { return err } next := rune(256*int(a) + int(b)) c = utf16.DecodeRune(c, next) } _, err = w.WriteRune(c) if err != nil { return errNoMoreOutput } } } // readBytePairBE gets you a pair of bytes in big-endian (original) order func readBytePairBE(br *bufio.Reader) (byte, byte, error) { a, err := br.ReadByte() if err != nil { return a, 0, err } b, err := br.ReadByte() return a, b, err } // readBytePairLE gets you a pair of bytes in little-endian order func readBytePairLE(br *bufio.Reader) (byte, byte, error) { a, b, err := readBytePairBE(br) return b, a, err } // utf32toUTF8 handles UTF-32 inputs for func utfate func utf32toUTF8(w *bufio.Writer, r *bufio.Reader, o binary.ByteOrder) error { var n uint32 for { err := binary.Read(r, o, &n) if err == io.EOF { return nil } if err != nil { return err } _, err = w.WriteRune(rune(n)) if err != nil { return errNoMoreOutput } } }