You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
1.9 KiB
91 lines
1.9 KiB
3 years ago
|
package util
|
||
3 years ago
|
|
||
|
import (
|
||
3 years ago
|
"bytes"
|
||
3 years ago
|
"encoding/binary"
|
||
3 years ago
|
"fmt"
|
||
|
"io"
|
||
|
)
|
||
|
|
||
|
// Shortcut function to read n bytes from reader. Peeked from here: https://github.com/dhowden/tag/blob/master/util.go
|
||
3 years ago
|
func Read(rs io.Reader, n int) ([]byte, error) {
|
||
3 years ago
|
read := make([]byte, n)
|
||
|
_, err := rs.Read(read)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("could not read from reader: %s", err)
|
||
|
}
|
||
|
|
||
|
return read, nil
|
||
|
}
|
||
3 years ago
|
|
||
3 years ago
|
// Shortcut function to read n bytes and convert them into string.
|
||
|
// If encountered zero-byte - converts to string only previously read bytes
|
||
3 years ago
|
func ReadToString(rs io.Reader, n int) (string, error) {
|
||
3 years ago
|
read := make([]byte, n)
|
||
|
_, err := rs.Read(read)
|
||
|
if err != nil {
|
||
|
return "", fmt.Errorf("could not read from reader: %s", err)
|
||
|
}
|
||
3 years ago
|
|
||
|
var readString string
|
||
|
for _, b := range read {
|
||
|
if b == 0 {
|
||
|
break
|
||
|
}
|
||
|
readString += string(b)
|
||
|
}
|
||
|
|
||
|
return readString, nil
|
||
3 years ago
|
}
|
||
3 years ago
|
|
||
|
// Writes data to wr, if len(data) is less than lenNeeded - adds null bytes until written lenNeeded bytes
|
||
3 years ago
|
func WriteToExtent(wr io.Writer, data []byte, lenNeeded int) error {
|
||
3 years ago
|
if len(data) > lenNeeded {
|
||
|
return fmt.Errorf("length of given data bytes is bigger than length needed")
|
||
|
}
|
||
|
|
||
|
buff := new(bytes.Buffer)
|
||
|
for i := 0; i < lenNeeded; i++ {
|
||
|
if i < len(data) {
|
||
|
err := buff.WriteByte(data[i])
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
} else {
|
||
|
err := buff.WriteByte(0)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_, err := wr.Write(buff.Bytes())
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// Returns found key (int) in provided map by value (string);
|
||
|
// If key does not exist in map - returns -1
|
||
3 years ago
|
func GetKey(mp map[int]string, givenValue string) int {
|
||
3 years ago
|
for key, value := range mp {
|
||
|
if value == givenValue {
|
||
|
return key
|
||
|
}
|
||
|
}
|
||
|
return -1
|
||
|
}
|
||
3 years ago
|
|
||
|
// Decodes given integer bytes into integer
|
||
3 years ago
|
func BytesToInt(gBytes []byte) (int64, error) {
|
||
3 years ago
|
buff := bytes.NewBuffer(gBytes)
|
||
|
integer, err := binary.ReadVarint(buff)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
buff = nil
|
||
|
return integer, nil
|
||
|
}
|