tuubes / TuubesCraft

Tuubes for Minecraft
GNU Lesser General Public License v3.0
8 stars 0 forks source link

Type-safe packet builder #9

Closed TheElectronWill closed 6 years ago

TheElectronWill commented 6 years ago

Example of how this could be done :

class PacketSomething(var number: Int, var infos: String)
class PacketSomethingBuilder[P <: PacketSomething] {
  private var number: Int = _
  private var infos: String = _

  def withNumber(n: Int): Builder[P with Number] {
    number=n
    this.asInstanceOf[Builder[P with Number]]
  }
  def withInfos(s: String): Builder[P with Infos] {
    infos=s
    this.asInstanceOf[Builder[P with Infos]]
  }
  def build()(implicit evidence: P =:= Complete) {
    new PacketSomething(number, infos)
  }
object PacketSomethingBuilder {
  sealed trait Number
  sealed trait Infos
  type Complete = PacketSomething with Number with Infos
}

We could also provide a way to construct a NiolBuffer directly, if the performance benefit is worth it.

TheElectronWill commented 6 years ago

Done! See https://github.com/tuubes/DataTractor/commit/74803ab18111d9652e268fefb4ebf2b8f551e3a1