diff --git a/encode.go b/encode.go index de3cf83..8ac2432 100644 --- a/encode.go +++ b/encode.go @@ -2,13 +2,14 @@ package hnsw import ( "bufio" + "bytes" "cmp" "encoding/binary" "fmt" "io" "os" - "github.com/google/renameio" + "github.com/natefinch/atomic" ) // errorEncoder is a helper type to encode multiple values @@ -301,14 +302,11 @@ func LoadSavedGraph[K cmp.Ordered](path string) (*SavedGraph[K], error) { // Save writes the graph to the file. func (g *SavedGraph[K]) Save() error { - tmp, err := renameio.TempFile("", g.Path) - if err != nil { - return err - } - defer tmp.Cleanup() - - wr := bufio.NewWriter(tmp) - err = g.Export(wr) + // Create a buffer to write the data + var buf bytes.Buffer + wr := bufio.NewWriter(&buf) + + err := g.Export(wr) if err != nil { return fmt.Errorf("exporting: %w", err) } @@ -318,9 +316,10 @@ func (g *SavedGraph[K]) Save() error { return fmt.Errorf("flushing: %w", err) } - err = tmp.CloseAtomicallyReplace() + // Use atomic.WriteFile to write the buffer contents atomically + err = atomic.WriteFile(g.Path, &buf) if err != nil { - return fmt.Errorf("closing atomically: %w", err) + return fmt.Errorf("writing atomically: %w", err) } return nil diff --git a/go.mod b/go.mod index 9d0d0f6..c308574 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,11 @@ module github.com/coder/hnsw go 1.21.4 require ( + github.com/chewxy/math32 v1.10.1 // indirect + github.com/natefinch/atomic v1.0.1 // indirect + github.com/viterin/partial v1.1.0 // indirect + github.com/viterin/vek v0.4.2 // indirect + golang.org/x/sys v0.11.0 // indirect github.com/google/renameio v1.0.1 github.com/stretchr/testify v1.9.0 ) diff --git a/go.sum b/go.sum index f74eb2b..97bcb84 100644 --- a/go.sum +++ b/go.sum @@ -5,6 +5,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/renameio v1.0.1 h1:Lh/jXZmvZxb0BBeSY5VKEfidcbcbenKjZFzM/q0fSeU= github.com/google/renameio v1.0.1/go.mod h1:t/HQoYBZSsWSNK35C6CO/TpPLDVWvxOHboWUAweKUpk= +github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A= +github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=