github.com/chain5j/chain5j-pkg@v1.0.7/collection/maps/hashmap/hashmap.go (about)

     1  // Package hashmap
     2  //
     3  // @author: xwc1125
     4  package hashmap
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"reflect"
    10  	"sort"
    11  	"sync"
    12  
    13  	"github.com/chain5j/chain5j-pkg/codec"
    14  	"github.com/chain5j/chain5j-pkg/util/reflectutil"
    15  )
    16  
    17  // HashMap ...
    18  type HashMap struct {
    19  	data   map[string]interface{} // 数据
    20  	val    interface{}            // 同类型的map类型
    21  	m      sync.Mutex             // 锁
    22  	isSafe bool                   // 是否安全
    23  }
    24  
    25  func (m *HashMap) lock() {
    26  	if m.isSafe {
    27  		m.m.Lock()
    28  	}
    29  }
    30  
    31  func (m *HashMap) unlock() {
    32  	if m.isSafe {
    33  		m.m.Unlock()
    34  	}
    35  }
    36  
    37  // NewHashMap ...
    38  func NewHashMap(isSafe bool) *HashMap {
    39  	return &HashMap{
    40  		data:   make(map[string]interface{}),
    41  		isSafe: isSafe,
    42  	}
    43  }
    44  
    45  func NewHashMapSame(isSafe bool, val interface{}) *HashMap {
    46  	h := NewHashMap(isSafe)
    47  	if val != nil {
    48  		h.val = val
    49  	}
    50  	return h
    51  }
    52  
    53  func NewHashMapFill(val interface{}) *HashMap {
    54  	valueOf := reflect.ValueOf(val)
    55  	if valueOf.Kind() == reflect.Map {
    56  		// elem := valueOf.Elem()
    57  		// fmt.Println(elem)
    58  		_, err := Get(val, []interface{}{})
    59  		if err != nil {
    60  			fmt.Println(err)
    61  		}
    62  		m := valueOf.Interface().(map[string]interface{})
    63  		fmt.Println(m)
    64  	}
    65  	fmt.Println(valueOf.Kind().String())
    66  	h := &HashMap{
    67  		data: val.(map[string]interface{}),
    68  	}
    69  	return h
    70  }
    71  
    72  func GetMapI(v interface{}, path ...interface{}) (map[interface{}]interface{}, error) {
    73  	v, err := Get(v, path...)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	m, ok := v.(map[interface{}]interface{})
    78  	if !ok {
    79  		return nil, fmt.Errorf("expected map with interface keys node, got: %T", v)
    80  	}
    81  	return m, nil
    82  }
    83  
    84  // GetMapS returns a map with string keys denoted by the path.
    85  //
    86  // If path is empty or nil, v is returned as a slice.
    87  func GetMapS(v interface{}, path ...interface{}) (map[string]interface{}, error) {
    88  	v, err := Get(v, path...)
    89  	if err != nil {
    90  		return nil, err
    91  	}
    92  	m, ok := v.(map[string]interface{})
    93  	if !ok {
    94  		return nil, fmt.Errorf("expected map with string keys node, got: %T", v)
    95  	}
    96  	return m, nil
    97  }
    98  
    99  func Get(v interface{}, path ...interface{}) (interface{}, error) {
   100  	for i, el := range path {
   101  		switch node := v.(type) {
   102  		case map[string]interface{}:
   103  			key, ok := el.(string)
   104  			if !ok {
   105  				return nil, fmt.Errorf("expected string path element, got: %T (path element idx: %d)", el, i)
   106  			}
   107  			v, ok = node[key]
   108  			if !ok {
   109  				return nil, fmt.Errorf("missing key: %s (path element idx: %d)", key, i)
   110  			}
   111  
   112  		case map[interface{}]interface{}:
   113  			var ok bool
   114  			v, ok = node[el]
   115  			if !ok {
   116  				return nil, fmt.Errorf("missing key: %v (path element idx: %d)", el, i)
   117  			}
   118  
   119  		case []interface{}:
   120  			idx, ok := el.(int)
   121  			if !ok {
   122  				return nil, fmt.Errorf("expected int path element, got: %T (path element idx: %d)", el, i)
   123  			}
   124  			if idx < 0 || idx >= len(node) {
   125  				return nil, fmt.Errorf("index out of range: %d (path element idx: %d)", idx, i)
   126  			}
   127  			v = node[idx]
   128  
   129  		default:
   130  			return nil, fmt.Errorf("expected map or slice node, got: %T (path element idx: %d)", node, i)
   131  		}
   132  	}
   133  
   134  	return v, nil
   135  }
   136  
   137  // SetSafe 设置为是否安全
   138  func (m *HashMap) SetSafe(isSafe bool) {
   139  	m.lock()
   140  	m.isSafe = isSafe
   141  	m.unlock()
   142  }
   143  
   144  // Put 增加或者修改一个元素
   145  func (m *HashMap) Put(k string, v interface{}) {
   146  	m.lock()
   147  	m.data[k] = v
   148  	m.unlock()
   149  }
   150  
   151  // Get ...
   152  // @obj: 值对象
   153  // @objType: 值类型
   154  // @isExist: 是否存在
   155  func (m *HashMap) Get(k string) (obj interface{}, objType string, isExist bool) {
   156  	m.lock()
   157  	v, ok := m.data[k]
   158  	m.unlock()
   159  	var rv interface{} = nil
   160  	var rt = ""
   161  	if ok {
   162  		rv = v
   163  		rt = reflect.TypeOf(v).String()
   164  	}
   165  	return rv, rt, ok
   166  }
   167  
   168  // GetObj ...
   169  func (m *HashMap) GetObj(k string) (obj interface{}) {
   170  	m.lock()
   171  	v, ok := m.data[k]
   172  	m.unlock()
   173  	var rv interface{} = nil
   174  	if ok {
   175  		rv = v
   176  	}
   177  	return rv
   178  }
   179  
   180  // GetValue ...
   181  func (m *HashMap) GetValue(k string) reflect.Value {
   182  	m.lock()
   183  	v, ok := m.data[k]
   184  	m.unlock()
   185  	var rv interface{} = nil
   186  	var sv reflect.Value
   187  	if ok {
   188  		rv = v
   189  		sv = reflectutil.GetValue(rv)
   190  	}
   191  	return sv
   192  }
   193  
   194  // GetValues ...
   195  func (m *HashMap) GetValues(k string) []reflect.Value {
   196  	m.lock()
   197  	v, ok := m.data[k]
   198  	m.unlock()
   199  	var rv interface{} = nil
   200  	var sv []reflect.Value
   201  	if ok {
   202  		rv = v
   203  		sv = reflectutil.GetValues(rv)
   204  	}
   205  	return sv
   206  }
   207  
   208  // HasKey 判断是否包括key,如果包含key返回value的类型
   209  func (m *HashMap) HasKey(k string) (bool, string) {
   210  	m.lock()
   211  	v, ok := m.data[k]
   212  	m.unlock()
   213  	var rt = ""
   214  	if ok {
   215  		rt = reflect.TypeOf(v).String()
   216  	}
   217  	return ok, rt
   218  }
   219  
   220  // Exist ...
   221  func (m *HashMap) Exist(k string) bool {
   222  	m.lock()
   223  	_, ok := m.data[k]
   224  	m.unlock()
   225  	return ok
   226  }
   227  
   228  // Remove 移除一个元素
   229  func (m *HashMap) Remove(k string) (interface{}, bool) {
   230  	m.lock()
   231  	v, ok := m.data[k]
   232  	var rv interface{} = nil
   233  	if ok {
   234  		rv = v
   235  		delete(m.data, k)
   236  	}
   237  	m.unlock()
   238  	return rv, ok
   239  }
   240  
   241  // ForEach 复制map用于外部遍历
   242  func (m *HashMap) ForEach() map[string]interface{} {
   243  	m.lock()
   244  	mb := map[string]interface{}{}
   245  	for k, v := range m.data {
   246  		mb[k] = v
   247  	}
   248  	m.unlock()
   249  	return mb
   250  }
   251  
   252  // Size ...
   253  func (m *HashMap) Size() int {
   254  	return len(m.data)
   255  }
   256  
   257  // Sort 排序
   258  func (m *HashMap) Sort() []KV {
   259  	var kvs []KV
   260  	var keyArray []string
   261  	m.lock()
   262  	for k, _ := range m.data {
   263  		keyArray = append(keyArray, k)
   264  	}
   265  	sort.Strings(keyArray)
   266  	for _, v := range keyArray {
   267  		kv := &KV{
   268  			Key:   v,
   269  			Value: m.data[v],
   270  		}
   271  		kvs = append(kvs, *kv)
   272  	}
   273  	m.unlock()
   274  	return kvs
   275  }
   276  
   277  // String ...
   278  func (m *HashMap) String() string {
   279  	bytes, _ := json.Marshal(m.data)
   280  	return string(bytes)
   281  }
   282  
   283  func (m *HashMap) MarshalJSON() ([]byte, error) {
   284  	return json.Marshal(m.data)
   285  }
   286  
   287  func (m *HashMap) UnmarshalJSON(bytes []byte) error {
   288  	if m.data == nil {
   289  		m.data = make(map[string]interface{})
   290  		m.isSafe = true
   291  	}
   292  	return json.Unmarshal(bytes, &m.data)
   293  }
   294  
   295  func (m *HashMap) Decode(data []byte) error {
   296  	return codec.Codecor().Decode(data, &m)
   297  }