Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add generic implementation of bidirectional map #303

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions bidirectionalmap/OWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# See the OWNERS docs at https://go.k8s.io/owners

reviewers:
- logicalhan
- thockin
approvers:
- logicalhan
- thockin
107 changes: 107 additions & 0 deletions bidirectionalmap/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bidirectionalmap

import (
"k8s.io/utils/genericinterfaces"
"k8s.io/utils/set"
)

// BidirectionalMap is a bidirectional map.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would flesh this out more. What is the semantic, what guarantees does it offer or not offer, what is it for (a real example)? Also explaion which is the left-key and right-value vs. the left-value and right-key.

Naively I would expect BiDiMap[X, Y] to mean map[X]Y + Map[Y]X, but this seems to be the opposite

Copy link
Member Author

@logicalhan logicalhan Mar 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what you mean by opposite, map[X]Y + Map[Y]X can be invalidated by have multiple keys in map[x]y map to the same y value. e.g.:

a = map[string]string
a["a"] = "1"
a["b"] = "1"

The reverse mapping must return a list of the keys of map a otherwise we have a lossy reverse map.

Therefore, a bidirectional map must be two maps, each of which map to a list (or set) of values.

type BidirectionalMap[X genericinterfaces.Ordered, Y genericinterfaces.Ordered] struct {
right map[X]set.Set[Y]
left map[Y]set.Set[X]
}

// NewBidirectionalMap creates a new BidirectionalMap.
func NewBidirectionalMap[X genericinterfaces.Ordered, Y genericinterfaces.Ordered]() *BidirectionalMap[X, Y] {
return &BidirectionalMap[X, Y]{
right: make(map[X]set.Set[Y]),
left: make(map[Y]set.Set[X]),
}
}

// InsertRight inserts a new item into the right map, return true if the key-value was not already
// present in the map, false otherwise
func (bdm *BidirectionalMap[X, Y]) InsertRight(x X, y Y) bool {
if bdm.right[x] == nil {
bdm.right[x] = set.New[Y]()
}
if bdm.right[x].Has(y) {
return false
}
if bdm.left[y] == nil {
bdm.left[y] = set.New[X]()
}
bdm.right[x].Insert(y)
bdm.left[y].Insert(x)
return true
}

// InsertLeft inserts a new item into the left map, return true if the key-value was not already
// present in the map, false otherwise
func (bdm *BidirectionalMap[X, Y]) InsertLeft(y Y, x X) bool {
return bdm.InsertRight(x, y)
}

// GetRight returns a value from the right map.
func (bdm *BidirectionalMap[X, Y]) GetRight(x X) set.Set[Y] {
return bdm.right[x]
}

// GetLeft returns a value from left map.
func (bdm *BidirectionalMap[X, Y]) GetLeft(y Y) set.Set[X] {
return bdm.left[y]
}

// DeleteRightKey deletes the key from the right map and removes
// the inverse mapping from the left map.
func (bdm *BidirectionalMap[X, Y]) DeleteRightKey(x X) {
if leftValues, ok := bdm.right[x]; ok {
delete(bdm.right, x)
for y := range leftValues {
bdm.left[y].Delete(x)
if bdm.left[y].Len() == 0 {
delete(bdm.left, y)
}
}
}
}

// DeleteLeftKey deletes the key from the left map and removes
// the inverse mapping from the right map.
func (bdm *BidirectionalMap[X, Y]) DeleteLeftKey(y Y) {
if rightValues, ok := bdm.left[y]; ok {
delete(bdm.left, y)
for x := range rightValues {
bdm.right[x].Delete(y)
if bdm.right[x].Len() == 0 {
delete(bdm.right, x)
}
}
}
}

// GetRightKeys returns the keys from the right map.
func (bdm *BidirectionalMap[X, Y]) GetRightKeys() set.Set[X] {
return set.KeySet[X](bdm.right)
}

// GetLeftKeys returns the keys from the left map.
func (bdm *BidirectionalMap[X, Y]) GetLeftKeys() set.Set[Y] {
return set.KeySet[Y](bdm.left)
}
46 changes: 46 additions & 0 deletions bidirectionalmap/map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bidirectionalmap

import "testing"

