File: bytesbuffer.go

package info (click to toggle)
golang-github-denverdino-aliyungo 0.0~git20180921.13fa8aa-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,824 kB
  • sloc: xml: 1,359; makefile: 3
file content (109 lines) | stat: -rw-r--r-- 2,249 bytes parent folder | download | duplicates (3)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package bytesbuffer

import (
	"bytes"
	"fmt"
	"io"
	"regexp"
)

type BytesBuffer struct {
	Buffer *bytes.Buffer
}

func Str_to_hex(str string, prefix string) string {
	dst := bytes.NewBufferString("")

	slen := len(str)
	for i := 0; i < slen; i++ {
		dst.WriteString(fmt.Sprintf("%s%2X", prefix, ([]byte(str))[i]))
	}

	return dst.String()
}

func Hex_to_str(str string) (string, error) {
	var tmp []byte = make([]byte, 2)

	re := regexp.MustCompile("[^a-fA-F0-9]")
	clean_str := re.ReplaceAllString(str, "")

	src := bytes.NewBufferString(clean_str)
	dst := bytes.NewBufferString("")

	cnt := src.Len() / 2

	for i := 0; i < cnt; i++ {
		num := 0
		_, err := src.Read(tmp)
		if err != nil {
			return "", err
		}
		fmt.Sscanf(string(tmp), "%X", &num)
		dst.WriteByte(byte(num))
	}

	return dst.String(), nil

}

func NewBuffer(buf []byte) *BytesBuffer {
	return &BytesBuffer{Buffer: bytes.NewBuffer(buf)}
}

func NewBufferString(s string) *BytesBuffer {
	return &BytesBuffer{Buffer: bytes.NewBufferString(s)}
}

// \x31\x32\x33\x34	-> 1234
// %31%32%33%34		-> 1234
// 31323334			-> 1234
func (this *BytesBuffer) WriteByteString(byteStr string) error {
	var tmp []byte = make([]byte, 2)

	re := regexp.MustCompile("[^a-fA-F0-9]")
	clean_str := re.ReplaceAllString(byteStr, "")

	src := bytes.NewBufferString(clean_str)

	cnt := src.Len() / 2

	for i := 0; i < cnt; i++ {
		num := 0
		_, err := src.Read(tmp)
		if err != nil {
			return err
		}
		fmt.Sscanf(string(tmp), "%X", &num)
		this.Buffer.WriteByte(byte(num))
	}
	return nil
}

// 1234 + prefix("%")	-> %31%32%33%34
// 1234 + prefix("\x")	-> \x31\x32\x33\x34
// 1234 + prefix("")	-> 31323334
func (this *BytesBuffer) ByteString(prefix string) string {
	slen := this.Buffer.Len()
	dst := bytes.NewBufferString("")

	for i := 0; i < slen; i++ {
		c, _ := this.Buffer.ReadByte()
		dst.WriteString(fmt.Sprintf("%s%02X", prefix, c))
	}

	return dst.String()
}

// Buffer will be empty after Write
func (this *BytesBuffer) WriteToByteString(w io.Writer, prefix string) (n int64, err error) {
	slen := this.Buffer.Len()
	dst := bytes.NewBufferString("")

	for i := 0; i < slen; i++ {
		c, _ := this.Buffer.ReadByte()
		dst.WriteString(fmt.Sprintf("%s%02X", prefix, c))
	}

	return dst.WriteTo(w)
}