| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package topologyv1 |
| 4 | |
| 5 | type StringDictionary struct { |
| 6 | values []string |
| 7 | index map[string]int |
| 8 | } |
| 9 | |
| 10 | func NewStringDictionary(values ...string) *StringDictionary { |
| 11 | dict := &StringDictionary{ |
| 12 | index: make(map[string]int, len(values)), |
| 13 | } |
| 14 | for _, value := range values { |
| 15 | dict.Ref(value) |
| 16 | } |
| 17 | return dict |
| 18 | } |
| 19 | |
| 20 | func (dict *StringDictionary) Ref(value string) int { |
| 21 | if dict == nil { |
| 22 | panic("topologyv1.StringDictionary.Ref called on nil dictionary") |
| 23 | } |
| 24 | if dict.index == nil { |
| 25 | dict.index = make(map[string]int) |
| 26 | } |
| 27 | if index, ok := dict.index[value]; ok { |
| 28 | return index |
| 29 | } |
| 30 | index := len(dict.values) |
| 31 | dict.values = append(dict.values, value) |
| 32 | dict.index[value] = index |
| 33 | return index |
| 34 | } |
| 35 | |
| 36 | func (dict *StringDictionary) Values() []any { |
| 37 | if dict == nil || len(dict.values) == 0 { |
| 38 | return []any{} |
| 39 | } |
| 40 | values := make([]any, len(dict.values)) |
| 41 | for index, value := range dict.values { |
| 42 | values[index] = value |
| 43 | } |
| 44 | return values |
| 45 | } |