Example #1
0
File: ordmap.go Project: ngaut/ty
// Put has a parametric type:
//
//	func (om *OrdMap<K, V>) Put(key K, val V)
//
// Put adds or overwrites `key` into the map `om` with value `val`.
// If `key` already exists in the map, then its position in the ordering
// of the map is not changed.
func (om *OrdMap) Put(key, val interface{}) {
	rkey := ty.AssertType(key, om.ktype)
	rval := ty.AssertType(val, om.vtype)
	if !om.exists(rkey) {
		om.keys = reflect.Append(om.keys, rkey)
	}
	om.m.SetMapIndex(rkey, rval)
}
Example #2
0
File: ordmap.go Project: ngaut/ty
// TryGet has a parametric type:
//
//	func (om *OrdMap<K, V>) TryGet(key K) (V, bool)
//
// TryGet retrieves the value in the map `om` corresponding to `key` and
// reports whether the value exists in the map or not. If the value does
// not exist, then the zero value of `V` and `false` are returned.
func (om *OrdMap) TryGet(key interface{}) (interface{}, bool) {
	rkey := ty.AssertType(key, om.ktype)
	rval := om.m.MapIndex(rkey)
	if !rval.IsValid() {
		return om.zeroValue().Interface(), false
	}
	return rval.Interface(), true
}
Example #3
0
File: ordmap.go Project: ngaut/ty
// Get has a parametric type:
//
//	func (om *OrdMap<K, V>) Get(key K) V
//
// Get retrieves the value in the map `om` corresponding to `key`. If the
// value does not exist, then the zero value of type `V` is returned.
func (om *OrdMap) Get(key interface{}) interface{} {
	rkey := ty.AssertType(key, om.ktype)
	rval := om.m.MapIndex(rkey)
	if !rval.IsValid() {
		return om.zeroValue().Interface()
	}
	return rval.Interface()
}
Example #4
0
File: ordmap.go Project: ngaut/ty
// Delete has a parametric type:
//
//	func (om *OrdMap<K, V>) Delete(key K)
//
// Delete removes `key` from the map `om`.
//
// N.B. Delete is O(n) in the number of keys.
func (om *OrdMap) Delete(key interface{}) {
	rkey := ty.AssertType(key, om.ktype)

	// Avoid doing work if we don't need to.
	if !om.exists(rkey) {
		return
	}

	keysLen := om.keys.Len()
	for i := 0; i < keysLen; i++ {
		if key == om.keys.Index(i).Interface() {
			// om.keys = append(om.keys[:i], om.keys[i+1:]...)
			om.keys = reflect.AppendSlice(
				om.keys.Slice(0, i), om.keys.Slice(i+1, keysLen))
			break
		}
	}

	// Setting a key to a zero reflect.Value deletes the key from the map.
	om.m.SetMapIndex(rkey, reflect.Value{})
}
Example #5
0
File: ordmap.go Project: ngaut/ty
// Exists has a parametric type:
//
//	func (om *OrdMap<K, V>) Exists(key K) bool
//
// Exists returns true if `key` is in the map `om`.
func (om *OrdMap) Exists(key interface{}) bool {
	rkey := ty.AssertType(key, om.ktype)
	return om.exists(rkey)
}