github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/encoding/hex/hex.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package hex implements hexadecimal encoding and decoding. 6 package hex 7 8 import ( 9 "bytes" 10 "errors" 11 "fmt" 12 "io" 13 ) 14 15 const hextable = "0123456789abcdef" 16 17 // EncodedLen returns the length of an encoding of n source bytes. 18 // Specifically, it returns n * 2. 19 func EncodedLen(n int) int { return n * 2 } 20 21 // Encode encodes src into EncodedLen(len(src)) 22 // bytes of dst. As a convenience, it returns the number 23 // of bytes written to dst, but this value is always EncodedLen(len(src)). 24 // Encode implements hexadecimal encoding. 25 func Encode(dst, src []byte) int { 26 for i, v := range src { 27 dst[i*2] = hextable[v>>4] 28 dst[i*2+1] = hextable[v&0x0f] 29 } 30 31 return len(src) * 2 32 } 33 34 // ErrLength results from decoding an odd length slice. 35 var ErrLength = errors.New("encoding/hex: odd length hex string") 36 37 // InvalidByteError values describe errors resulting from an invalid byte in a hex string. 38 type InvalidByteError byte 39 40 func (e InvalidByteError) Error() string { 41 return fmt.Sprintf("encoding/hex: invalid byte: %#U", rune(e)) 42 } 43 44 // DecodedLen returns the length of a decoding of x source bytes. 45 // Specifically, it returns x / 2. 46 func DecodedLen(x int) int { return x / 2 } 47 48 // Decode decodes src into DecodedLen(len(src)) bytes, 49 // returning the actual number of bytes written to dst. 50 // 51 // Decode expects that src contain only hexadecimal 52 // characters and that src should have an even length. 53 func Decode(dst, src []byte) (int, error) { 54 if len(src)%2 == 1 { 55 return 0, ErrLength 56 } 57 58 for i := 0; i < len(src)/2; i++ { 59 a, ok := fromHexChar(src[i*2]) 60 if !ok { 61 return 0, InvalidByteError(src[i*2]) 62 } 63 b, ok := fromHexChar(src[i*2+1]) 64 if !ok { 65 return 0, InvalidByteError(src[i*2+1]) 66 } 67 dst[i] = (a << 4) | b 68 } 69 70 return len(src) / 2, nil 71 } 72 73 // fromHexChar converts a hex character into its value and a success flag. 74 func fromHexChar(c byte) (byte, bool) { 75 switch { 76 case '0' <= c && c <= '9': 77 return c - '0', true 78 case 'a' <= c && c <= 'f': 79 return c - 'a' + 10, true 80 case 'A' <= c && c <= 'F': 81 return c - 'A' + 10, true 82 } 83 84 return 0, false 85 } 86 87 // EncodeToString returns the hexadecimal encoding of src. 88 func EncodeToString(src []byte) string { 89 dst := make([]byte, EncodedLen(len(src))) 90 Encode(dst, src) 91 return string(dst) 92 } 93 94 // DecodeString returns the bytes represented by the hexadecimal string s. 95 func DecodeString(s string) ([]byte, error) { 96 src := []byte(s) 97 // We can use the source slice itself as the destination 98 // because the decode loop increments by one and then the 'seen' byte is not used anymore. 99 len, err := Decode(src, src) 100 if err != nil { 101 return nil, err 102 } 103 return src[:len], nil 104 } 105 106 // Dump returns a string that contains a hex dump of the given data. The format 107 // of the hex dump matches the output of `hexdump -C` on the command line. 108 func Dump(data []byte) string { 109 var buf bytes.Buffer 110 dumper := Dumper(&buf) 111 dumper.Write(data) 112 dumper.Close() 113 return buf.String() 114 } 115 116 // Dumper returns a WriteCloser that writes a hex dump of all written data to 117 // w. The format of the dump matches the output of `hexdump -C` on the command 118 // line. 119 func Dumper(w io.Writer) io.WriteCloser { 120 return &dumper{w: w} 121 } 122 123 type dumper struct { 124 w io.Writer 125 rightChars [18]byte 126 buf [14]byte 127 used int // number of bytes in the current line 128 n uint // number of bytes, total 129 } 130 131 func toChar(b byte) byte { 132 if b < 32 || b > 126 { 133 return '.' 134 } 135 return b 136 } 137 138 func (h *dumper) Write(data []byte) (n int, err error) { 139 // Output lines look like: 140 // 00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=| 141 // ^ offset ^ extra space ^ ASCII of line. 142 for i := range data { 143 if h.used == 0 { 144 // At the beginning of a line we print the current 145 // offset in hex. 146 h.buf[0] = byte(h.n >> 24) 147 h.buf[1] = byte(h.n >> 16) 148 h.buf[2] = byte(h.n >> 8) 149 h.buf[3] = byte(h.n) 150 Encode(h.buf[4:], h.buf[:4]) 151 h.buf[12] = ' ' 152 h.buf[13] = ' ' 153 _, err = h.w.Write(h.buf[4:]) 154 if err != nil { 155 return 156 } 157 } 158 Encode(h.buf[:], data[i:i+1]) 159 h.buf[2] = ' ' 160 l := 3 161 if h.used == 7 { 162 // There's an additional space after the 8th byte. 163 h.buf[3] = ' ' 164 l = 4 165 } else if h.used == 15 { 166 // At the end of the line there's an extra space and 167 // the bar for the right column. 168 h.buf[3] = ' ' 169 h.buf[4] = '|' 170 l = 5 171 } 172 _, err = h.w.Write(h.buf[:l]) 173 if err != nil { 174 return 175 } 176 n++ 177 h.rightChars[h.used] = toChar(data[i]) 178 h.used++ 179 h.n++ 180 if h.used == 16 { 181 h.rightChars[16] = '|' 182 h.rightChars[17] = '\n' 183 _, err = h.w.Write(h.rightChars[:]) 184 if err != nil { 185 return 186 } 187 h.used = 0 188 } 189 } 190 return 191 } 192 193 func (h *dumper) Close() (err error) { 194 // See the comments in Write() for the details of this format. 195 if h.used == 0 { 196 return 197 } 198 h.buf[0] = ' ' 199 h.buf[1] = ' ' 200 h.buf[2] = ' ' 201 h.buf[3] = ' ' 202 h.buf[4] = '|' 203 nBytes := h.used 204 for h.used < 16 { 205 l := 3 206 if h.used == 7 { 207 l = 4 208 } else if h.used == 15 { 209 l = 5 210 } 211 _, err = h.w.Write(h.buf[:l]) 212 if err != nil { 213 return 214 } 215 h.used++ 216 } 217 h.rightChars[nBytes] = '|' 218 h.rightChars[nBytes+1] = '\n' 219 _, err = h.w.Write(h.rightChars[:nBytes+2]) 220 return 221 }