WIP: adding randommessage package for generating test data

This commit is contained in:
2025-05-16 07:14:56 +10:00
parent 169e0539f6
commit 06d39158a5
3 changed files with 109 additions and 2 deletions

View File

@@ -0,0 +1,100 @@
package randommessage
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import (
"crypto/rand"
"encoding/binary"
"errors"
"hash"
"io"
"golang.org/x/crypto/blake2s"
)
type StreamReader struct {
pos int64
size int64
hashEngine hash.Hash
}
var (
ErrInvalidBufSize = errors.New("invalid buffer size")
)
func NewStreamReader(size int64) (*StreamReader, error) {
var (
h hash.Hash
err error
)
if h, err = blake2s.New256(nil); err != nil {
return nil, err
}
return &StreamReader{
pos: 0,
size: size,
hashEngine: h,
}, nil
}
func (s *StreamReader) Read(buf []byte) (int, error) {
var (
n int
err error
)
if s.pos == 0 {
if len(buf) < 4 {
return 0, ErrInvalidBufSize
}
binary.BigEndian.PutUint32(buf, uint32(s.size))
n, err = s.read(buf[4:])
n += 4
} else {
n, err = s.read(buf)
}
return n, err
}
func (s *StreamReader) read(buf []byte) (int, error) {
var (
n int
limit int
err error
)
limit = len(buf)
err = nil
if s.size-s.pos < int64(len(buf)) {
err = io.EOF
limit = int(s.size - s.pos)
if limit < 0 {
panic("unexpected limit")
}
}
if limit > 0 {
n, _ = rand.Read(buf[:limit])
s.pos += int64(limit)
s.hashEngine.Write(buf[:limit])
}
return n, err
}