summaryrefslogtreecommitdiff
path: root/internal/iorw/iorw.go
blob: a91a5b29c849eb17567da6fba3e9d0f9f215cf89 (plain)
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
package iorw

import (
	"encoding/binary"
	"io"
)

func WriteStr(w io.Writer, message string) error {
	messageBytes := []byte(message)
	sizeBytes := make([]byte, 8)
	binary.BigEndian.PutUint64(sizeBytes, uint64(len(messageBytes)))

	if _, err := w.Write(sizeBytes); err != nil {
		return err
	}
	if _, err := w.Write(messageBytes); err != nil {
		return err
	}

	return nil
}

func ReadStr(r io.Reader) (string, error) {
	sizeBytes := make([]byte, 8)
	if _, err := io.ReadFull(r, sizeBytes); err != nil {
		return "", err
	}
	messageSize := binary.BigEndian.Uint64(sizeBytes)

	messageBytes := make([]byte, messageSize)
	if _, err := io.ReadFull(r, messageBytes); err != nil {
		return "", err
	}

	return string(messageBytes), nil
}