Add "len" methods to encode and decode
Some checks failed
Benchmark BufferPool / RunBenchmarks (push) Failing after 18s
Run Tests / Test (push) Failing after 16s

To get length of encoded/decoded string
This commit is contained in:
2024-07-30 22:45:56 +02:00
parent db61da9fc2
commit b2a588e667
2 changed files with 82 additions and 11 deletions

View File

@@ -3,10 +3,15 @@ package encoding
import (
"bytes"
"fmt"
"log"
)
type GSM7Coder struct{}
// Make sure buffer can fit EncodesInto bytes
// Otherwise Encode will allocate memory as it sees fit
// Which is fine but not optimal
// Preallocate the buffer with the size of EncodesInto bytes
func (c *GSM7Coder) Encode(s string, buf *bytes.Buffer) error {
// utf8 := *(*[]byte)(unsafe.Pointer(&s))
utf8 := []byte(s)
@@ -15,10 +20,6 @@ func (c *GSM7Coder) Encode(s string, buf *bytes.Buffer) error {
bitshift byte = 0
leap, shift bool
)
tbw := len(utf8) * 7 / 8
if buf.Available() < tbw {
buf.Grow(tbw)
}
for index, septet := range utf8 {
if septet > 0b01111111 {
@@ -62,17 +63,18 @@ func (c *GSM7Coder) Encode(s string, buf *bytes.Buffer) error {
offset = 1
}
}
log.Println(buf.Cap(), buf.Len())
return nil
}
func (c *GSM7Coder) Decode(buf *bytes.Buffer) (string, error) {
gsm7 := buf.Bytes()
var (
offset int = (len(gsm7) / 8) + 1
bitshift byte = 0
offset int = (len(gsm7) / 8) + 1
bitshift byte = 0
leap, shift bool
)
outLength := len(gsm7)*8/7
outLength := DecodesInto(buf)
lengthDiff := outLength - len(gsm7)
gsm7 = append(gsm7, make([]byte, lengthDiff)...)
@@ -130,7 +132,7 @@ func (c *GSM7Coder) Decode(buf *bytes.Buffer) (string, error) {
}
// log.Printf("Result: %+v", gsm7)
// for _, v := range gsm7 {
// log.Printf("%08b", v)
// log.Printf("%08b", v)
// }
return string(gsm7), nil
}
@@ -138,6 +140,20 @@ func (c *GSM7Coder) Decode(buf *bytes.Buffer) (string, error) {
// Allocation free
// Which means data MUST have space for value
func InsertAt(data *[]byte, index int, value byte) {
copy((*data)[index+1:], (*data)[index:])
(*data)[index] = value
copy((*data)[index+1:], (*data)[index:])
(*data)[index] = value
}
func EncodesInto(s *string) int {
slen := len(*s)
enclen := slen * 7 / 8
if slen%8 != 0 {
enclen++
}
return enclen
}
func DecodesInto(buf *bytes.Buffer) int {
blen := buf.Len()
declen := blen * 8 / 7
return declen
}