gopcp/example.v2

关于第五章Cmap的bucket的Delete方法是否可以简化一下

summerKK opened this issue · 1 comments

  • 老师您好,在cmap里面bucketDelete方法是否可以简化一下 .我们可以直接记录删除要删除节点的pre节点和next节点.把pre.next = next节点

  • 书里面的示例代码:

func (b *bucket) Delete(key string, lock sync.Locker) bool {
	if lock != nil {
		lock.Lock()
		defer lock.Unlock()
	}
	firstPair := b.GetFirstPair()
	if firstPair == nil {
		return false
	}
	var prevPairs []Pair
	var target Pair
	var breakpoint Pair
	for v := firstPair; v != nil; v = v.Next() {
		if v.Key() == key {
			target = v
			breakpoint = v.Next()
			break
		}
		prevPairs = append(prevPairs, v)
	}
	if target == nil {
		return false
	}
	newFirstPair := breakpoint
	for i := len(prevPairs) - 1; i >= 0; i-- {
		pairCopy := prevPairs[i].Copy()
		pairCopy.SetNext(newFirstPair)
		newFirstPair = pairCopy
	}
	if newFirstPair != nil {
		b.firstValue.Store(newFirstPair)
	} else {
		b.firstValue.Store(placeholder)
	}
	atomic.AddUint64(&b.size, ^uint64(0))
	return true
}
  • 我实现的代码
func (b *bucket) Delete(key string, locker sync.Locker) bool {
	if locker != nil {
		locker.Lock()
		defer locker.Unlock()
	}

	firstPair := b.GetFirstPair()
	if firstPair == nil {
		return false
	}
	var prePair IPair
	var target IPair
	var nextPair IPair
	for v := firstPair; v != nil; v = v.Next() {
		if v.Key() == key {
			target = v
			nextPair = v.Next()
			break
		}
		prePair = v
	}

	if target == nil {
		return false
	}

	// bucket只存在一个元素
	if prePair == nil {
		b.firstValue.Store(placeholder)
	} else {
		prePair.SetNext(nextPair)
	}

	atomic.AddUint64(&b.size, ^uint64(0))

	return true
}

image