github.com/SDLMoe/hugo@v0.47.1/hugolib/orderedMap.go (about)

     1  // Copyright 2018 The Hugo Authors. All rights reserved.
     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  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package hugolib
    15  
    16  import (
    17  	"fmt"
    18  	"sync"
    19  )
    20  
    21  type orderedMap struct {
    22  	sync.RWMutex
    23  	keys []interface{}
    24  	m    map[interface{}]interface{}
    25  }
    26  
    27  func newOrderedMap() *orderedMap {
    28  	return &orderedMap{m: make(map[interface{}]interface{})}
    29  }
    30  
    31  func newOrderedMapFromStringMapString(m map[string]string) *orderedMap {
    32  	om := newOrderedMap()
    33  	for k, v := range m {
    34  		om.Add(k, v)
    35  	}
    36  	return om
    37  }
    38  
    39  func (m *orderedMap) Add(k, v interface{}) {
    40  	m.Lock()
    41  	defer m.Unlock()
    42  	_, found := m.m[k]
    43  	if found {
    44  		panic(fmt.Sprintf("%v already added", v))
    45  	}
    46  	m.m[k] = v
    47  	m.keys = append(m.keys, k)
    48  }
    49  
    50  func (m *orderedMap) Get(k interface{}) (interface{}, bool) {
    51  	m.RLock()
    52  	defer m.RUnlock()
    53  	v, found := m.m[k]
    54  	return v, found
    55  }
    56  
    57  func (m *orderedMap) Contains(k interface{}) bool {
    58  	m.RLock()
    59  	defer m.RUnlock()
    60  	_, found := m.m[k]
    61  	return found
    62  }
    63  
    64  func (m *orderedMap) Keys() []interface{} {
    65  	m.RLock()
    66  	defer m.RUnlock()
    67  	return m.keys
    68  }
    69  
    70  func (m *orderedMap) Len() int {
    71  	m.RLock()
    72  	defer m.RUnlock()
    73  	return len(m.keys)
    74  }
    75  
    76  // Some shortcuts for known types.
    77  func (m *orderedMap) getShortcode(k interface{}) *shortcode {
    78  	v, found := m.Get(k)
    79  	if !found {
    80  		return nil
    81  	}
    82  	return v.(*shortcode)
    83  }
    84  
    85  func (m *orderedMap) getShortcodeRenderer(k interface{}) func() (string, error) {
    86  	v, found := m.Get(k)
    87  	if !found {
    88  		return nil
    89  	}
    90  	return v.(func() (string, error))
    91  }
    92  
    93  func (m *orderedMap) getString(k interface{}) string {
    94  	v, found := m.Get(k)
    95  	if !found {
    96  		return ""
    97  	}
    98  	return v.(string)
    99  }