Debian Codegraph @

charset/ascii.go

raw symbols SCIP
1 package charset
2
3 import (
4 "bytes"
5 "fmt"
6 "unicode/utf8"
7 )
8
9 func init() {
10 registerClass("ascii", fromASCII, toASCII)
11 }
12
13 const errorByte = '?'
14
15 type translateFromASCII bool
16
17 type codePointError struct {
18 i int
19 cp rune
20 charset string
21 }
22
23 func (e *codePointError) Error() string {
24 return fmt.Sprintf("Parse error at index %d: Code point %d is undefined in %s", e.i, e.cp, e.charset)
25 }
26
27 func (strict translateFromASCII) Translate(data []byte, eof bool) (int, []byte, error) {
28 buf := bytes.NewBuffer(make([]byte, 0, len(data)))
29 for i, c := range data {
30 if c > 0 && c < 128 {
31 buf.WriteByte(c)
32 if c < 32 && c != 10 && c != 13 && c != 9 {
33 // badly formed
34 }
35 } else {
36 if strict {
37 return 0, nil, &codePointError{i, rune(c), "US-ASCII"}
38 }
39 buf.WriteRune(utf8.RuneError)
40 }
41 }
42 return len(data), buf.Bytes(), nil
43 }
44
45 type translateToASCII bool
46
47 func (strict translateToASCII) Translate(data []byte, eof bool) (int, []byte, error) {
48 buf := bytes.NewBuffer(make([]byte, 0, len(data)))
49 for _, c := range data {
50 if c > 0 && c < 128 {
51 buf.WriteByte(c)
52 } else {
53 buf.WriteByte(errorByte)
54 }
55 }
56 return len(data), buf.Bytes(), nil
57 }
58
59 func fromASCII(arg string) (Translator, error) {
60 return new(translateFromASCII), nil
61 }
62
63 func toASCII(arg string) (Translator, error) {
64 return new(translateToASCII), nil
65 }