Skip to content

Instantly share code, notes, and snippets.

@archie
Created November 25, 2013 14:34
Show Gist options
  • Select an option

  • Save archie/7642081 to your computer and use it in GitHub Desktop.

Select an option

Save archie/7642081 to your computer and use it in GitHub Desktop.

Revisions

  1. archie created this gist Nov 25, 2013.
    42 changes: 42 additions & 0 deletions Log.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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)
    }