Files
obitools4/pkg/obitax/inner.go

54 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-11-08 09:48:16 +01:00
package obitax
import (
"strings"
"sync"
)
2024-11-08 09:48:16 +01:00
// InnerString is a struct that holds a map of strings and a read-write lock for concurrent access.
// The index map is used to store key-value pairs of strings.
type InnerString struct {
2024-11-16 05:59:41 +01:00
index map[string]*string // Map to store string values
lock sync.RWMutex // Read-write lock for concurrent access
2024-11-08 09:48:16 +01:00
}
// NewInnerString creates a new instance of InnerString.
2024-11-16 05:59:41 +01:00
// It initializes the index map and prepares the lock for use.
2024-11-08 09:48:16 +01:00
func NewInnerString() *InnerString {
return &InnerString{
2024-11-14 19:10:23 +01:00
index: make(map[string]*string),
2024-11-08 09:48:16 +01:00
}
}
// Innerize stores the given value in the index map if it is not already present.
2024-11-16 05:59:41 +01:00
// It returns the pointer to the string associated with the key, which is either the newly stored value
2024-11-08 09:48:16 +01:00
// or the existing value if it was already present in the map.
//
// Parameters:
// - value: The string value to be stored in the index map.
//
// Returns:
2024-11-16 05:59:41 +01:00
// - A pointer to the string value associated with the key.
2024-11-14 19:10:23 +01:00
func (i *InnerString) Innerize(value string) *string {
2024-11-08 09:48:16 +01:00
i.lock.Lock()
defer i.lock.Unlock()
s, ok := i.index[value]
if !ok {
value = strings.Clone(value)
2024-11-14 19:10:23 +01:00
s = &value
i.index[value] = s
2024-11-08 09:48:16 +01:00
}
return s
}
2024-11-16 05:59:41 +01:00
// Slice returns a slice of strings containing all the values stored in the index map.
2024-11-08 09:48:16 +01:00
func (i *InnerString) Slice() []string {
rep := make([]string, len(i.index))
j := 0
for _, v := range i.index {
2024-11-14 19:10:23 +01:00
rep[j] = *v
2024-11-08 09:48:16 +01:00
j++
}
return rep
}