github.com/greenpau/go-authcrunch@v1.1.4/pkg/shared/shared.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 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 package shared 16 17 import ( 18 "fmt" 19 "sync" 20 ) 21 22 var ( 23 // Buffer is a key-value store. 24 Buffer *buffer 25 ) 26 27 func init() { 28 Buffer = newBuffer() 29 } 30 31 type buffer struct { 32 mu sync.RWMutex 33 Entries map[string]string 34 } 35 36 func newBuffer() *buffer { 37 c := &buffer{ 38 Entries: make(map[string]string), 39 } 40 return c 41 } 42 43 // Add adds a serialized key to the buffer. 44 func (c *buffer) Add(k, v string) error { 45 if k == "" || v == "" { 46 return fmt.Errorf("invalid input") 47 } 48 c.mu.Lock() 49 defer c.mu.Unlock() 50 if _, exists := c.Entries[k]; exists { 51 return fmt.Errorf("not empty") 52 } 53 c.Entries[k] = v 54 return nil 55 } 56 57 // Get returns a serialized key from the stash. 58 func (c *buffer) Get(k string) (string, error) { 59 c.mu.Lock() 60 defer c.mu.Unlock() 61 if v, exists := c.Entries[k]; exists { 62 return v, nil 63 } 64 return "", fmt.Errorf("not found") 65 }