Files
sqlite3/internal/util/handle.go

71 lines
1.2 KiB
Go
Raw Normal View History

2023-06-30 01:52:18 +01:00
package util
import (
"context"
"io"
)
type handleState struct {
handles []any
holes int
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
s.holes = 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
}
s := ctx.Value(moduleKey{}).(*moduleState)
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
}
s := ctx.Value(moduleKey{}).(*moduleState)
2023-06-30 17:08:35 +01:00
a := s.handles[^id]
s.handles[^id] = nil
2024-09-30 13:11:04 +01:00
if l := uint32(len(s.handles)); l == ^id {
s.handles = s.handles[:l-1]
} else {
s.holes++
}
2023-06-30 01:52:18 +01:00
if c, ok := a.(io.Closer); ok {
return c.Close()
}
return nil
}
2024-09-30 13:11:04 +01:00
func AddHandle(ctx context.Context, a any) 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
}
2024-09-30 13:11:04 +01:00
s := ctx.Value(moduleKey{}).(*moduleState)
2023-06-30 01:52:18 +01:00
// Find an empty slot.
if s.holes > cap(s.handles)-len(s.handles) {
2023-07-04 11:16:29 +01:00
for id, h := range s.handles {
if h == nil {
s.holes--
2023-07-04 11:16:29 +01:00
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
}