Files
tasks/common/collection/oncemap_test.go
Roey BermanandGitHub ca3db91ab3 Add oncemap collection (#5416)
## What changed?

Added a OnceMap collection to common.

> OnceMap is a concurrent map which lazily constructs its values. Map
values are initialized on-the-fly, using a
> provided construction function only when a key is accessed for the
first time.
## Why?

I have a couple of uses for it in the nexus branch.

## How did you test it?

Added unit tests
2024-02-14 10:02:10 -08:00

51 lines
1.6 KiB
Go

// The MIT License
//
// Copyright (c) 2024 Temporal Technologies Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package collection
import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
)
func TestOnceMap(t *testing.T) {
counter := atomic.Int32{}
m := NewOnceMap(func(k string) int {
return int(counter.Add(1))
})
foo1 := m.Get("foo")
foo2 := m.Get("foo")
require.Equal(t, 1, foo1)
require.Equal(t, 1, foo2)
bar1 := m.Get("bar")
bar2 := m.Get("bar")
require.Equal(t, 2, bar1)
require.Equal(t, 2, bar2)
}