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