Skip to content

Instantly share code, notes, and snippets.

@mbloms
Created December 7, 2020 10:24
Show Gist options
  • Save mbloms/31f8c8c32cfb0dec2d636d5f55ad9499 to your computer and use it in GitHub Desktop.
Save mbloms/31f8c8c32cfb0dec2d636d5f55ad9499 to your computer and use it in GitHub Desktop.
package vector
import scala.reflect.ClassTag
import collection.{immutable,mutable}
import mutable.Cloneable
/** Const Interface for a Wrapped Array
* An instance of this class is either a MutableArray or ImmutableArray
*/
sealed abstract class ConstArray[+A] protected (arr: Array[A])
extends collection.AbstractSeq[A]
with collection.IndexedSeq[A]
with collection.IndexedSeqOps[A,ConstArray,ConstArray[A]] {
export arr.{apply,length}
def frozen(): ImmutableArray[A]
}
final class MutableArray[A] private (arr: Array[A])
extends ConstArray[A](arr)
with mutable.IndexedSeq[A]
with mutable.IndexedSeqOps[A,MutableArray,MutableArray[A]] {
export arr.update
override def iterableFactory = collection.ClassTagSeqFactory.AnySeqDelegate(MutableArray)
override def clone() = new MutableArray[A](arr.clone())
def frozen() = ImmutableArray.freeze(arr)
}
object MutableArray extends collection.StrictOptimizedClassTagSeqFactory[MutableArray] {
override def empty[A: ClassTag]: MutableArray[A] = new MutableArray[A](Array.empty)
override def from[E: ClassTag](it: IterableOnce[E]): MutableArray[E] = new MutableArray[E](Array.from(it))
override def newBuilder[A: ClassTag]: mutable.Builder[A, MutableArray[A]] = mutable.ArrayBuilder.make[A].mapResult(new MutableArray[A](_))
}
final class ImmutableArray[+A] private (arr: Array[A])
extends ConstArray[A](arr)
with immutable.IndexedSeq[A] {
def this(xs: A*)(using ClassTag[A]) = this(Array[A](xs:_*))
override def iterableFactory = collection.ClassTagSeqFactory.AnySeqDelegate(ImmutableArray)
def frozen() = this
}
object ImmutableArray extends collection.StrictOptimizedClassTagSeqFactory[ImmutableArray] {
def freeze[T](arr: Array[T]) = new ImmutableArray[T](arr.clone())
override def empty[A: ClassTag]: ImmutableArray[A] = new ImmutableArray[A](Array.empty)
override def from[E: ClassTag](it: IterableOnce[E]): ImmutableArray[E] = new ImmutableArray[E](Array.from(it))
override def newBuilder[A: ClassTag]: mutable.Builder[A, ImmutableArray[A]] = mutable.ArrayBuilder.make[A].mapResult(new ImmutableArray[A](_))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment