Skip to content

Commit

Permalink
add Context Clone
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinku-Chen committed Oct 24, 2024
1 parent 5224b97 commit b44b2ec
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
12 changes: 12 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,15 @@ func (c *Context) ForEach(fn func(k string, v interface{}) interface{}) []interf

return ret
}

// Clone clones context
func (c *Context) Clone() *Context {
c.lock.RLock()
defer c.lock.RUnlock()
newCtx := NewContext()
c.ForEach(func(key string, value interface{}) interface{} {
newCtx.Put(key, value)
return nil
})
return newCtx
}
21 changes: 21 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,24 @@ func TestContextIteration(t *testing.T) {
}
}
}

func TestContextClone(t *testing.T) {
ctxOrg := NewContext()
for i := 0; i < 10; i++ {
ctxOrg.Put(strconv.Itoa(i), i)
}

ctx := ctxOrg.Clone()
values := ctx.ForEach(func(k string, v interface{}) interface{} {
return v.(int)
})
if len(values) != 10 {
t.Fatal("fail to iterate context")
}
for _, i := range values {
v := i.(int)
if v != ctx.GetAny(strconv.Itoa(v)).(int) {
t.Fatal("value not equal")
}
}
}

0 comments on commit b44b2ec

Please sign in to comment.