1
0
Fork 0
mirror of https://github.com/mautrix/signal.git synced 2026-05-15 05:36:53 -04:00
mautrix-signal/pkg/libsignalgo/storeutil.go

77 lines
2.1 KiB
Go
Raw Permalink Normal View History

2023-12-17 15:54:35 +02:00
// mautrix-signal - A Matrix-signal puppeting bridge.
// Copyright (C) 2023 Sumner Evans
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package libsignalgo
/*
#include "./libsignal-ffi.h"
*/
import "C"
import (
"context"
2024-01-04 01:06:45 +02:00
"errors"
"unsafe"
gopointer "github.com/mattn/go-pointer"
)
2024-01-04 01:06:45 +02:00
type WrappedStore[T any] struct {
Store T
Ctx *CallbackContext
}
2024-01-04 01:06:45 +02:00
type CallbackContext struct {
Error error
Ctx context.Context
Unrefs []unsafe.Pointer
}
func NewCallbackContext(ctx context.Context) *CallbackContext {
2024-01-04 01:06:45 +02:00
if ctx == nil {
panic(errors.New("nil context passed to NewCallbackContext"))
}
return &CallbackContext{Ctx: ctx}
}
2024-01-04 01:06:45 +02:00
func (ctx *CallbackContext) Unref() {
for _, ptr := range ctx.Unrefs {
gopointer.Unref(ptr)
2024-01-04 01:06:45 +02:00
}
}
func wrapStore[T any](ctx *CallbackContext, store T) unsafe.Pointer {
wrappedStore := gopointer.Save(&WrappedStore[T]{Store: store, Ctx: ctx})
2024-01-04 01:06:45 +02:00
ctx.Unrefs = append(ctx.Unrefs, wrappedStore)
return wrappedStore
}
func wrapStoreCallbackCustomReturn[T any](storeCtx unsafe.Pointer, callback func(store T, ctx context.Context) (int, error)) C.int {
wrap := gopointer.Restore(storeCtx).(*WrappedStore[T])
2024-01-04 01:06:45 +02:00
retVal, err := callback(wrap.Store, wrap.Ctx.Ctx)
if err != nil {
wrap.Ctx.Error = err
}
2024-01-04 01:06:45 +02:00
return C.int(retVal)
}
func wrapStoreCallback[T any](storeCtx unsafe.Pointer, callback func(store T, ctx context.Context) error) C.int {
wrap := gopointer.Restore(storeCtx).(*WrappedStore[T])
2024-01-04 01:06:45 +02:00
if err := callback(wrap.Store, wrap.Ctx.Ctx); err != nil {
wrap.Ctx.Error = err
return -1
}
return 0
}