func TestMultipleInserts(t *testing.T) {
bidimap := NewBidirectionalMap[string, string]()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Examples with different types would better illustrate.

You could add an example_test.go to get a nice godoc example

bidimap.InsertRight("r1", "l1")
bidimap.InsertRight("r1", "l2")
if bidimap.GetRight("r1").Len() != 2 {
t.Errorf("GetRight('r1').Len() == %d, expected 2", bidimap.GetRight("r1").Len())
}
if bidimap.GetLeft("l2").Len() != 1 {
t.Errorf("GetLeft('l2').Len() == %d, expected 1", bidimap.GetLeft("l2").Len())
}
bidimap.InsertLeft("l2", "r2")
if bidimap.GetLeft("l2").Len() != 2 {
t.Errorf("GetLeft('l2').Len() == %d, expected 2", bidimap.GetLeft("l2").Len())
}
r2Len := bidimap.GetRight("r2").Len()
if r2Len != 1 {
t.Errorf("GetRight('r2').Len() == %d, expected 1", r2Len)
}
bidimap.DeleteRightKey("r2")
if bidimap.GetRight("r2") != nil {
t.Errorf("GetRight('r2') should be nil")
}
if bidimap.GetLeft("l2").Len() != 1 {
t.Errorf("GetLeft('l2').Len() == %d, expected 1", bidimap.GetLeft("l2").Len())
}
}
8 changes: 8 additions & 0 deletions genericinterfaces/OWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# See the OWNERS docs at https://go.k8s.io/owners

reviewers:
- logicalhan
- thockin
approvers:
- logicalhan
- thockin
28 changes: 14 additions & 14 deletions set/ordered.go → genericinterfaces/ordered.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Kubernetes Authors.
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -14,40 +14,40 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package set
package genericinterfaces

// ordered is a constraint that permits any ordered type: any type
// Ordered is a constraint that permits any ordered type: any type
// that supports the operators < <= >= >.
// If future releases of Go add new ordered types,
// this constraint will be modified to include them.
type ordered interface {
integer | float | ~string
type Ordered interface {
Integer | Float | ~string
}

// integer is a constraint that permits any integer type.
// Integer is a constraint that permits any integer type.
// If future releases of Go add new predeclared integer types,
// this constraint will be modified to include them.
type integer interface {
signed | unsigned
type Integer interface {
Signed | Unsigned
}

// float is a constraint that permits any floating-point type.
// Float is a constraint that permits any floating-point type.
// If future releases of Go add new predeclared floating-point types,
// this constraint will be modified to include them.
type float interface {
type Float interface {
~float32 | ~float64
}

// signed is a constraint that permits any signed integer type.
// Signed is a constraint that permits any signed integer type.
// If future releases of Go add new predeclared signed integer types,
// this constraint will be modified to include them.
type signed interface {
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}

// unsigned is a constraint that permits any unsigned integer type.
// Unsigned is a constraint that permits any unsigned integer type.
// If future releases of Go add new predeclared unsigned integer types,
// this constraint will be modified to include them.
type unsigned interface {
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
10 changes: 6 additions & 4 deletions set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,26 @@ package set

import (
"sort"

"k8s.io/utils/genericinterfaces"
)

// Empty is public since it is used by some internal API objects for conversions between external
// string arrays and internal sets, and conversion logic requires public types today.
type Empty struct{}

// Set is a set of the same type elements, implemented via map[ordered]struct{} for minimal memory consumption.
type Set[E ordered] map[E]Empty
type Set[E genericinterfaces.Ordered] map[E]Empty

// New creates a new set.
func New[E ordered](items ...E) Set[E] {
func New[E genericinterfaces.Ordered](items ...E) Set[E] {
ss := Set[E]{}
ss.Insert(items...)
return ss
}

// KeySet creates a Set[E] from a keys of a map[E](? extends interface{}).
func KeySet[E ordered, A any](theMap map[E]A) Set[E] {
func KeySet[E genericinterfaces.Ordered, A any](theMap map[E]A) Set[E] {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the motivation for exporting the type? are we expecting other things to reference the interface? They couldn't previously, which had the benefit of only allowing people to declare KeySet with their own types, which had to be compatible with our constraints... that seemed reasonable to me.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd need to redeclare the exact same type in the maps package otherwise, since the output of the value of a map is a generic set.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about waiting for the bump to Go 1.21 in utils and relying on cmp.Ordered? See also #295.

ret := Set[E]{}
for key := range theMap {
ret.Insert(key)
Expand Down Expand Up @@ -158,7 +160,7 @@ func (s Set[E]) Equal(s2 Set[E]) bool {
return s.Len() == s2.Len() && s.IsSuperset(s2)
}

type sortableSlice[E ordered] []E
type sortableSlice[E genericinterfaces.Ordered] []E

func (s sortableSlice[E]) Len() int {
return len(s)
Expand Down
4 changes: 3 additions & 1 deletion set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package set
import (
"reflect"
"testing"

"k8s.io/utils/genericinterfaces"
)

func TestStringSetHasAll(t *testing.T) {
Expand Down Expand Up @@ -365,7 +367,7 @@ func TestSetClearInSeparateFunction(t *testing.T) {
}
}

func clearSetAndAdd[T ordered](s Set[T], a T) {
func clearSetAndAdd[T genericinterfaces.Ordered](s Set[T], a T) {
s.Clear()
s.Insert(a)
}