Files
sqlite3/internal/util/handle.go

76 lines
1.3 KiB
Go
Raw Normal View History

2023-06-30 01:52:18 +01:00
package util
import (
"context"
"io"
2023-07-11 12:30:09 +01:00
"github.com/tetratelabs/wazero/experimental"
2023-06-30 01:52:18 +01:00
)
type handleKey struct{}
type handleState struct {
handles []any
2023-07-04 11:16:29 +01:00
empty int
2023-06-30 01:52:18 +01:00
}
2023-07-11 12:30:09 +01:00
func NewContext(ctx context.Context) context.Context {
2023-06-30 01:52:18 +01:00
state := new(handleState)
2023-07-11 12:30:09 +01:00
ctx = experimental.WithCloseNotifier(ctx, state)
ctx = context.WithValue(ctx, handleKey{}, state)
return ctx
2023-06-30 01:52:18 +01:00
}
2023-07-11 12:30:09 +01:00
func (s *handleState) CloseNotify(ctx context.Context, exitCode uint32) {
2023-06-30 01:52:18 +01:00
for _, h := range s.handles {
if c, ok := h.(io.Closer); ok {
2023-07-11 12:30:09 +01:00
c.Close()
2023-06-30 01:52:18 +01:00
}
}
s.handles = nil
2023-07-04 11:16:29 +01:00
s.empty = 0
2023-06-30 01:52:18 +01:00
}
func GetHandle(ctx context.Context, id uint32) any {
2023-06-30 17:08:35 +01:00
if id == 0 {
2023-07-04 02:18:03 +01:00
return nil
2023-06-30 17:08:35 +01:00
}
2023-06-30 01:52:18 +01:00
s := ctx.Value(handleKey{}).(*handleState)
2023-06-30 17:08:35 +01:00
return s.handles[^id]
2023-06-30 01:52:18 +01:00
}
func DelHandle(ctx context.Context, id uint32) error {
2023-06-30 17:08:35 +01:00
if id == 0 {
return nil
}
2023-06-30 01:52:18 +01:00
s := ctx.Value(handleKey{}).(*handleState)
2023-06-30 17:08:35 +01:00
a := s.handles[^id]
s.handles[^id] = nil
2023-07-04 11:16:29 +01:00
s.empty++
2023-06-30 01:52:18 +01:00
if c, ok := a.(io.Closer); ok {
return c.Close()
}
return nil
}
func AddHandle(ctx context.Context, a any) (id uint32) {
2023-06-30 17:08:35 +01:00
if a == nil {
2023-07-03 17:21:35 +01:00
panic(NilErr)
2023-06-30 17:08:35 +01:00
}
2023-06-30 01:52:18 +01:00
s := ctx.Value(handleKey{}).(*handleState)
// Find an empty slot.
2023-07-04 11:16:29 +01:00
if s.empty > cap(s.handles)-len(s.handles) {
for id, h := range s.handles {
if h == nil {
s.empty--
s.handles[id] = a
return ^uint32(id)
}
2023-06-30 01:52:18 +01:00
}
}
// Add a new slot.
s.handles = append(s.handles, a)
2023-06-30 17:08:35 +01:00
return -uint32(len(s.handles))
2023-06-30 01:52:18 +01:00
}