Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
What's new
10
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
p2p
go-msgio
Commits
538b3e28
Commit
538b3e28
authored
Jun 06, 2019
by
Steven Allen
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
avoid allocating unless we need to
parent
b47fa43a
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
7 additions
and
16 deletions
+7
-16
varint.go
varint.go
+7
-16
No files found.
varint.go
View file @
538b3e28
...
...
@@ -12,8 +12,8 @@ import (
type
varintWriter
struct
{
W
io
.
Writer
lbuf
[]
byte
// for encoding varints
lock
sync
.
Locker
// for threadsafe writes
lbuf
[
binary
.
MaxVarintLen64
]
byte
// for encoding varints
lock
sync
.
Mutex
// for threadsafe writes
}
// NewVarintWriter wraps an io.Writer with a varint msgio framed writer.
...
...
@@ -21,9 +21,7 @@ type varintWriter struct {
// as a varint, using https://golang.org/pkg/encoding/binary/#PutUvarint
func
NewVarintWriter
(
w
io
.
Writer
)
WriteCloser
{
return
&
varintWriter
{
W
:
w
,
lbuf
:
make
([]
byte
,
binary
.
MaxVarintLen64
),
lock
:
new
(
sync
.
Mutex
),
W
:
w
,
}
}
...
...
@@ -40,7 +38,7 @@ func (s *varintWriter) WriteMsg(msg []byte) error {
defer
s
.
lock
.
Unlock
()
length
:=
uint64
(
len
(
msg
))
n
:=
binary
.
PutUvarint
(
s
.
lbuf
,
length
)
n
:=
binary
.
PutUvarint
(
s
.
lbuf
[
:
]
,
length
)
if
_
,
err
:=
s
.
W
.
Write
(
s
.
lbuf
[
:
n
]);
err
!=
nil
{
return
err
}
...
...
@@ -60,10 +58,9 @@ type varintReader struct {
R
io
.
Reader
br
io
.
ByteReader
// for reading varints.
lbuf
[]
byte
next
int
pool
*
pool
.
BufferPool
lock
sync
.
Locker
lock
sync
.
Mutex
max
int
// the maximal message size (in bytes) this reader handles
}
...
...
@@ -87,10 +84,8 @@ func NewVarintReaderWithPool(r io.Reader, p *pool.BufferPool) ReadCloser {
return
&
varintReader
{
R
:
r
,
br
:
&
simpleByteReader
{
R
:
r
},
lbuf
:
make
([]
byte
,
binary
.
MaxVarintLen64
),
next
:
-
1
,
pool
:
p
,
lock
:
new
(
sync
.
Mutex
),
max
:
defaultMaxSize
,
}
}
...
...
@@ -168,15 +163,11 @@ func (s *varintReader) Close() error {
type
simpleByteReader
struct
{
R
io
.
Reader
buf
[]
byte
buf
[
1
]
byte
}
func
(
r
*
simpleByteReader
)
ReadByte
()
(
c
byte
,
err
error
)
{
if
r
.
buf
==
nil
{
r
.
buf
=
make
([]
byte
,
1
)
}
if
_
,
err
:=
io
.
ReadFull
(
r
.
R
,
r
.
buf
);
err
!=
nil
{
if
_
,
err
:=
io
.
ReadFull
(
r
.
R
,
r
.
buf
[
:
]);
err
!=
nil
{
return
0
,
err
}
return
r
.
buf
[
0
],
nil
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment