github.com/pdfcpu/pdfcpu@v0.11.1/pkg/filter/asciiHexDecode.go (about) 1 /* 2 Copyright 2018 The pdfcpu Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package filter 18 19 import ( 20 "bytes" 21 "encoding/hex" 22 "io" 23 ) 24 25 type asciiHexDecode struct { 26 baseFilter 27 } 28 29 const eodHexDecode = '>' 30 31 // Encode implements encoding for an ASCIIHexDecode filter. 32 func (f asciiHexDecode) Encode(r io.Reader) (io.Reader, error) { 33 34 bb, err := getReaderBytes(r) 35 if err != nil { 36 return nil, err 37 } 38 39 dst := make([]byte, hex.EncodedLen(len(bb))) 40 hex.Encode(dst, bb) 41 42 // eod marker 43 dst = append(dst, eodHexDecode) 44 45 return bytes.NewBuffer(dst), nil 46 } 47 48 // Decode implements decoding for an ASCIIHexDecode filter. 49 func (f asciiHexDecode) Decode(r io.Reader) (io.Reader, error) { 50 return f.DecodeLength(r, -1) 51 } 52 53 func (f asciiHexDecode) DecodeLength(r io.Reader, maxLen int64) (io.Reader, error) { 54 bb, err := getReaderBytes(r) 55 if err != nil { 56 return nil, err 57 } 58 59 var p []byte 60 61 // Remove any white space and cut off on eod 62 for i := 0; i < len(bb); i++ { 63 if bb[i] == eodHexDecode { 64 break 65 } 66 if !bytes.ContainsRune([]byte{0x09, 0x0A, 0x0C, 0x0D, 0x20}, rune(bb[i])) { 67 p = append(p, bb[i]) 68 } 69 } 70 71 // if len == odd add "0" 72 if len(p)%2 == 1 { 73 p = append(p, '0') 74 } 75 76 if maxLen < 0 { 77 maxLen = int64(hex.DecodedLen(len(p))) 78 } 79 dst := make([]byte, maxLen) 80 81 if _, err := hex.Decode(dst, p[:maxLen*2]); err != nil { 82 return nil, err 83 } 84 85 return bytes.NewBuffer(dst), nil 86 }