github.com/DQNEO/babygo@v0.0.3/lib/mymap/map.go (about)

     1  package mymap
     2  
     3  import "unsafe"
     4  
     5  type Map struct {
     6  	first  *item
     7  	length int
     8  }
     9  
    10  type item struct {
    11  	key   interface{}
    12  	Value interface{}
    13  	next  *item
    14  }
    15  
    16  func (i *item) Next() *item {
    17  	return i.next
    18  }
    19  
    20  func (i *item) GetKeyAsString() string {
    21  	return i.key.(string)
    22  }
    23  
    24  func (i *item) match(key interface{}) bool {
    25  	switch k := key.(type) {
    26  	case string:
    27  		return i.key.(string) == k
    28  	case unsafe.Pointer:
    29  		return i.key.(unsafe.Pointer) == k
    30  	default:
    31  		panic("Not supported key type")
    32  	}
    33  	panic("Not supported key type")
    34  }
    35  
    36  func (mp *Map) Len() int {
    37  	return mp.length
    38  }
    39  
    40  func (mp *Map) First() *item {
    41  	return mp.first
    42  }
    43  
    44  func (mp *Map) Get(key interface{}) (interface{}, bool) {
    45  	for item := mp.first; item != nil; item = item.next {
    46  		if item.match(key) {
    47  			return item.Value, true
    48  		}
    49  	}
    50  	return nil, false
    51  }
    52  
    53  func (mp *Map) Delete(key interface{}) {
    54  	if mp.first == nil {
    55  		return
    56  	}
    57  	if mp.first.match(key) {
    58  		mp.first = mp.first.next
    59  		mp.length -= 1
    60  		return
    61  	}
    62  	var prev *item
    63  	for item := mp.first; item != nil; item = item.next {
    64  		if item.match(key) {
    65  			prev.next = item.next
    66  			mp.length -= 1
    67  			return
    68  		}
    69  		prev = item
    70  	}
    71  
    72  }
    73  
    74  func (mp *Map) Set(key interface{}, value interface{}) {
    75  	var last *item
    76  	for item := mp.first; item != nil; item = item.next {
    77  		if item.match(key) {
    78  			item.Value = value
    79  			return
    80  		}
    81  		last = item
    82  	}
    83  	newItem := &item{
    84  		key:   key,
    85  		Value: value,
    86  	}
    87  	if mp.first == nil {
    88  		mp.first = newItem
    89  	} else {
    90  		last.next = newItem
    91  	}
    92  	mp.length += 1
    93  }