Skip to content

Instantly share code, notes, and snippets.

@kjk
Created June 19, 2025 10:57
Show Gist options
  • Save kjk/99a7b41236dfcf76d9407a94b4b8dce1 to your computer and use it in GitHub Desktop.
Save kjk/99a7b41236dfcf76d9407a94b4b8dce1 to your computer and use it in GitHub Desktop.
sketch for fast str to WCHAR conversion
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"sync/atomic"
)
// general purpose function that tries fast conversion into provided bufOut
// if bufOut too small or nil, it allocates a buffer
// returns a slice of the buffer with the result
func ToWcharBuf(s string, bufOut []uint16) []uint16 {
// do the conversion
return bufOut
}
var (
reusableBufTaken int32
reusableBuf []uint16
)
func ToWcharReusableBuf(s string) ([]uint16, bool) {
// grab the buffer if available
// if 0 (not taken) swap with 1 (taken)
// returns true if swapped i.e. was not taken and we did take it
weTookIt := atomic.CompareAndSwapInt32(&reusableBufTaken, 0, 1)
var buf []uint16
if weTookIt {
buf = reusableBuf
}
res := ToWcharBuf()
return buf, weTookIt
}
func ReleaseReusableBuf(release bool) {
if release {
atomic.Store(&reuasableBufTaken, 0)
}
}
func useBuf() {
ws, release := ToWcharReusableBuf(s)
// ... use ws
ReleaseReusableBuf(release)
}
func main() {
fmt.Println("Hello, 世界")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment