|
| 1 | +//> using options -language:experimental.modularity -source future |
| 2 | +package hylo |
| 3 | + |
| 4 | +/** A type-erased collection. |
| 5 | + * |
| 6 | + * A `AnyCollection` forwards its operations to a wrapped value, hiding its implementation. |
| 7 | + */ |
| 8 | +final class AnyCollection[Element] private ( |
| 9 | + val _start: () => AnyValue, |
| 10 | + val _end: () => AnyValue, |
| 11 | + val _after: (AnyValue) => AnyValue, |
| 12 | + val _at: (AnyValue) => Element |
| 13 | +) |
| 14 | + |
| 15 | +object AnyCollection { |
| 16 | + |
| 17 | + /** Creates an instance forwarding its operations to `base`. */ |
| 18 | + def apply[Base: Collection](base: Base): AnyCollection[Base.Element] = |
| 19 | + |
| 20 | + def start(): AnyValue = |
| 21 | + AnyValue(base.startPosition) |
| 22 | + |
| 23 | + def end(): AnyValue = |
| 24 | + AnyValue(base.endPosition) |
| 25 | + |
| 26 | + def after(p: AnyValue): AnyValue = |
| 27 | + AnyValue(base.positionAfter(p.unsafelyUnwrappedAs[Base.Position])) |
| 28 | + |
| 29 | + def at(p: AnyValue): Base.Element = |
| 30 | + base.at(p.unsafelyUnwrappedAs[Base.Position]) |
| 31 | + |
| 32 | + new AnyCollection[Base.Element]( |
| 33 | + _start = start, |
| 34 | + _end = end, |
| 35 | + _after = after, |
| 36 | + _at = at |
| 37 | + ) |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +given [T: Value] => AnyCollection[T] is Collection: |
| 42 | + |
| 43 | + type Element = T |
| 44 | + type Position = AnyValue |
| 45 | + |
| 46 | + extension (self: AnyCollection[T]) |
| 47 | + def startPosition = self._start() |
| 48 | + def endPosition = self._end() |
| 49 | + def positionAfter(p: Position) = self._after(p) |
| 50 | + def at(p: Position) = self._at(p) |
| 51 | + |
0 commit comments