github.com/opcr-io/oras-go/v2@v2.0.0-20231122155130-eb4260d8a0ae/internal/resolver/memory.go (about) 1 /* 2 Copyright The ORAS Authors. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package resolver 17 18 import ( 19 "context" 20 "sync" 21 22 "github.com/opcr-io/oras-go/v2/errdef" 23 ocispec "github.com/opencontainers/image-spec/specs-go/v1" 24 ) 25 26 // Memory is a memory based resolver. 27 type Memory struct { 28 index sync.Map // map[string]ocispec.Descriptor 29 } 30 31 // NewMemory creates a new Memory resolver. 32 func NewMemory() *Memory { 33 return &Memory{} 34 } 35 36 // Resolve resolves a reference to a descriptor. 37 func (m *Memory) Resolve(_ context.Context, reference string) (ocispec.Descriptor, error) { 38 desc, ok := m.index.Load(reference) 39 if !ok { 40 return ocispec.Descriptor{}, errdef.ErrNotFound 41 } 42 return desc.(ocispec.Descriptor), nil 43 } 44 45 // Tag tags a descriptor with a reference string. 46 func (m *Memory) Tag(_ context.Context, desc ocispec.Descriptor, reference string) error { 47 m.index.Store(reference, desc) 48 return nil 49 } 50 51 // Delete removes a reference from index map. 52 func (m *Memory) Delete(reference string) { 53 m.index.Delete(reference) 54 } 55 56 // Map dumps the memory into a built-in map structure. 57 // Like other operations, calling Map() is go-routine safe. However, it does not 58 // necessarily correspond to any consistent snapshot of the storage contents. 59 func (m *Memory) Map() map[string]ocispec.Descriptor { 60 res := make(map[string]ocispec.Descriptor) 61 m.index.Range(func(key, value interface{}) bool { 62 res[key.(string)] = value.(ocispec.Descriptor) 63 return true 64 }) 65 return res 66 }