Debian Codegraph @

cms/bytesbuffer/bytesbuffer.go

raw symbols SCIP
1 package bytesbuffer
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "regexp"
8 )
9
10 type BytesBuffer struct {
11 Buffer *bytes.Buffer
12 }
13
14 func Str_to_hex(str string, prefix string) string {
15 dst := bytes.NewBufferString("")
16
17 slen := len(str)
18 for i := 0; i < slen; i++ {
19 dst.WriteString(fmt.Sprintf("%s%2X", prefix, ([]byte(str))[i]))
20 }
21
22 return dst.String()
23 }
24
25 func Hex_to_str(str string) (string, error) {
26 var tmp []byte = make([]byte, 2)
27
28 re := regexp.MustCompile("[^a-fA-F0-9]")
29 clean_str := re.ReplaceAllString(str, "")
30
31 src := bytes.NewBufferString(clean_str)
32 dst := bytes.NewBufferString("")
33
34 cnt := src.Len() / 2
35
36 for i := 0; i < cnt; i++ {
37 num := 0
38 _, err := src.Read(tmp)
39 if err != nil {
40 return "", err
41 }
42 fmt.Sscanf(string(tmp), "%X", &num)
43 dst.WriteByte(byte(num))
44 }
45
46 return dst.String(), nil
47
48 }
49
50 func NewBuffer(buf []byte) *BytesBuffer {
51 return &BytesBuffer{Buffer: bytes.NewBuffer(buf)}
52 }
53
54 func NewBufferString(s string) *BytesBuffer {
55 return &BytesBuffer{Buffer: bytes.NewBufferString(s)}
56 }
57
58 // \x31\x32\x33\x34 -> 1234
59 // %31%32%33%34 -> 1234
60 // 31323334 -> 1234
61 func (this *BytesBuffer) WriteByteString(byteStr string) error {
62 var tmp []byte = make([]byte, 2)
63
64 re := regexp.MustCompile("[^a-fA-F0-9]")
65 clean_str := re.ReplaceAllString(byteStr, "")
66
67 src := bytes.NewBufferString(clean_str)
68
69 cnt := src.Len() / 2
70
71 for i := 0; i < cnt; i++ {
72 num := 0
73 _, err := src.Read(tmp)
74 if err != nil {
75 return err
76 }
77 fmt.Sscanf(string(tmp), "%X", &num)
78 this.Buffer.WriteByte(byte(num))
79 }
80 return nil
81 }
82
83 // 1234 + prefix("%") -> %31%32%33%34
84 // 1234 + prefix("\x") -> \x31\x32\x33\x34
85 // 1234 + prefix("") -> 31323334
86 func (this *BytesBuffer) ByteString(prefix string) string {
87 slen := this.Buffer.Len()
88 dst := bytes.NewBufferString("")
89
90 for i := 0; i < slen; i++ {
91 c, _ := this.Buffer.ReadByte()
92 dst.WriteString(fmt.Sprintf("%s%02X", prefix, c))
93 }
94
95 return dst.String()
96 }
97
98 // Buffer will be empty after Write
99 func (this *BytesBuffer) WriteToByteString(w io.Writer, prefix string) (n int64, err error) {
100 slen := this.Buffer.Len()
101 dst := bytes.NewBufferString("")
102
103 for i := 0; i < slen; i++ {
104 c, _ := this.Buffer.ReadByte()
105 dst.WriteString(fmt.Sprintf("%s%02X", prefix, c))
106 }
107
108 return dst.WriteTo(w)
109 }