Make packetcache.Get use a caller-allocated buffer.

This commit is contained in:
Juliusz Chroboczek
2020-05-20 20:32:30 +02:00
parent a6ff98a313
commit f641e263f1
3 changed files with 26 additions and 16 deletions
+6 -5
View File
@@ -115,7 +115,7 @@ func (cache *Cache) Expect(n int) {
cache.expected += uint32(n)
}
func (cache *Cache) Get(seqno uint16) []byte {
func (cache *Cache) Get(seqno uint16, result []byte) uint16 {
cache.mu.Lock()
defer cache.mu.Unlock()
@@ -124,11 +124,12 @@ func (cache *Cache) Get(seqno uint16) []byte {
cache.entries[i].seqno != seqno {
continue
}
buf := make([]byte, cache.entries[i].length)
copy(buf, cache.entries[i].buf[:])
return buf
return uint16(copy(
result[:cache.entries[i].length],
cache.entries[i].buf[:]),
)
}
return nil
return 0
}
// Shift 17 bits out of the bitmap. Return a boolean indicating if any
+15 -7
View File
@@ -23,13 +23,20 @@ func TestCache(t *testing.T) {
cache.Store(13, buf1)
cache.Store(17, buf2)
if bytes.Compare(cache.Get(13), buf1) != 0 {
buf := make([]byte, BufSize)
l := cache.Get(13, buf)
if bytes.Compare(buf[:l], buf1) != 0 {
t.Errorf("Couldn't get 13")
}
if bytes.Compare(cache.Get(17), buf2) != 0 {
l = cache.Get(17, buf)
if bytes.Compare(buf[:l], buf2) != 0 {
t.Errorf("Couldn't get 17")
}
if cache.Get(42) != nil {
l = cache.Get(42, buf)
if l != 0 {
t.Errorf("Creation ex nihilo")
}
}
@@ -42,14 +49,15 @@ func TestCacheOverflow(t *testing.T) {
}
for i := 0; i < 32; i++ {
buf := cache.Get(uint16(i))
buf := make([]byte, BufSize)
l := cache.Get(uint16(i), buf)
if i < 16 {
if buf != nil {
if l > 0 {
t.Errorf("Creation ex nihilo: %v", i)
}
} else {
if len(buf) != 1 || buf[0] != uint8(i) {
t.Errorf("Expected [%v], got %v", i, buf)
if l != 1 || buf[0] != uint8(i) {
t.Errorf("Expected [%v], got %v", i, buf[:l])
}
}
}