Skip to content

Commit

Permalink
Avoid updateWith
Browse files Browse the repository at this point in the history
These mutable structures update rarely: normally they mutate.
Since updateWith is for updating, just get the thing to mutate.
Rarely, when the thing is empty, remove the key.
  • Loading branch information
som-snytt committed May 24, 2024
1 parent 13f2934 commit 8e84fd3
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 14 deletions.
8 changes: 4 additions & 4 deletions src/main/scala/scala/collection/mutable/MultiDict.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ class MultiDict[K, V] private (elems: Map[K, Set[V]])

def subtractOne(elem: (K, V)): this.type = {
val (k, v) = elem
val _ = elems.updateWith(k) {
case existing @ Some(vs) =>
elems.get(k) match {
case Some(vs) =>
vs.subtractOne(v)
if (vs.isEmpty) None else existing
case _ => None
if (vs.isEmpty) elems.subtractOne(k)
case _ =>
}
this
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/scala/scala/collection/mutable/MultiSet.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ class MultiSetImpl[A] private[mutable] (elems: Map[A, AtomicInteger]) extends Mu
}

def subtractOne(elem: A): this.type = {
val _ = elems.updateWith(elem) {
case existing @ Some(n) => if (n.decrementAndGet <= 0) None else existing
case _ => None
elems.get(elem) match {
case Some(n) => if (n.decrementAndGet <= 0) elems.subtractOne(elem)
case _ =>
}
this
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/scala/scala/collection/mutable/SortedMultiDict.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ class SortedMultiDict[K, V] private (elems: SortedMap[K, Set[V]])(implicit val o

def subtractOne(elem: (K, V)): this.type = {
val (k, v) = elem
val _ = elems.updateWith(k) {
case existing @ Some(vs) =>
elems.get(k) match {
case Some(vs) =>
vs.subtractOne(v)
if (vs.isEmpty) None else existing
case _ => None
if (vs.isEmpty) elems.subtractOne(k)
case _ =>
}
this
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/scala/scala/collection/mutable/SortedMultiSet.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ class SortedMultiSet[A] private (elems: SortedMap[A, AtomicInteger])(implicit va
}

def subtractOne(elem: A): this.type = {
val _ = elems.updateWith(elem) {
case existing @ Some(n) => if (n.decrementAndGet <= 0) None else existing
case _ => None
elems.get(elem) match {
case Some(n) => if (n.decrementAndGet <= 0) elems.subtractOne(elem)
case _ =>
}
this
}
Expand Down

0 comments on commit 8e84fd3

Please sign in to comment.