]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/encoding/hex/hex.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.git] / libgo / go / encoding / hex / hex.go
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 // This package implements hexadecimal encoding and decoding.
6 package hex
7
8 import (
9 "os"
10 "strconv"
11 )
12
13 const hextable = "0123456789abcdef"
14
15 // EncodedLen returns the length of an encoding of n source bytes.
16 func EncodedLen(n int) int { return n * 2 }
17
18 // Encode encodes src into EncodedLen(len(src))
19 // bytes of dst. As a convenience, it returns the number
20 // of bytes written to dst, but this value is always EncodedLen(len(src)).
21 // Encode implements hexadecimal encoding.
22 func Encode(dst, src []byte) int {
23 for i, v := range src {
24 dst[i*2] = hextable[v>>4]
25 dst[i*2+1] = hextable[v&0x0f]
26 }
27
28 return len(src) * 2
29 }
30
31 // OddLengthInputError results from decoding an odd length slice.
32 type OddLengthInputError struct{}
33
34 func (OddLengthInputError) String() string { return "odd length hex string" }
35
36 // InvalidHexCharError results from finding an invalid character in a hex string.
37 type InvalidHexCharError byte
38
39 func (e InvalidHexCharError) String() string {
40 return "invalid hex char: " + strconv.Itoa(int(e))
41 }
42
43
44 func DecodedLen(x int) int { return x / 2 }
45
46 // Decode decodes src into DecodedLen(len(src)) bytes, returning the actual
47 // number of bytes written to dst.
48 //
49 // If Decode encounters invalid input, it returns an OddLengthInputError or an
50 // InvalidHexCharError.
51 func Decode(dst, src []byte) (int, os.Error) {
52 if len(src)%2 == 1 {
53 return 0, OddLengthInputError{}
54 }
55
56 for i := 0; i < len(src)/2; i++ {
57 a, ok := fromHexChar(src[i*2])
58 if !ok {
59 return 0, InvalidHexCharError(src[i*2])
60 }
61 b, ok := fromHexChar(src[i*2+1])
62 if !ok {
63 return 0, InvalidHexCharError(src[i*2+1])
64 }
65 dst[i] = (a << 4) | b
66 }
67
68 return len(src) / 2, nil
69 }
70
71 // fromHexChar converts a hex character into its value and a success flag.
72 func fromHexChar(c byte) (byte, bool) {
73 switch {
74 case '0' <= c && c <= '9':
75 return c - '0', true
76 case 'a' <= c && c <= 'f':
77 return c - 'a' + 10, true
78 case 'A' <= c && c <= 'F':
79 return c - 'A' + 10, true
80 }
81
82 return 0, false
83 }
84
85 // EncodeToString returns the hexadecimal encoding of src.
86 func EncodeToString(src []byte) string {
87 dst := make([]byte, EncodedLen(len(src)))
88 Encode(dst, src)
89 return string(dst)
90 }
91
92 // DecodeString returns the bytes represented by the hexadecimal string s.
93 func DecodeString(s string) ([]byte, os.Error) {
94 src := []byte(s)
95 dst := make([]byte, DecodedLen(len(src)))
96 _, err := Decode(dst, src)
97 if err != nil {
98 return nil, err
99 }
100 return dst, nil
101 }