forked from pdfcpu/pdfcpu
/
asciiHexDecode.go
69 lines (51 loc) · 1.13 KB
/
asciiHexDecode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package filter
import (
"bytes"
"encoding/hex"
"io"
"io/ioutil"
"github.com/pkg/errors"
)
/////////////////
// ASCIIHexDecode
/////////////////
type asciiHexDecode struct {
baseFilter
}
// EOD represents the end of data marker.
const EOD = '>'
// Encode implements encoding for an ASCIIHexDecode filter.
func (f asciiHexDecode) Encode(r io.Reader) (*bytes.Buffer, error) {
p, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
dst := make([]byte, hex.EncodedLen(len(p)))
hex.Encode(dst, p)
// eod marker
dst = append(dst, EOD)
return bytes.NewBuffer(dst), nil
}
// Decode implements decoding for an ASCIIHexDecode filter.
func (f asciiHexDecode) Decode(r io.Reader) (*bytes.Buffer, error) {
p, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
// if no eod then err
if p[len(p)-1] != EOD {
return nil, errors.New("Decode: missing eod marker")
}
// remove eod,
p = p[:len(p)-1]
// if len == odd add "0"
if len(p)%2 == 1 {
p = append(p, '0')
}
dst := make([]byte, hex.DecodedLen(len(p)))
_, err = hex.Decode(dst, p)
if err != nil {
return nil, err
}
return bytes.NewBuffer(dst), nil
}