storage.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package transientstorageimpl
  2. //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
  3. import (
  4. "context"
  5. "github.com/v2fly/v2ray-core/v5/features/extension/storage"
  6. "strings"
  7. "sync"
  8. )
  9. func NewScopedTransientStorageImpl() storage.ScopedTransientStorage {
  10. return &scopedTransientStorageImpl{scopes: map[string]storage.ScopedTransientStorage{}, values: map[string]interface{}{}}
  11. }
  12. type scopedTransientStorageImpl struct {
  13. access sync.Mutex
  14. scopes map[string]storage.ScopedTransientStorage
  15. values map[string]interface{}
  16. }
  17. func (s *scopedTransientStorageImpl) ScopedTransientStorage() {
  18. panic("implement me")
  19. }
  20. func (s *scopedTransientStorageImpl) Put(ctx context.Context, key string, value interface{}) error {
  21. s.access.Lock()
  22. defer s.access.Unlock()
  23. s.values[key] = value
  24. return nil
  25. }
  26. func (s *scopedTransientStorageImpl) Get(ctx context.Context, key string) (interface{}, error) {
  27. s.access.Lock()
  28. defer s.access.Unlock()
  29. sw, ok := s.values[key]
  30. if !ok {
  31. return nil, newError("unable to find ")
  32. }
  33. return sw, nil
  34. }
  35. func (s *scopedTransientStorageImpl) List(ctx context.Context, keyPrefix string) ([]string, error) {
  36. s.access.Lock()
  37. defer s.access.Unlock()
  38. var ret []string
  39. for key, _ := range s.values {
  40. if strings.HasPrefix(key, keyPrefix) {
  41. ret = append(ret, key)
  42. }
  43. }
  44. return ret, nil
  45. }
  46. func (s *scopedTransientStorageImpl) Clear(ctx context.Context) {
  47. s.access.Lock()
  48. defer s.access.Unlock()
  49. s.values = map[string]interface{}{}
  50. }
  51. func (s *scopedTransientStorageImpl) NarrowScope(ctx context.Context, key string) (storage.ScopedTransientStorage, error) {
  52. s.access.Lock()
  53. defer s.access.Unlock()
  54. sw, ok := s.scopes[key]
  55. if !ok {
  56. scope := NewScopedTransientStorageImpl()
  57. s.scopes[key] = scope
  58. return scope, nil
  59. }
  60. return sw, nil
  61. }
  62. func (s *scopedTransientStorageImpl) DropScope(ctx context.Context, key string) error {
  63. s.access.Lock()
  64. defer s.access.Unlock()
  65. delete(s.scopes, key)
  66. return nil
  67. }