gitee.com/quant1x/gox@v1.21.2/util/hashmap/hashmap.go (about)

     1  // Copyright (c) 2015, Emir Pasic. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package hashmap implements a map backed by a hash table.
     6  //
     7  // Elements are unordered in the map.
     8  //
     9  // Structure is not thread safe.
    10  //
    11  // Reference: http://en.wikipedia.org/wiki/Associative_array
    12  package hashmap
    13  
    14  import (
    15  	"fmt"
    16  	"gitee.com/quant1x/gox/util/internal"
    17  )
    18  
    19  func assertMapImplementation() {
    20  	var _ internal.Map = (*Map)(nil)
    21  }
    22  
    23  // Map holds the elements in go's native map
    24  type Map struct {
    25  	m map[interface{}]interface{}
    26  }
    27  
    28  // New instantiates a hash map.
    29  func New() *Map {
    30  	return &Map{m: make(map[interface{}]interface{})}
    31  }
    32  
    33  // Put inserts element into the map.
    34  func (m *Map) Put(key interface{}, value interface{}) {
    35  	m.m[key] = value
    36  }
    37  
    38  // Get searches the element in the map by key and returns its value or nil if key is not found in map.
    39  // Second return parameter is true if key was found, otherwise false.
    40  func (m *Map) Get(key interface{}) (value interface{}, found bool) {
    41  	value, found = m.m[key]
    42  	return
    43  }
    44  
    45  // Remove removes the element from the map by key.
    46  func (m *Map) Remove(key interface{}) {
    47  	delete(m.m, key)
    48  }
    49  
    50  // Empty returns true if map does not contain any elements
    51  func (m *Map) Empty() bool {
    52  	return m.Size() == 0
    53  }
    54  
    55  // Size returns number of elements in the map.
    56  func (m *Map) Size() int {
    57  	return len(m.m)
    58  }
    59  
    60  // Keys returns all keys (random order).
    61  func (m *Map) Keys() []interface{} {
    62  	keys := make([]interface{}, m.Size())
    63  	count := 0
    64  	for key := range m.m {
    65  		keys[count] = key
    66  		count++
    67  	}
    68  	return keys
    69  }
    70  
    71  // Values returns all values (random order).
    72  func (m *Map) Values() []interface{} {
    73  	values := make([]interface{}, m.Size())
    74  	count := 0
    75  	for _, value := range m.m {
    76  		values[count] = value
    77  		count++
    78  	}
    79  	return values
    80  }
    81  
    82  // Clear removes all elements from the map.
    83  func (m *Map) Clear() {
    84  	m.m = make(map[interface{}]interface{})
    85  }
    86  
    87  // String returns a string representation of container
    88  func (m *Map) String() string {
    89  	str := "HashMap\n"
    90  	str += fmt.Sprintf("%v", m.m)
    91  	return str
    92  }