Skip to content

Commit

Permalink
Avoid heap allocations in Htonl
Browse files Browse the repository at this point in the history
  • Loading branch information
jinroh committed Nov 21, 2024
1 parent facee9e commit d57d9a7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 24 deletions.
30 changes: 6 additions & 24 deletions pkg/inet.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,17 @@
package rpmdb

import (
"bytes"
"encoding/binary"
"log"
)

func Htonl(val int32) int32 {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.LittleEndian, val); err != nil {
log.Println(err)
return 0
}

if err := binary.Read(buf, binary.BigEndian, &val); err != nil {
log.Println(err)
return 0
}
return val
var buf [4]byte
binary.LittleEndian.PutUint32(buf[:], uint32(val))
return int32(binary.BigEndian.Uint32(buf[:]))
}

func HtonlU(val uint32) uint32 {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.LittleEndian, val); err != nil {
log.Println(err)
return 0
}

if err := binary.Read(buf, binary.BigEndian, &val); err != nil {
log.Println(err)
return 0
}
return val
var buf [4]byte
binary.LittleEndian.PutUint32(buf[:], val)
return binary.BigEndian.Uint32(buf[:])
}
11 changes: 11 additions & 0 deletions pkg/rpmdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,17 @@ func TestPackageList(t *testing.T) {
}
})
}

for _, tt := range tests {
allocs := testing.AllocsPerRun(10, func() {
db, err := Open(tt.file)
require.NoError(t, err)

_, err = db.ListPackages()
require.NoError(t, err)
})
t.Logf("Allocations per run %q: %f", tt.name, allocs)
}
}

func TestRpmDB_Package(t *testing.T) {
Expand Down

0 comments on commit d57d9a7

Please sign in to comment.