Skip to content

Commit

Permalink
Improve the performance of creating null terminated byte strings
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacalz committed Mar 15, 2024
1 parent 7e0ca40 commit 06f189b
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 8 deletions.
2 changes: 1 addition & 1 deletion filechooser/open.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func OpenFile(parentWindow, title string, options *OpenFileOptions) ([]string, e
}

if options.CurrentFolder != "" {
data["current_folder"] = convert.ToNullTerminatedString(options.CurrentFolder)
data["current_folder"] = dbus.MakeVariant(convert.ToNullTerminated(options.CurrentFolder))
}

obj := conn.Object(apis.ObjectName, apis.ObjectPath)
Expand Down
4 changes: 2 additions & 2 deletions filechooser/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func SaveFile(parentWindow, title string, options *SaveFileOptions) ([]string, e
}

if options.CurrentFolder != "" {
data["current_folder"] = convert.ToNullTerminatedString(options.CurrentFolder)
data["current_folder"] = dbus.MakeVariant(convert.ToNullTerminated(options.CurrentFolder))
}

obj := conn.Object(apis.ObjectName, apis.ObjectPath)
Expand Down Expand Up @@ -76,7 +76,7 @@ func SaveFiles(parentWindow, title string, options *SaveFilesOptions) ([]string,
}

if options.CurrentFolder != "" {
data["current_folder"] = convert.ToNullTerminatedString(options.CurrentFolder)
data["current_folder"] = dbus.MakeVariant(convert.ToNullTerminated(options.CurrentFolder))
}

obj := conn.Object(apis.ObjectName, apis.ObjectPath)
Expand Down
10 changes: 5 additions & 5 deletions internal/convert/nullstr.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package convert

import "github.com/godbus/dbus/v5"

// ToNullTerminatedString connverts a regular string into a null terminated dbus variant string.
func ToNullTerminatedString(input string) dbus.Variant {
return dbus.MakeVariant([]byte(input + "\000"))
// ToNullTerminated connverts a regular string into a null terminated byte string.
func ToNullTerminated(input string) []byte {
terminated := make([]byte, len(input)+1)
copy(terminated, input)
return terminated
}
28 changes: 28 additions & 0 deletions internal/convert/nullstr_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package convert

import (
"bytes"
"testing"
)

func TestToNullTerminated(t *testing.T) {
input := "test"

got := ToNullTerminated(input)
expect := []byte{'t', 'e', 's', 't', '\000'}
if !bytes.Equal(got, expect) {
t.Fatalf("Got %v, expected %v", got, expect)
}
}

var benchResult []byte

func BenchmarkToNullTerminated(b *testing.B) {
var result []byte

for i := 0; i < b.N; i++ {
result = ToNullTerminated("long_input_string")
}

benchResult = result
}

0 comments on commit 06f189b

Please sign in to comment.