TreeSet/TreeMap#range()#clear() shouldn’t clear the whole set/map #12808
Description
Reproduction steps
Scala version: 2.13.11
scala> val set = collection.mutable.SortedSet(1, 2, 3, 4, 5, 6)
val set: scala.collection.mutable.SortedSet[Int] = TreeSet(1, 2, 3, 4, 5, 6)
scala> set.range(3, 5).clear()
scala> set
val res1: scala.collection.mutable.SortedSet[Int] = TreeSet()
scala> val map = collection.mutable.SortedMap(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four", 5 -> "five")
val map: scala.collection.mutable.SortedMap[Int,String] = TreeMap(1 -> one, 2 -> two, 3 -> three, 4 -> four, 5 -> five)
scala> map.range(2, 4).clear()
scala> map
val res3: scala.collection.mutable.SortedMap[Int,String] = TreeMap()
Problem
range
(and all its similarly-named siblings) returns a projection that reflects/contains only a bounded slice of the set/map. It is natural to assume that clearing this projection should clear all elements within these bounds and keep any other elements unaffected.
A trusting programmer could use this (as I did) in an attempt to efficiently delete a whole (sub)range of values, and only testing would show that it doesn’t work.
Looking at the standard library’s source code, it seems that RedBlackTree
doesn’t implement a range delete operation at the moment. I hear it is possible to implement range deletion in asymptotically logarithmic time, but I admit I don’t know how complicated the code would be or how big the constant factor would be.