Skip to content

Instantly share code, notes, and snippets.

@archie
Created November 25, 2013 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archie/7642081 to your computer and use it in GitHub Desktop.
Save archie/7642081 to your computer and use it in GitHub Desktop.
Using "Pimp my library" pattern to add customised functionality to a Scala Vector.
package raft
import scala.language.implicitConversions
import akka.actor.ActorRef
abstract class Entry[T](val command: T, val term: Int, val sender: (ActorRef, Int))
case class StringEntry(
override val command: String,
override val term: Int,
override val sender: (ActorRef, Int))
extends Entry[String](command, term, sender)
abstract class Entries[T](log: Vector[Entry[T]]) {
def persist(entries: Vector[Entry[T]])
def append(entries: Vector[Entry[T]]): Vector[Entry[T]] =
append(entries, log.length)
def append(entries: Vector[Entry[T]], at: Int): Vector[Entry[T]] = {
val updlog = log.take(at) ++ entries
persist(updlog)
updlog
}
def termOf(index: Int): Int = this(index).term
def get(i: Int) = this(i) // how to use apply directly?
def lastIndex = log.length
def lastTerm = termOf(log.length)
def apply(index: Int): Entry[T] =
if (index > 0) log(index - 1)
else null
}
class InMemoryEntries[T](log: Vector[Entry[T]]) extends Entries(log) {
/* in memory we leave in a free world */
def persist(entries: Vector[Entry[T]]) = ()
}
object InMemoryEntries {
implicit def canBuildFrom[T](v: Vector[Entry[T]]) = new InMemoryEntries(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment