Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid heap allocations in Htonl #55

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this test? ListPackages is already tested above and this test doesn't seem to add any value for testing. BenchmarkXXX makes more sense.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely. Let me arrange that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 24028bb

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
Loading