github.com/Jeffail/benthos/v3@v3.65.0/lib/message/metadata/lazy_copy.go (about) 1 package metadata 2 3 import ( 4 "github.com/Jeffail/benthos/v3/lib/types" 5 ) 6 7 //------------------------------------------------------------------------------ 8 9 // lazyCopy is a types.Metadata implementation that takes an existing metadata 10 // object and lazily returns its values. If a call is made to edit the contents 11 // of the metadata then a copy is made of the original before doing so. 12 type lazyCopy struct { 13 copied bool 14 m types.Metadata 15 } 16 17 func (l *lazyCopy) ensureCopied() { 18 if l.copied { 19 return 20 } 21 var newMap map[string]string 22 if t, ok := l.m.(*Type); ok { 23 newMap = make(map[string]string, len(t.m)) 24 } else { 25 newMap = map[string]string{} 26 } 27 l.m.Iter(func(k, v string) error { 28 newMap[k] = v 29 return nil 30 }) 31 l.m = New(newMap) 32 l.copied = true 33 } 34 35 // Get returns a metadata value if a key exists, otherwise an empty string. 36 func (l *lazyCopy) Get(key string) string { 37 return l.m.Get(key) 38 } 39 40 // Set sets the value of a metadata key. 41 func (l *lazyCopy) Set(key, value string) types.Metadata { 42 l.ensureCopied() 43 l.m.Set(key, value) 44 return l 45 } 46 47 // Delete removes the value of a metadata key. 48 func (l *lazyCopy) Delete(key string) types.Metadata { 49 l.ensureCopied() 50 l.m.Delete(key) 51 return l 52 } 53 54 // Iter iterates each metadata key/value pair. 55 func (l *lazyCopy) Iter(f func(k, v string) error) error { 56 return l.m.Iter(f) 57 } 58 59 // Copy returns a copy of the metadata object that can be edited without 60 // changing the contents of the original. 61 func (l *lazyCopy) Copy() types.Metadata { 62 return l.m.Copy() 63 } 64 65 //------------------------------------------------------------------------------ 66 67 // LazyCopy takes an existing metadata object and returns a new implementation 68 // that lazily returns its values. If a call is made to edit the contents of the 69 // metadata then a copy is made of the original before doing so. 70 func LazyCopy(m types.Metadata) types.Metadata { 71 return &lazyCopy{ 72 m: m, 73 } 74 } 75 76 //------------------------------------------------------------------------------