[Git][java-team/scala-tools-sbinary][upstream] New upstream version 0.5.1
Simon Quigley (@tsimonq2)
gitlab at salsa.debian.org
Tue Nov 17 02:16:04 GMT 2026
Simon Quigley pushed to branch upstream at Debian Java Maintainers / scala-tools-sbinary
Commits:
c5f9e4f7 by Juan Manuel Méndez Rey at 2026-10-28T00:12:13+01:00
New upstream version 0.5.1
- - - - -
25 changed files:
- .gitignore
- + .scalafmt.conf
- + .travis.yml
- + INSTALL.markdown
- − README
- + README.markdown
- + build.sbt
- core/src/generic.scala → core/src/main/fmpp/generic.scala
- core/src/standardtypes.scala → core/src/main/fmpp/standardtypes.scala
- + core/src/main/scala-2.13+/LowPriorityCollectionTypes.scala
- + core/src/main/scala-2.13-/LowPriorityCollectionTypes.scala
- core/src/defaultprotocol.scala → core/src/main/scala/defaultprotocol.scala
- core/src/io.scala → core/src/main/scala/io.scala
- core/src/javaprotocol.scala → core/src/main/scala/javaprotocol.scala
- core/src/operations.scala → core/src/main/scala/operations.scala
- + core/src/main/scala/protocol.scala
- − core/src/protocol.scala
- core/test-src/binaryTests.scala → core/src/test/scala/binaryTests.scala
- examples/bt/BT.scala
- + project/Dependencies.scala
- + project/Fmpp.scala
- + project/HouseRulesPlugins.scala
- − project/SBinaryProject.scala
- project/build.properties
- + project/plugins.sbt
Changes:
=====================================
.gitignore
=====================================
@@ -1,2 +1,2 @@
target/
-.gitignore
+foo.bin
=====================================
.scalafmt.conf
=====================================
@@ -0,0 +1,24 @@
+version = 2.3.2
+edition = 2019-10
+maxColumn = 100
+project.git = true
+
+# http://docs.scala-lang.org/style/scaladoc.html recommends the JavaDoc style.
+# scala/scala is written that way too https://github.com/scala/scala/blob/v2.12.2/src/library/scala/Predef.scala
+docstrings = JavaDoc
+
+# This also seems more idiomatic to include whitespace in import x.{ yyy }
+spaces.inImportCurlyBraces = true
+
+# This also seems more idiomatic to include whitespace in import x.{ yyy }
+spaces.inImportCurlyBraces = true
+
+# This is more idiomatic Scala.
+# http://docs.scala-lang.org/style/indentation.html#methods-with-numerous-arguments
+align.openParenCallSite = false
+align.openParenDefnSite = false
+
+# For better code clarity
+danglingParentheses = true
+
+trailingCommas = preserve
=====================================
.travis.yml
=====================================
@@ -0,0 +1,34 @@
+language: scala
+
+matrix:
+ include:
+ - env: ADOPTOPENJDK=11
+ script: sbt ++2.12.11! test
+ - env: ADOPTOPENJDK=8
+ script: sbt scalafmtCheckAll scalafmtSbtCheck mimaReportBinaryIssues +test
+
+before_install:
+ # adding $HOME/.sdkman to cache would create an empty directory, which interferes with the initial installation
+ - "[[ -d /home/travis/.sdkman/ ]] && [[ -d /home/travis/.sdkman/bin/ ]] || rm -rf /home/travis/.sdkman/"
+ - curl -sL https://get.sdkman.io | bash
+ - echo sdkman_auto_answer=true > /home/travis/.sdkman/etc/config
+ - echo sdkman_auto_selfupdate=true >> $HOME/.sdkman/etc/config
+ - source "/home/travis/.sdkman/bin/sdkman-init.sh"
+
+install:
+ - sdk install java $(sdk list java | grep -o "$ADOPTOPENJDK\.[0-9\.]*hs-adpt" | head -1) || true
+ - unset _JAVA_OPTIONS
+ - java -Xmx32m -version
+ - unset SBT_OPTS
+ - unset JAVA_OPTS
+
+before_cache:
+ - find $HOME/.ivy2/cache -name "ivydata-*.properties" -delete
+ - find $HOME/.sbt -name "*.lock" -delete
+
+cache:
+ directories:
+ - $HOME/.cache/coursier
+ - $HOME/.ivy2/cache
+ - $HOME/.sbt/boot
+ - $HOME/.sdkman
=====================================
INSTALL.markdown
=====================================
@@ -0,0 +1,14 @@
+
+### Build instructions
+
+SBinary uses sbt to build.
+
+To build and run the example:
+
+```
+$ sbt publishLocal 'project treeExample' run
+```
+
+This will retrieve dependencies and compile, package, and publish SBinary to your ~/.ivy2/local repository. If you just want to use the jar directly, it is in the `target/` directory.
+
+You can find the source for the example is in the examples/bt/ directory.
=====================================
README deleted
=====================================
@@ -1,24 +0,0 @@
-SBinary is a library for describing binary protocols, in the form of mappings between Scala types and binary formats. It can be used as a robust serialization mechanism for Scala objects or a way of dealing with existing binary formats found in the wild.
-
-It started out life as a loose port of Haskell's Data.Binary. It's since evolved a bit from there to take advantage of the features Scala implicits offer over Haskell type classes, but the core idea has remained the same.
-
-SBinary was written by David MacIver. You can find his introduction here: http://code.google.com/p/sbinary/wiki/IntroductionToSBinary.
-
-= Getting SBinary =
-
-SBinary is in the Scala Tools Repository. If you are using sbt with Scala 2.7.7:
- val sbinary = "org.scala-tools.sbinary" %% "sbinary" % "0.3"
-
-For Maven users, use "sbinary_2.7.7" for the artifact ID.
-
-
-= Build instructions =
-
-SBinary uses sbt to build. Get sbt at http://code.google.com/p/simple-build-tool/wiki/Setup
-
-To build and run the example:
-sbt update publish-local 'project Binary Tree Example' run
-
-This will retrieve dependencies and compile, package, and publish SBinary to your ~/.ivy2/local repository. If you just want to use the jar directly, it is in the `target/` directory.
-
-You can find the source for the example is in the examples/bt/ directory.
\ No newline at end of file
=====================================
README.markdown
=====================================
@@ -0,0 +1,428 @@
+SBinary
+=======
+
+SBinary is a library for describing binary protocols, in the form of mappings between
+Scala types and binary formats. It can be used as a robust serialization mechanism for
+Scala objects or a way of dealing with existing binary formats found in the wild.
+
+It started out life as a loose port of Haskell's Data.Binary.
+It's since evolved a bit from there to take advantage of the features Scala implicits
+offer over Haskell type classes, but the core idea has remained the same.
+
+## Getting SBinary
+
+If you are using sbt with Scala 2.10.x or 2.11.x:
+
+```scala
+val sbinary = "org.scala-sbt" %% "sbinary" % "0.4.4"
+```
+
+## Credits
+
+- SBinary was written by David MacIver. The following is an instruction written by David.
+
+## Usage
+
+The basic entry point to SBinary is the `Protocol` trait.
+A Protocol specifies a form of binary IO (although to be honest, you're probably
+just going to end up using the standard Java implementation for IO) and a number of Formats.
+
+Binary formats are specified by the following traits:
+
+```scala
+trait Reads[T]{
+ def reads(in : Input) : T
+}
+
+trait Writes[T]{
+ def writes(out : Output, value : T)
+}
+
+trait Format[T] extends Reads[T] with Writes[T]
+```
+
+i.e. a format is something that specifies how to read an element from an input source and
+write an element to an output source.
+
+You're not expected to use the reads and writes method directly. Instead Formats are typically
+made available implicitly and you use the methods
+
+```scala
+def read[T](in : Input)(implicit reader : Reads[T]) = reader.reads(in)
+def write[T](out : Output, value : T)(implicit writer : Writes[T]) = writer.writes(out, value)
+```
+
+The example interactive sessions are self-contained. Other example code assumes these imports:
+
+```scala
+import sbinary._
+import DefaultProtocol._
+import Operations._
+```
+
+The example code is available as a runnable project. If you have checked out the SBinary project
+and have sbt installed, run the examples by executing the following in the root directory:
+
+```
+$ sbt publishLocal 'project treeExample' run
+```
+
+### The Default Protocol
+
+You're expected to define your own protocol for most uses of SBinary in order to serialize your
+own types. However for getting started and for simple uses SBinary provides a default protocol
+which lets you serialize most standard library types out of the box. It uses Java IO, but all
+the types it defines are available in traits if you want to use a different IO mechanism.
+
+So, let's see some examples of how to use this:
+
+```
+scala> import sbinary.DefaultProtocol._
+import sbinary.DefaultProtocol._
+
+scala> List("foo", "bar", "baz")
+res0: List[java.lang.String] = List(foo, bar, baz)
+
+scala> toByteArray(res0)
+res1: Array[Byte] = Array(0, 0, 0, 3, 0, 3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122)
+
+scala> fromByteArrayList[String]
+res3: List[String] = List(foo, bar, baz)
+```
+
+Straightforward enough. There's also some helper stuff for writing to files:
+
+```
+scala> toFile(res0)(new java.io.File("foo.bin"))
+
+scala> fromFile[List[String]](new java.io.File("foo.bin"))
+res7: List[String] = List(foo, bar, baz)
+```
+
+Curious fact:
+
+```
+scala> fromFile[Array[String]](new java.io.File("foo.bin"))
+res8: Array[String] = Array(foo, bar, baz)
+```
+
+Note that this is the same file we just wrote as a `ListString` and we've just read it as an `ArrayString`!
+
+In general, SBinary formats aim to be as straightforward as possible. Formats for similar
+things tend to be the same. Consequently most of the time you have a fair bit of flexibility
+as to whether you write things as the same type you read them as.
+
+### Defining your own protocols
+
+One way to use SBinary would just be to use the default protocol and extend the Format type it provides.
+This is perfectly effective, but not really the best way.
+
+The idea is that your usage of SBinary defines a protocol for binary formats. Two different protocols might
+define very different formats for the same type, and as long as both are creating formats in the default protocol
+there's no way to distinguish between them.
+
+Lest this sound like an obscure theoretical possibility, please consider just how many character encodings
+for strings there are (in fact, a very large part of the motivation for the move to protocols in 0.3 was
+the fact that I didn't want to force the standard Java UTF format to be used everywhere).
+
+So, the idea is that you define a protocol. For simplicitly, let's make it a single object.
+We'll look into how you might modularise it later.
+
+```scala
+object MyProtocol extends DefaultProtocol{ }
+```
+
+(There is a trait `DefaultProtocol` as well. The `DefaultProtocol` object simply extends it and adds no additional methods).
+
+Great. We have a protocol. It does exactly the same as the default one. But that's a start.
+
+Now, we need something to write to it. Let's consider a simple binary tree type where the leafs are annotated by strings.
+
+```scala
+sealed abstract class BT
+case class Bin(left: BT, right: BT) extends BT
+case class Leaf(label: String) extends BT
+```
+
+How could we define a format for this?
+
+Let's start by thinking about how we read this off a stream of bytes.
+
+We first need something to distinguish what we're reading. i.e. we need to know whether we have a `Bin` or a `Leaf`.
+So let's start with a marker byte: If it's `0`, we have a `Bin`, otherwise we have a `Leaf`.
+
+So, now we know whether we're reading a `Bin` or a `Leaf`. What do we do now? Easy. If we have a Bin, then we read one BT,
+then another. If we have a Leaf, we read a string. We then assemble these in the obvious way:
+
+```scala
+object MyProtocol extends DefaultProtocol{
+ implicit object BTFormat extends Format[BT]{
+ def reads(in: Input) = readByte match {
+ case 0 => Bin(reads(in), reads(in))
+ case _ => Leaf(readString)
+ }
+
+ def writes(out : Output, value : BT) = sys.error("What do I do here?")
+ }
+}
+```
+
+Pretty straightforward. And once we've written that, it becomes obvious what to do for the `write` method:
+
+```scala
+object MyProtocol extends DefaultProtocol{
+ implicit object BTFormat extends Format[BT] {
+ def reads(in: Input) = readByte match {
+ case 0 => Bin(reads(in), reads(in))
+ case _ => Leaf(readString)
+ }
+
+ def writes(out : Output, value : BT) = value match {
+ case Bin(left, right) =>
+ write[Byte](out, 0)
+ writes(out, left)
+ writes(out, right)
+ case Leaf(label) =>
+ write[Byte](out, 1)
+ write(out, label)
+ }
+ }
+}
+```
+
+Now we can use this just like we would the default protocol:
+
+```scala
+scala> import MyProtocol._
+import MyProtocol._
+
+scala> Bin(Leaf("foo"), Bin(Leaf("bar"), Leaf("baz")))
+res0: Bin = Bin(Leaf(foo),Bin(Leaf(bar),Leaf(baz)))
+
+scala> toByteArrayBT
+res2: Array[Byte] = Array(0, 1, 0, 3, 102, 111, 111, 0, 1, 0, 3, 98, 97, 114, 1, 0, 3, 98, 97, 122)
+
+scala> fromByteArrayBT
+res3: BT = Bin(Leaf(foo),Bin(Leaf(bar),Leaf(baz)))
+```
+
+See, wasn't that easy? Perfectly straightforward to define a binary format, right?
+
+Right?
+
+### Generic format construction
+
+Ok, it wasn't particularly easy. In fact, it was massively verbose. I don't know about you,
+but I'd get pretty sick of writing things like the above. And I'd almost certainly make mistakes
+(of course, I didn't make any mistakes in SBinary, because I'm amazing. But in theory I might make mistakes.
+Particularly if I didn't use a lot of scalacheck tests to make sure I didn't).
+
+So, let's write this a bit differently:
+
+```scala
+object MyProtocol extends DefaultProtocol {
+ implicit val BTFormat: Format[BT] = lazyFormat(asUnion[BT](
+ asProduct2(Bin)(Bin.unapply(_).get),
+ wrap[Leaf, String](_.label, Leaf)))
+}
+```
+
+Which is rather nicer (not to mention shorter) I feel!
+
+Let's unpack how this works through some simpler examples (we're going to do this in the the REPL).
+
+#### Wrapping formats
+
+First let's look at what we did to leaves:
+
+```scala
+scala> implicit val LeafFormat = wrap[Leaf, String](_.label, Leaf)
+LeafFormat: java.lang.Object with MyProtocol2.Format[Leaf] = sbinary.Generic$$anon$4 at 1e081c5
+```
+
+So the wrap method defines a format for Leaf.
+
+Let's see what it looks like:
+
+```scala
+scala> toByteArray(Leaf("foo"))
+res9: Array[Byte] = Array(0, 3, 102, 111, 111)
+
+scala> toByteArray("foo")
+res10: Array[Byte] = Array(0, 3, 102, 111, 111)
+```
+
+The format of the `Leaf` is exactly that of the String it wraps. The two functions which we pass
+to wrap are simply used to pack and unpack it from the original format (which was picked up as an implicit argument).
+
+#### Formats for case classes
+
+First let's see how the asProduct stuff works:
+
+```scala
+scala> import MyProtocol._
+import MyProtocol._
+
+scala> case class Foo(bar : String, baz : Int);
+defined class Foo
+
+scala> implicit val Foormat = asProduct2(Foo)(Foo.unapply(_).get)
+Foormat: java.lang.Object with MyProtocol2.Format[Foo] = sbinary.Generic$$anon$8 at 1f5205c
+
+scala> toByteArray(Foo("bar", 3))
+res4: Array[Byte] = Array(0, 3, 98, 97, 114, 0, 0, 0, 3)
+
+scala> fromByteArrayFoo
+res5: Foo = Foo(bar,3)
+```
+
+`asProductN` basically defines binary formats which are concatenations of other formats.
+In this instance, Foo is just its components written in order:
+
+```scala
+scala> toByteArray("bar")
+res6: Array[Byte] = Array(0, 3, 98, 97, 114)
+
+scala> toByteArray(3)
+res7: Array[Byte] = Array(0, 0, 0, 3)
+
+scala> res4
+res8: Array[Byte] = Array(0, 3, 98, 97, 114, 0, 0, 0, 3)
+```
+
+We give `asProduct` methods for assembling and disassembling instances of the type into their component parts.
+Conveniently, the `apply` and `unapply` methods generated on case classes do more or less what we want.
+This makes it very easy to define formats for case classes.
+
+#### Formats for unions
+
+We frequently have a setup like the following:
+
+```scala
+scala> abstract class Bar
+defined class Bar
+
+scala> case class Baz(foo : Int) extends Bar
+defined class Baz
+
+scala> case class Blib(foo : String) extends Bar
+defined class Blib
+```
+
+We've seen how to define formats for `Baz` and `Blib`:
+
+```scala
+scala> implicit val BazFormat : Format[Baz] = wrap(_.foo, Baz)
+BazFormat: MyProtocol2.Format[Baz] = sbinary.Generic$$anon$4 at de3c87
+
+scala> implicit val BlibFormat : Format[Blib] = wrap(_.foo, Blib)
+BlibFormat: MyProtocol2.Format[Blib] = sbinary.Generic$$anon$4 at 16b0c24
+```
+
+But how do we go from there to a format for `Bar`?
+
+Well, we basically saw how to do this with our hand written binary tree example:
+We define a byte tag which says which subtype we're in. So all we need to do to represent this is
+specify the formats for the subtypes in order and associate a tag with each. That's what `asUnion` does.
+
+```scala
+scala> implicit val BarFormat = asUnion[Bar](BazFormat, BlibFormat)
+BarFormat: MyProtocol2.Format[Bar] = sbinary.Generic$$anon$16 at 12143d8
+
+scala> toByteArrayBar
+res11: Array[Byte] = Array(1, 0, 3, 102, 111, 111)
+
+scala> toByteArrayBlib
+res12: Array[Byte] = Array(0, 3, 102, 111, 111)
+
+scala> toByteArrayBar
+res13: Array[Byte] = Array(0, 0, 0, 0, 3)
+
+scala> toByteArrayBaz
+res14: Array[Byte] = Array(0, 0, 0, 3)
+```
+
+Note how in each case the Bar format is just a tag prepended to the subformat?
+
+Another important thing to notice: The format depends on the static type of the argument,
+not the runtime type. The format written as a Bar is not the same as the format written as a Baz
+Because of this you should try to only make formats you actually care about visible,
+otherwise type inference can occasionally screw you over. This means that the approach taken in
+the binary tree example where the subtypes do not have their own explicit format is generally
+a better default than defining a format for each type as in this example.
+
+#### Self referential formats
+
+Suppose we had the following linked list type:
+
+```scala
+scala> abstract class LL
+defined class LL
+
+scala> case object Nope extends LL
+defined module Nope
+
+scala> abstract class Yup(car : Int, cdr : LL) extends LL
+defined class Yup
+```
+
+Great. This looks like stuff we've seen before. We know how to write a format for it.
+
+```scala
+scala> implicit val LLFormat : Format[LL] = asUnion[LL](Nope, asProduct2(Yup)(Yup.unapply(_).get))
+
+scala> toByteArrayLL
+res16: Array[Byte] = Array(0)
+```
+
+So far so good...
+
+```scala
+scala> toByteArray[LL](Yup(1, Nope))
+java.lang.NullPointerException at sbinary.Protocol$class.write(protocol.scala:27)
+at MyProtocol2$.write(binarytree.scala:7)
+at sbinary.Generic$$anon$8.writes(generic.scala:111)
+at sbinary.Protocol$class.write(protocol.scala:27)
+at MyProtocol2$.write(binarytree.scala:7)
+at sbinary.Generic$$anon$16$$anonfun$writes$3.apply(generic.scala:361)
+at sbinary.Generic$$anon$16$$anonfun$wr...
+```
+
+Oops. What happened here? :-(
+
+Well, the problem is that `asProduct2` takes a bunch of implicit arguments: Two in fact.
+One for the format for its first argument, one for the format for its second argument.
+
+Unfortunately the format for its second argument is the format currently being defined!
+It hasn't been initialised yet, so we got a null when calling asProduct2 and it all went wrong.
+
+Let's fix it:
+
+```scala
+scala> implicit val LLFormat : Format[LL] =lazyFormat(asUnion[LL](Nope, asProduct2(Yup)(Yup.unapply(_).get)))
+LLFormat: MyProtocol2.Format[LL] = sbinary.Generic$$anon$5 at 17ce686
+
+scala> toByteArrayLL
+res18: Array[Byte] = Array(1, 0, 0, 0, 1, 0)
+```
+
+`lazyFormat` basically performs magic to make cases like this work. It takes a call by name argument which
+will produce a format and returns a format which delegates to that. This means that it's ok to reference the format
+currently being defined inside the body because the body is not called during initialisation, only when the format is first used.
+
+#### Putting it all together
+
+Let's look at it again:
+
+```scala
+object MyProtocol extends DefaultProtocol {
+ implicit val BTFormat : Format[BT] = lazyFormat(asUnion[BT](
+ asProduct2(Bin)(Bin.unapply(_).get),
+ wrap[Leaf, String](_.label, Leaf) ))
+}
+```
+
+Hopefully, it should all make sense now. We use `asProduct2` and wrap to define formats for the two subtypes,
+use `asUnion` to glue them together and then use `lazyFormat` to allow the format to still refer to itself.
+
+Easy, right?
=====================================
build.sbt
=====================================
@@ -0,0 +1,92 @@
+import Dependencies._
+
+ThisBuild / organization := "org.scala-sbt"
+ThisBuild / organizationHomepage := Some(url("http://scala-sbt.org/"))
+ThisBuild / homepage := Some(url("https://github.com/sbt/sbinary"))
+ThisBuild / version := "0.5.1-SNAPSHOT"
+ThisBuild / scalaVersion := scala212
+ThisBuild / crossScalaVersions := Seq(scala210, scala211, scala212, scala213)
+ThisBuild / bintrayPackage := "sbinary"
+ThisBuild / developers := List(
+ Developer(
+ "drmaciver",
+ "David R. MacIver",
+ "@drmaciver",
+ url("https://github.com/DRMacIver")
+ ),
+ Developer("harrah", "Mark Harrah", "@harrah", url("https://github.com/harrah")),
+ Developer("eed3si9n", "Eugene Yokota", "@eed3si9n", url("https://github.com/eed3si9n"))
+)
+ThisBuild / description := "Library for describing binary formats for Scala types"
+ThisBuild / licenses := Seq("MIT" -> new URL("https://github.com/sbt/sbinary/blob/master/LICENSE"))
+ThisBuild / scmInfo := Some(
+ ScmInfo(url("https://github.com/sbt/sbinary"), "git at github.com:sbt/sbinary.git")
+)
+
+lazy val root = (project in file("."))
+ .aggregate(core, treeExample)
+ .settings(nocomma {
+ name := "SBinary Root"
+ publish / skip := true
+ mimaPreviousArtifacts := Set.empty
+ })
+
+lazy val core = (project in file("core"))
+ .settings(nocomma {
+ name := "SBinary"
+
+ mimaPreviousArtifacts := {
+ Set.empty
+ }
+ libraryDependencies += scalacheck % Test
+ libraryDependencies ++= scalaVersion(scalaXmlDep).value
+ Compile / unmanagedSourceDirectories += {
+ val base = (Compile / scalaSource).value.getParentFile
+ CrossVersion.partialVersion(scalaVersion.value) match {
+ case Some((2, v)) if v >= 13 =>
+ base / s"scala-2.13+"
+ case _ =>
+ base / s"scala-2.13-"
+ }
+ }
+ Compile / unmanagedResources += (baseDirectory map { _ / "LICENSE" }).value
+ mimaPreviousArtifacts := {
+ val versions = Seq("0.5.0")
+ val crossVersion = if (crossPaths.value) CrossVersion.binary else CrossVersion.disabled
+ versions.map(v => organization.value % moduleName.value % v cross crossVersion).toSet
+ },
+ })
+ .settings(
+ relaxOldScala,
+ Fmpp.templateSettings
+ )
+
+lazy val treeExample = (project in (file("examples") / "bt"))
+ .dependsOn(core)
+ .settings(nocomma {
+ name := "SBinary Tree Example"
+ publish / skip := true
+ mimaPreviousArtifacts := Set.empty
+ })
+ .settings(relaxOldScala)
+
+def relaxOldScala: Seq[Setting[_]] = Seq(
+ scalacOptions := {
+ val old = scalacOptions.value
+ CrossVersion.partialVersion(scalaVersion.value) match {
+ case Some((2, n)) if n >= 12 =>
+ old filterNot Set(
+ "-Xfatal-warnings",
+ "-Ywarn-unused-import",
+ "-Yno-adapted-args"
+ )
+ case _ =>
+ old filterNot (Set(
+ "-Xfatal-warnings",
+ "-deprecation",
+ "-Ywarn-unused",
+ "-Ywarn-unused-import"
+ ).apply _)
+ }
+ }
+)
=====================================
core/src/generic.scala → core/src/main/fmpp/generic.scala
=====================================
@@ -3,10 +3,8 @@
*/
package sbinary;
-import scala.collection.mutable.{ListBuffer, ArrayBuffer};
import scala.collection._;
-import java.io._;
import Operations._;
trait Generic extends CoreProtocol{
@@ -43,7 +41,7 @@ trait Generic extends CoreProtocol{
* Length encodes, but with the result built from a Seq.
* Useful for when a `ClassManifest` is not available the underlying type `T`.
*/
- def viaSeq[S <: Traversable[T], T] (f : Seq[T] => S) (implicit binary : Format[T]) : Format[S] = new Format[S] {
+ def viaSeq[S <: Traversable[T], T] (f : collection.Seq[T] => S) (implicit binary : Format[T]) : Format[S] = new Format[S] {
def writes(out : Output, xs : S) = { write(out, xs.size); xs.foreach(write(out, _)); }
def reads(in : Input) = f(read[List[T]](in));
}
@@ -89,7 +87,7 @@ trait Generic extends CoreProtocol{
def withStamp[S, T](stamp : S)(binary : Format[T])(implicit binS : Format[S]) : Format[T] = new Format[T]{
def reads(in : Input) = {
val datastamp = read[S](in);
- if (stamp != datastamp) error("Incorrect stamp. Expected: " + stamp + ", Found: " + datastamp);
+ if (stamp != datastamp) sys.error("Incorrect stamp. Expected: " + stamp + ", Found: " + datastamp);
binary.reads(in);
}
@@ -110,7 +108,7 @@ trait Generic extends CoreProtocol{
def writes(out : Output, value : V) = write(out, value.id)
}
- <#list 2..9 as i>
+ <#list 2..21 as i>
<#assign typeParams><#list 1..i as j>T${j}<#if i !=j>,</#if></#list></#assign>
/**
* Represents this type as ${i} consecutive binary blocks of type T1..T${i},
@@ -137,7 +135,7 @@ trait Generic extends CoreProtocol{
case class Summand[T](clazz : Class[_], format : Format[T]);
implicit def classToSummand[T](clazz : Class[T])(implicit bin : Format[T]) : Summand[T] = Summand[T](clazz, bin);
- implicit def formatToSummand[T](format : Format[T])(implicit mf : scala.reflect.Manifest[T]) : Summand[T] = Summand[T](mf.erasure, format);
+ implicit def formatToSummand[T](format : Format[T])(implicit mf : scala.reflect.Manifest[T]) : Summand[T] = Summand[T](mf.runtimeClass, format);
// This is a bit gross.
implicit def anyToSummand[T](t : T) = Summand[T](t.asInstanceOf[AnyRef].getClass, asSingleton(t))
@@ -145,7 +143,7 @@ trait Generic extends CoreProtocol{
* Uses a single tag byte to represent S as a union of subtypes.
*/
def asUnion[S](summands : Summand[_ <: S]*) : Format[S] =
- if (summands.length >= 256) error("Sums of 256 or more elements currently not supported");
+ if (summands.length >= 256) sys.error("Sums of 256 or more elements currently not supported");
else
new Format[S]{
val mappings = summands.toArray.zipWithIndex;
@@ -155,12 +153,12 @@ trait Generic extends CoreProtocol{
def writes(out : Output, s : S): Unit =
mappings.find(_._1.clazz.isInstance(s)) match {
case Some( (sum, i) ) => writeSum(out, s, sum, i)
- case None => error("No known sum type for object " + s);
+ case None => sys.error("No known sum type for object " + s);
}
- private def writeSum[T](out : Output, s : S, sum : Summand[T], i : Int) {
+ private def writeSum[T](out : Output, s : S, sum : Summand[T], i : Int): Unit = {
write(out, i.toByte);
// 2.7/2.8 compatibility: cast added by MH
write(out, sum.clazz.cast(s).asInstanceOf[T])(sum.format);
}
}
-}
\ No newline at end of file
+}
=====================================
core/src/standardtypes.scala → core/src/main/fmpp/standardtypes.scala
=====================================
@@ -2,7 +2,6 @@ package sbinary;
import Operations._;
import scala.collection._;
-import generic.CanBuildFrom
trait BasicTypes extends CoreProtocol{
implicit def optionsAreFormat[S](implicit bin : Format[S]) : Format[Option[S]] = new Format[Option[S]]{
@@ -41,19 +40,6 @@ trait BasicTypes extends CoreProtocol{
</#list>
}
-trait LowPriorityCollectionTypes extends Generic {
- def canBuildFormat[CC[X] <: Traversable[X], T](implicit bin : Format[T], cbf: CanBuildFrom[Nothing, T, CC[T]]) : Format[CC[T]] =
- new LengthEncoded[CC[T], T]{
- def build(length : Int, ts : Iterator[T]) = {
- val builder = cbf.apply()
- builder.sizeHint(length)
- builder ++= ts
- if(ts.hasNext) error("Builder did not consume all input.") // no lazy builders allowed
- builder.result()
- }
- }
-}
-
trait CollectionTypes extends BasicTypes with LowPriorityCollectionTypes {
implicit def listFormat[T](implicit bin : Format[T]) : Format[List[T]] = canBuildFormat[List, T]
@@ -79,27 +65,27 @@ trait CollectionTypes extends BasicTypes with LowPriorityCollectionTypes {
bytes;
}
- def writes(out : Output, bytes : Array[Byte]){
+ def writes(out : Output, bytes : Array[Byte]): Unit = {
write(out, bytes.length);
out.writeAll(bytes);
}
}
implicit def mutableSetFormat[T](implicit bin : Format[T]) : Format[mutable.Set[T]] =
- viaSeq((x : Seq[T]) => mutable.Set(x :_*))
+ viaSeq((x : Seq[T]) => mutable.Set(x.toSeq :_*))
implicit def immutableSetFormat[T](implicit bin : Format[T]) : Format[immutable.Set[T]] =
- viaSeq((x : Seq[T]) => immutable.Set(x :_*))
+ viaSeq((x : Seq[T]) => immutable.Set(x.toSeq :_*))
implicit def immutableSortedSetFormat[S](implicit ord : Ordering[S], binS : Format[S]) : Format[immutable.SortedSet[S]] = {
- viaSeq( (x : Seq[S]) => immutable.TreeSet[S](x :_*))
+ viaSeq( (x : Seq[S]) => immutable.TreeSet[S](x.toSeq :_*))
}
implicit def immutableMapFormat[S, T](implicit binS : Format[S], binT : Format[T]) : Format[immutable.Map[S, T]] =
- viaSeq( (x : Seq[(S, T)]) => immutable.Map(x :_*));
+ viaSeq( (x : Seq[(S, T)]) => immutable.Map(x.toSeq :_*));
implicit def immutableSortedMapFormat[S, T](implicit ord : Ordering[S], binS : Format[S], binT : Format[T]) : Format[immutable.SortedMap[S, T]] = {
- viaSeq( (x : Seq[(S, T)]) => immutable.TreeMap[S, T](x :_*))
+ viaSeq( (x : Seq[(S, T)]) => immutable.TreeMap[S, T](x.toSeq :_*))
}
/**
@@ -128,7 +114,7 @@ trait CollectionTypes extends BasicTypes with LowPriorityCollectionTypes {
buffer.toStream;
}
- def writes(out : Output, stream : Stream[S]){
+ def writes(out : Output, stream : Stream[S]): Unit = {
stream.foreach(x => { write[Byte](out, 1); write(out, x); });
write[Byte](out, 0);
}
@@ -161,7 +147,7 @@ trait StandardTypes extends CollectionTypes{
implicit lazy val UriFormat : Format[URI] = viaString(new URI(_ : String));
- import scala.xml.{XML, Elem, NodeSeq};
+ import scala.xml.{XML, NodeSeq};
implicit lazy val XmlFormat : Format[NodeSeq] = new Format[NodeSeq]{
def reads(in : Input) = XML.loadString(read[String](in)).child;
def writes(out : Output, elem : NodeSeq) = write(out, <binary>elem</binary>.toString);
=====================================
core/src/main/scala-2.13+/LowPriorityCollectionTypes.scala
=====================================
@@ -0,0 +1,16 @@
+package sbinary
+
+import scala.collection.Factory
+
+trait LowPriorityCollectionTypes extends Generic {
+ def canBuildFormat[CC[X] <: Iterable[X], T](implicit bin : Format[T], cbf: Factory[T, CC[T]]) : Format[CC[T]] =
+ new LengthEncoded[CC[T], T]{
+ def build(length : Int, ts : Iterator[T]) = {
+ val builder = cbf.newBuilder
+ builder.sizeHint(length)
+ builder ++= ts
+ if(ts.hasNext) sys.error("Builder did not consume all input.") // no lazy builders allowed
+ builder.result()
+ }
+ }
+}
=====================================
core/src/main/scala-2.13-/LowPriorityCollectionTypes.scala
=====================================
@@ -0,0 +1,19 @@
+package sbinary
+
+import scala.collection.generic.CanBuildFrom
+
+trait LowPriorityCollectionTypes extends Generic {
+ def canBuildFormat[CC[X] <: Traversable[X], T](
+ implicit bin: Format[T],
+ cbf: CanBuildFrom[Nothing, T, CC[T]]
+ ): Format[CC[T]] =
+ new LengthEncoded[CC[T], T] {
+ def build(length: Int, ts: Iterator[T]) = {
+ val builder = cbf.apply()
+ builder.sizeHint(length)
+ builder ++= ts
+ if (ts.hasNext) sys.error("Builder did not consume all input.") // no lazy builders allowed
+ builder.result()
+ }
+ }
+}
=====================================
core/src/defaultprotocol.scala → core/src/main/scala/defaultprotocol.scala
=====================================
=====================================
core/src/io.scala → core/src/main/scala/io.scala
=====================================
@@ -1,91 +1,92 @@
package sbinary;
case class EOF() extends Exception;
-object EOF{
+object EOF {
def eof = throw new EOF;
}
import EOF.eof
-trait Input{
+trait Input {
/**
* Read a byte. If we have come to the end of the stream, throws EOF.
*/
- def readByte : Byte;
+ def readByte: Byte;
- def readTo(target : Array[Byte], offset : Int, length : Int) : Int = {
+ def readTo(target: Array[Byte], offset: Int, length: Int): Int = {
var i = 0;
- try{
- while (i < length){
+ try {
+ while (i < length) {
target(offset + i) = readByte;
i += 1;
}
} catch {
- case EOF() =>;
+ case EOF() => ;
}
i;
}
- def readTo(target : Array[Byte]) : Int = readTo(target, 0, target.length);
+ def readTo(target: Array[Byte]): Int = readTo(target, 0, target.length);
- def readFully(target : Array[Byte], offset : Int, length : Int){
+ def readFully(target: Array[Byte], offset: Int, length: Int): Unit = {
var bytesRead = 0;
- while(bytesRead < length){
+ while (bytesRead < length) {
val newRead = readTo(target, offset + bytesRead, length - bytesRead);
if (newRead <= 0) eof;
bytesRead += newRead;
}
}
- def readFully(target : Array[Byte]){
+ def readFully(target: Array[Byte]): Unit = {
readFully(target, 0, target.length);
- }
+ }
}
-trait Output{
- def writeByte(value : Byte);
+trait Output {
+ def writeByte(value: Byte): Unit
- def writeAll(source : Array[Byte], offset : Int, length : Int) {
+ def writeAll(source: Array[Byte], offset: Int, length: Int): Unit = {
var i = 0;
- while(i < length){
+ while (i < length) {
writeByte(source(offset + i));
i += 1;
}
}
- def writeAll(source : Array[Byte]){
+ def writeAll(source: Array[Byte]): Unit = {
writeAll(source, 0, source.length);
}
}
import java.io._;
-class JavaInput(in : InputStream) extends Input{
+class JavaInput(in: InputStream) extends Input {
def readByte = in.read() match {
- case x if x < 0 => eof;
- case x => x.toByte;
+ case x if x < 0 => eof;
+ case x => x.toByte;
}
- override def readTo(target : Array[Byte], offset : Int, length : Int) : Int =
+ override def readTo(target: Array[Byte], offset: Int, length: Int): Int =
in.read(target, offset, length) match {
case x if x < 0 => eof;
- case x => x;
+ case x => x;
}
}
-class JavaOutput(out : OutputStream) extends Output{
- def writeByte(value : Byte) = out.write(value);
- override def writeAll(source : Array[Byte], offset : Int, length : Int) = out.write(source, offset, length);
+class JavaOutput(out: OutputStream) extends Output {
+ def writeByte(value: Byte) = out.write(value);
+ override def writeAll(source: Array[Byte], offset: Int, length: Int) =
+ out.write(source, offset, length);
}
object Input {
- implicit def javaInputToInput(x : InputStream): JavaInput = new JavaInput(x)
+ implicit def javaInputToInput(x: InputStream): JavaInput = new JavaInput(x)
}
object Output {
- implicit def javaOutputToOutput(x : OutputStream): JavaOutput = new JavaOutput(x);
+ implicit def javaOutputToOutput(x: OutputStream): JavaOutput = new JavaOutput(x);
}
=====================================
core/src/javaprotocol.scala → core/src/main/scala/javaprotocol.scala
=====================================
@@ -2,59 +2,59 @@ package sbinary;
import Operations._;
-trait StandardPrimitives extends CoreProtocol{
- private def readUnsigned(in : Input) = in.readByte.toInt & 0xFF
+trait StandardPrimitives extends CoreProtocol {
+ private def readUnsigned(in: Input) = in.readByte.toInt & 0xFF
- implicit object BooleanFormat extends Format[Boolean]{
- def reads(in : Input) = in.readByte != 0
- def writes(out : Output, t : Boolean) = out.writeByte(if (t) (0x01) else (0x00));
+ implicit object BooleanFormat extends Format[Boolean] {
+ def reads(in: Input) = in.readByte != 0
+ def writes(out: Output, t: Boolean) = out.writeByte(if (t) (0x01) else (0x00));
}
- implicit object CharFormat extends Format[Char]{
- def reads(in : Input) = ((readUnsigned(in) << 8) + readUnsigned(in)).toChar;
- def writes(out : Output, t : Char) = {
+ implicit object CharFormat extends Format[Char] {
+ def reads(in: Input) = ((readUnsigned(in) << 8) + readUnsigned(in)).toChar;
+ def writes(out: Output, t: Char) = {
out.writeByte(((t >>> 8) & 0xFF).toByte);
out.writeByte(((t >>> 0) & 0xFF).toByte);
}
}
- implicit object ShortFormat extends Format[Short]{
- def reads(in : Input) = ((readUnsigned(in) << 8) + readUnsigned(in)).toShort
+ implicit object ShortFormat extends Format[Short] {
+ def reads(in: Input) = ((readUnsigned(in) << 8) + readUnsigned(in)).toShort
- def writes(out : Output, t : Short) = {
+ def writes(out: Output, t: Short) = {
out.writeByte(((t >>> 8) & 0xFF).toByte);
out.writeByte(t.toByte);
- }
+ }
}
- implicit object IntFormat extends Format[Int]{
- def reads(in : Input) = {
+ implicit object IntFormat extends Format[Int] {
+ def reads(in: Input) = {
val ch1 = readUnsigned(in);
val ch2 = readUnsigned(in);
val ch3 = readUnsigned(in);
val ch4 = readUnsigned(in);
- ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0))
+ ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0))
}
- def writes(out : Output, t : Int) {
+ def writes(out: Output, t: Int): Unit = {
out.writeByte(((t >>> 24) & 0xFF).toByte);
out.writeByte(((t >>> 16) & 0xFF).toByte);
- out.writeByte(((t >>> 8) & 0xFF).toByte);
- out.writeByte(((t >>> 0) & 0xFF).toByte);
- }
+ out.writeByte(((t >>> 8) & 0xFF).toByte);
+ out.writeByte(((t >>> 0) & 0xFF).toByte);
+ }
}
- implicit object LongFormat extends Format[Long]{
- def reads(in : Input) =
- (readUnsigned(in).toLong << 56) +
- (readUnsigned(in).toLong << 48) +
- (readUnsigned(in).toLong << 40) +
- (readUnsigned(in).toLong << 32) +
- (readUnsigned(in).toLong << 24) +
- (readUnsigned(in).toLong << 16) +
- (readUnsigned(in).toLong << 8) +
- (readUnsigned(in).toLong << 0);
- def writes(out : Output, t : Long) = {
+ implicit object LongFormat extends Format[Long] {
+ def reads(in: Input) =
+ (readUnsigned(in).toLong << 56) +
+ (readUnsigned(in).toLong << 48) +
+ (readUnsigned(in).toLong << 40) +
+ (readUnsigned(in).toLong << 32) +
+ (readUnsigned(in).toLong << 24) +
+ (readUnsigned(in).toLong << 16) +
+ (readUnsigned(in).toLong << 8) +
+ (readUnsigned(in).toLong << 0);
+ def writes(out: Output, t: Long) = {
out.writeByte((t >>> 56).toByte);
out.writeByte((t >>> 48).toByte);
out.writeByte((t >>> 40).toByte);
@@ -66,39 +66,39 @@ trait StandardPrimitives extends CoreProtocol{
}
}
- implicit object FloatFormat extends Format[Float]{
- def reads(in : Input) = java.lang.Float.intBitsToFloat(read[Int](in))
- def writes(out : Output, t : Float) = write[Int](out, java.lang.Float.floatToIntBits(t));
+ implicit object FloatFormat extends Format[Float] {
+ def reads(in: Input) = java.lang.Float.intBitsToFloat(read[Int](in))
+ def writes(out: Output, t: Float) = write[Int](out, java.lang.Float.floatToIntBits(t));
}
- implicit object DoubleFormat extends Format[Double]{
- def reads(in : Input) = java.lang.Double.longBitsToDouble(read[Long](in));
- def writes(out : Output, t : Double) = write[Long](out, java.lang.Double.doubleToLongBits(t));
+ implicit object DoubleFormat extends Format[Double] {
+ def reads(in: Input) = java.lang.Double.longBitsToDouble(read[Long](in));
+ def writes(out: Output, t: Double) = write[Long](out, java.lang.Double.doubleToLongBits(t));
}
}
-trait JavaUTF extends CoreProtocol{
- private[this] def readUnsignedByte(in : Input) : Int = in.readByte.toInt & 0xFF
- private[this] def readUnsignedShort(in : Input) : Int =
+trait JavaUTF extends CoreProtocol {
+ private[this] def readUnsignedByte(in: Input): Int = in.readByte.toInt & 0xFF
+ private[this] def readUnsignedShort(in: Input): Int =
(readUnsignedByte(in) << 8) + readUnsignedByte(in)
- private[this] val buffers = new java.lang.ThreadLocal[(Array[Char], Array[Byte])]{
+ private[this] val buffers = new java.lang.ThreadLocal[(Array[Char], Array[Byte])] {
override def initialValue() = (new Array[Char](80), new Array[Byte](80))
}
- private[this] def fetchBuffers(size : Int) = {
- if (buffers.get()._1.length < size){
+ private[this] def fetchBuffers(size: Int) = {
+ if (buffers.get()._1.length < size) {
buffers.set((new Array[Char](size * 2), new Array[Byte](size * 2)));
}
buffers.get();
}
/**
- * A Format for strings compatible with the modified UTF format used by
+ * A Format for strings compatible with the modified UTF format used by
* java.io.DataInput and java.io.DataOutput.
*/
- implicit object StringFormat extends Format[String]{
- def reads(in : Input) = {
+ implicit object StringFormat extends Format[String] {
+ def reads(in: Input) = {
val utflen = readUnsignedShort(in);
val (cbuffer, bbuffer) = fetchBuffers(utflen);
@@ -106,23 +106,23 @@ trait JavaUTF extends CoreProtocol{
var count, charCount, c, char2, char3 = 0;
- def malformed(index : Int) = error("Malformed input around byte " + index);
- def partial = error("Malformed input: Partial character at end");
+ def malformed(index: Int) = sys.error("Malformed input around byte " + index);
+ def partial = sys.error("Malformed input: Partial character at end");
- while((count < utflen) && {c = bbuffer(count) & 0xff; c <= 127 }) {
+ while ((count < utflen) && { c = bbuffer(count) & 0xff; c <= 127 }) {
cbuffer(charCount) = c.toChar;
charCount += 1;
count += 1;
}
- while(count < utflen){
+ while (count < utflen) {
c = bbuffer(count).toInt & 0xFF
cbuffer(charCount) = ((c >> 4) match {
- case 0|1|2|3|4|5|6|7 => {
+ case 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 => {
count += 1;
c
}
- case 12|13 => {
+ case 12 | 13 => {
count += 2;
if (count > utflen) partial;
@@ -134,10 +134,10 @@ trait JavaUTF extends CoreProtocol{
count += 3;
char2 = bbuffer(count - 2);
char3 = bbuffer(count - 1);
- if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
+ if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
malformed(count - 1);
- ((c & 0x0F).toInt << 12) | ((char2 & 0x3F).toInt << 6) | ((char3 & 0x3F).toInt << 0);
+ ((c & 0x0F).toInt << 12) | ((char2 & 0x3F).toInt << 6) | ((char3 & 0x3F).toInt << 0);
}
case _ => malformed(count);
}).toChar
@@ -146,27 +146,28 @@ trait JavaUTF extends CoreProtocol{
new String(cbuffer, 0, charCount);
}
-
- def writes(out : Output, value : String){
+
+ def writes(out: Output, value: String): Unit = {
var utflen = 0;
-
+
var i = 0;
- def c = value.charAt(i);
+ def c = value.charAt(i);
- while(i < value.length){
+ while (i < value.length) {
utflen += (
if ((c >= 0x0001) && (c <= 0x007F)) 1
else if (c > 0x07FF) 3
- else 2)
+ else 2
+ )
i += 1;
}
-
- if (utflen > 65535)
- error("encoded string too long: " + utflen + " bytes");
+
+ if (utflen > 65535)
+ sys.error("encoded string too long: " + utflen + " bytes");
val bbuffer = fetchBuffers(utflen + 2)._2;
var count = 0;
- def append(value : Int) {
+ def append(value: Int): Unit = {
bbuffer(count) = value.toByte;
count += 1;
}
@@ -175,31 +176,30 @@ trait JavaUTF extends CoreProtocol{
append(utflen & 0xFF)
i = 0;
- while((i < value.length) && ((c >= 0x0001) && (c <= 0x007F))) {
+ while ((i < value.length) && ((c >= 0x0001) && (c <= 0x007F))) {
bbuffer(count) = c.toByte;
- count += 1;
+ count += 1;
i += 1;
}
-
- while(i < value.length){
+
+ while (i < value.length) {
if ((c >= 0x0001) && (c <= 0x007F)) {
append(c);
} else if (c > 0x07FF) {
append(0xE0 | ((c >> 12) & 0x0F));
- append(0x80 | ((c >> 6) & 0x3F));
- append(0x80 | ((c >> 0) & 0x3F));
+ append(0x80 | ((c >> 6) & 0x3F));
+ append(0x80 | ((c >> 0) & 0x3F));
} else {
- append(0xC0 | ((c >> 6) & 0x1F));
- append(0x80 | ((c >> 0) & 0x3F));
+ append(0xC0 | ((c >> 6) & 0x1F));
+ append(0x80 | ((c >> 0) & 0x3F));
}
i += 1;
}
- out.writeAll(bbuffer, 0, utflen + 2);
+ out.writeAll(bbuffer, 0, utflen + 2);
}
- }
+ }
}
-trait JavaFormats extends StandardPrimitives with JavaUTF{
-}
+trait JavaFormats extends StandardPrimitives with JavaUTF {}
=====================================
core/src/operations.scala → core/src/main/scala/operations.scala
=====================================
@@ -1,50 +1,58 @@
-
package sbinary;
-object Operations{
- import java.io.{BufferedInputStream, BufferedOutputStream, ByteArrayInputStream, ByteArrayOutputStream, File, FileInputStream, FileOutputStream};
-
- def format[T](implicit fm : Format[T]) = fm;
+object Operations {
+ import java.io.{
+ BufferedInputStream,
+ BufferedOutputStream,
+ ByteArrayInputStream,
+ ByteArrayOutputStream,
+ File,
+ FileInputStream,
+ FileOutputStream
+ };
- def read[T](in : Input)(implicit reader : Reads[T]) = reader.reads(in);
- def write[T](out : Output, value : T)(implicit writer : Writes[T]) = writer.writes(out, value);
+ def format[T](implicit fm: Format[T]) = fm;
+ def read[T](in: Input)(implicit reader: Reads[T]) = reader.reads(in);
+ def write[T](out: Output, value: T)(implicit writer: Writes[T]) = writer.writes(out, value);
/**
* Get the serialized value of this class as a byte array.
*/
- def toByteArray[T](t : T)(implicit bin : Writes[T]) : Array[Byte] = {
+ def toByteArray[T](t: T)(implicit bin: Writes[T]): Array[Byte] = {
val target = new ByteArrayOutputStream();
bin.writes(target, t);
- target.toByteArray();
+ target.toByteArray();
}
-
+
/**
* Read a value from the byte array. Anything past the end of the value will be
* ignored.
- */
- def fromByteArray[T](array : Array[Byte])(implicit bin : Reads[T]) = read[T](new ByteArrayInputStream(array));
+ */
+ def fromByteArray[T](array: Array[Byte])(implicit bin: Reads[T]) =
+ read[T](new ByteArrayInputStream(array));
- /**
+ /**
* Convenience method for writing binary data to a file.
*/
- def toFile[T](t : T)(file : File)(implicit bin : Writes[T]) = {
+ def toFile[T](t: T)(file: File)(implicit bin: Writes[T]) = {
val out = new BufferedOutputStream(new FileOutputStream(file));
- try{
- out.write(toByteArray(t));}
- finally{
- out.close(); }
+ try {
+ out.write(toByteArray(t));
+ } finally {
+ out.close();
+ }
}
- /**
+ /**
* Convenience method for reading binary data from a file.
*/
- def fromFile[T](file : File)(implicit bin : Reads[T]) = {
+ def fromFile[T](file: File)(implicit bin: Reads[T]) = {
val in = new BufferedInputStream(new FileInputStream(file))
- try{
+ try {
read[T](in)
- } finally{
- in.close();
+ } finally {
+ in.close();
}
}
}
=====================================
core/src/main/scala/protocol.scala
=====================================
@@ -0,0 +1,34 @@
+package sbinary;
+
+trait Reads[T] {
+ def reads(in: Input): T;
+}
+
+trait Writes[T] {
+ def writes(out: Output, value: T): Unit;
+}
+
+trait Format[T] extends Reads[T] with Writes[T];
+
+trait Protocol {
+ implicit object ByteFormat extends Format[Byte] {
+ def reads(in: Input) = in.readByte;
+ def writes(out: Output, value: Byte) = out.writeByte(value);
+ }
+
+ implicit object UnitFormat extends Format[Unit] {
+ def reads(in: Input): Unit = {}
+ def writes(out: Output, value: Unit): Unit = {}
+ }
+}
+
+trait CoreProtocol extends Protocol {
+ implicit val IntFormat: Format[Int];
+ implicit val ShortFormat: Format[Short];
+ implicit val LongFormat: Format[Long];
+ implicit val BooleanFormat: Format[Boolean];
+ implicit val CharFormat: Format[Char];
+ implicit val FloatFormat: Format[Float];
+ implicit val DoubleFormat: Format[Double];
+ implicit val StringFormat: Format[String];
+}
=====================================
core/src/protocol.scala deleted
=====================================
@@ -1,38 +0,0 @@
-package sbinary;
-
-
-trait Reads[T]{
- def reads(in : Input) : T;
-}
-
-trait Writes[T]{
- def writes(out : Output, value : T) : Unit;
-}
-
-trait Format[T] extends Reads[T] with Writes[T];
-
-
-trait Protocol{
- implicit object ByteFormat extends Format[Byte]{
- def reads(in : Input) = in.readByte;
- def writes(out : Output, value : Byte) = out.writeByte(value);
- }
-
- implicit object UnitFormat extends Format[Unit]{
- def reads(in : Input){}
- def writes(out : Output, value : Unit) {}
- }
-}
-
-trait CoreProtocol extends Protocol{
- implicit val IntFormat : Format[Int];
- implicit val ShortFormat : Format[Short];
- implicit val LongFormat : Format[Long];
- implicit val BooleanFormat : Format[Boolean];
- implicit val CharFormat : Format[Char];
- implicit val FloatFormat : Format[Float];
- implicit val DoubleFormat : Format[Double];
- implicit val StringFormat : Format[String];
-}
-
-
=====================================
core/test-src/binaryTests.scala → core/src/test/scala/binaryTests.scala
=====================================
@@ -1,6 +1,5 @@
package sbinary;
import org.scalacheck._;
-import org.scalacheck.Test._;
import Gen._;
import Arbitrary.arbitrary;
import Prop._;
@@ -9,11 +8,11 @@ import scala.collection._;
import DefaultProtocol._;
import Operations._;
-object Equal{
+object Equal {
abstract class Equal[T] extends Function2[T, T, Boolean];
- def allAreEqual[T] : Equal[T] = new Equal[T]{
- def apply(x : T, y : T) = x == y
+ def allAreEqual[T]: Equal[T] = new Equal[T] {
+ def apply(x: T, y: T) = x == y
}
implicit val eqString = allAreEqual[String];
@@ -26,69 +25,82 @@ object Equal{
implicit val eqChar = allAreEqual[Char];
implicit def eqSet[T] = allAreEqual[immutable.Set[T]];
implicit def eqSortedSet[T] = allAreEqual[immutable.SortedSet[T]];
- implicit def eqMap[S,T] = allAreEqual[immutable.Map[S,T]];
- implicit def eqSortedMap[S,T] = allAreEqual[immutable.SortedMap[S,T]];
+ implicit def eqMap[S, T] = allAreEqual[immutable.Map[S, T]];
+ implicit def eqSortedMap[S, T] = allAreEqual[immutable.SortedMap[S, T]];
- implicit def eqList[T](implicit eqT : Equal[T]) : Equal[List[T]] = new Equal[List[T]]{
- def apply(x : List[T], y : List[T]) = (x, y) match {
- case (Nil, Nil) => true;
+ implicit def eqList[T](implicit eqT: Equal[T]): Equal[List[T]] = new Equal[List[T]] {
+ def apply(x: List[T], y: List[T]) = (x, y) match {
+ case (Nil, Nil) => true;
case (x :: xs, y :: ys) => eqT(x, y) && apply(xs, ys);
- case _ => false;
+ case _ => false;
}
}
- implicit def eqOption[T](implicit eqT : Equal[T]) : Equal[Option[T]] = new Equal[Option[T]]{
- def apply(x : Option[T], y : Option[T]) = (x, y) match {
- case (None, None) => true;
- case (Some(u), Some(v)) => eqT(u, v);
- case _ => false;
+ implicit def eqOption[T](implicit eqT: Equal[T]): Equal[Option[T]] = new Equal[Option[T]] {
+ def apply(x: Option[T], y: Option[T]) = (x, y) match {
+ case (None, None) => true;
+ case (Some(u), Some(v)) => eqT(u, v);
+ case _ => false;
}
}
- implicit def eqTuple3[S, T, U](implicit eqS : Equal[S], eqT : Equal[T], eqU : Equal[U]) : Equal[(S, T, U)] = new Equal[(S, T, U)]{
- def apply(x : (S, T, U), y : (S, T, U)) = eqS(x._1, y._1) && eqT(x._2, y._2) && eqU(x._3, y._3);
+ implicit def eqTuple3[S, T, U](
+ implicit
+ eqS: Equal[S],
+ eqT: Equal[T],
+ eqU: Equal[U]
+ ): Equal[(S, T, U)] = new Equal[(S, T, U)] {
+ def apply(x: (S, T, U), y: (S, T, U)) = eqS(x._1, y._1) && eqT(x._2, y._2) && eqU(x._3, y._3);
}
- implicit def eqTuple2[S, T](implicit eqS : Equal[S], eqT : Equal[T]) : Equal[(S, T)] = new Equal[(S, T)]{
- def apply(x : (S, T), y : (S, T)) = eqS(x._1, y._1) && eqT(x._2, y._2)
- }
+ implicit def eqTuple2[S, T](implicit eqS: Equal[S], eqT: Equal[T]): Equal[(S, T)] =
+ new Equal[(S, T)] {
+ def apply(x: (S, T), y: (S, T)) = eqS(x._1, y._1) && eqT(x._2, y._2)
+ }
- implicit def arraysAreEqual[T](implicit e : Equal[T]) : Equal[Array[T]] = new Equal[Array[T]]{
- def apply(x : Array[T], y : Array[T]) = (x.length == y.length) && x.zip(y).forall({case (x, y) => e(x, y)})
+ implicit def arraysAreEqual[T](implicit e: Equal[T]): Equal[Array[T]] = new Equal[Array[T]] {
+ def apply(x: Array[T], y: Array[T]) =
+ (x.length == y.length) && x.zip(y).forall({ case (x, y) => e(x, y) })
}
- implicit def streamsAreEqual[T](implicit e : Equal[T]) : Equal[Stream[T]] = new Equal[Stream[T]]{
- def apply(x : Stream[T], y : Stream[T]) = (x.length == y.length) && x.zip(y).forall({case (x, y) => e(x, y)})
+ implicit def streamsAreEqual[T](implicit e: Equal[T]): Equal[Stream[T]] = new Equal[Stream[T]] {
+ def apply(x: Stream[T], y: Stream[T]) =
+ (x.length == y.length) && x.zip(y).forall({ case (x, y) => e(x, y) })
}
- def equal[T](x : T, y : T)(implicit f : Equal[T]) = f(x, y);
-
+ def equal[T](x: T, y: T)(implicit f: Equal[T]) = f(x, y);
}
import Equal._;
-object CompatTests extends Properties("CompatTests"){
+object CompatTests extends Properties("CompatTests") {
import java.io._;
- def compatFor[T](name : String, readJ : DataInput => T, writeJ : (DataOutput, T) => Unit)(implicit fmt : Format[T], arb : Arbitrary[T]) = {
- property(name + "AgreesWithDataInput") = forAll { (x : T) =>
+ def compatFor[T](name: String, readJ: DataInput => T, writeJ: (DataOutput, T) => Unit)(
+ implicit
+ fmt: Format[T],
+ arb: Arbitrary[T]
+ ) = {
+ property(name + "AgreesWithDataInput") = forAll { (x: T) =>
val it = new ByteArrayOutputStream();
- try { fmt.writes(it, x); readJ(new DataInputStream(new ByteArrayInputStream(it.toByteArray))) == x }
- catch { case (e : Throwable) => e.printStackTrace; false }
+ try {
+ fmt.writes(it, x)
+ readJ(new DataInputStream(new ByteArrayInputStream(it.toByteArray))) == x
+ } catch { case (e: Throwable) => e.printStackTrace; false }
};
- property(name + "AgreesWithDataOutput") = forAll { (x : T) =>
+ property(name + "AgreesWithDataOutput") = forAll { (x: T) =>
val it = new ByteArrayOutputStream();
- try {
- writeJ(new DataOutputStream(it), x);
+ try {
+ writeJ(new DataOutputStream(it), x);
val ba = it.toByteArray;
fromByteArray[T](ba) == x
- } catch { case (e : Throwable) => e.printStackTrace; false }
+ } catch { case (e: Throwable) => e.printStackTrace; false }
}
}
- compatFor[String]("String", _.readUTF, _.writeUTF(_))
+ compatFor[String]("String", _.readUTF, _.writeUTF(_))
compatFor[Long]("Long", _.readLong, _.writeLong(_))
compatFor[Int]("Int", _.readInt, _.writeInt(_))
compatFor[Byte]("Byte", _.readByte, _.writeByte(_))
@@ -96,105 +108,130 @@ object CompatTests extends Properties("CompatTests"){
compatFor[Boolean]("Boolean", _.readBoolean, _.writeBoolean(_))
}
+object LazyIOTests extends Properties("LazyIO") {
-object LazyIOTests extends Properties("LazyIO"){
-
- import java.io._;
- property("NoMixingOfStreams") = forAll { (x : Stream[Int]) =>
+ property("NoMixingOfStreams") = forAll { (x: Stream[Int]) =>
val (u, v) = fromByteArray[(Stream[Int], Stream[Int])](toByteArray((x, x)))
- equal(u, v) && equal(u, x);
+ equal(u, v) && equal(u, x);
};
- property("NoMixingOfStreamsAndOthers") = forAll { (x : Stream[Int], y : String, z : Stream[Int]) =>
+ property("NoMixingOfStreamsAndOthers") = forAll { (x: Stream[Int], y: String, z: Stream[Int]) =>
val (u, s, v) = fromByteArray[(Stream[Int], String, Stream[Int])](toByteArray((x, y, z)))
- equal(u, x) && equal(s, y) && equal(z, v);
+ equal(u, x) && equal(s, y) && equal(z, v);
};
- property("StreamsOfStreams") = forAll { (x : Stream[Stream[Int]]) => !x.isEmpty ==> {
- val x2 = fromByteArray[Stream[Stream[Int]]](toByteArray(x));
- equal(x(x.length - 1), x2(x.length - 1));
- } };
+ property("StreamsOfStreams") = forAll { (x: Stream[Stream[Int]]) =>
+ !x.isEmpty ==> {
+ val x2 = fromByteArray[Stream[Stream[Int]]](toByteArray(x));
+ equal(x(x.length - 1), x2(x.length - 1));
+ }
+ };
}
-object FormatTests extends Properties("Formats"){
- def validFormat[T](implicit
- bin : Format[T],
- arb : Arbitrary[T],
- equal : Equal[T]) = forAll((x : T) =>
- try { equal(x, fromByteArray[T](toByteArray(x))) } catch {
- case (e : Throwable) => e.printStackTrace; false
- })
-
- def formatSpec[T](name : String)(implicit
- bin : Format[T],
- arb : Arbitrary[T],
- equal : Equal[T]) =
- { property(name) = validFormat[T] }
-
- implicit val arbitraryUnit = Arbitrary[Unit](value(() => ()))
-
- implicit def arbitrarySortedMap[K, V](implicit ord : Ordering[K], arbK : Arbitrary[K], arbV : Arbitrary[V]) : Arbitrary[immutable.SortedMap[K, V]] = {
- Arbitrary(arbitrary[List[(K, V)]].map(x => immutable.TreeMap(x :_*)))
+object FormatTests extends Properties("Formats") {
+ def validFormat[T](
+ implicit
+ bin: Format[T],
+ arb: Arbitrary[T],
+ equal: Equal[T]
+ ) =
+ forAll(
+ (x: T) =>
+ try {
+ equal(x, fromByteArray[T](toByteArray(x)))
+ } catch {
+ case (e: Throwable) => e.printStackTrace; false
+ }
+ )
+
+ def formatSpec[T](name: String)(
+ implicit
+ bin: Format[T],
+ arb: Arbitrary[T],
+ equal: Equal[T]
+ ) = { property(name) = validFormat[T] }
+
+ implicit val arbitraryUnit = implicitly[Arbitrary[Unit]]
+
+ implicit def arbitrarySortedMap[K, V](
+ implicit
+ ord: Ordering[K],
+ arbK: Arbitrary[K],
+ arbV: Arbitrary[V]
+ ): Arbitrary[immutable.SortedMap[K, V]] = {
+ Arbitrary(arbitrary[List[(K, V)]].map(x => immutable.TreeMap(x: _*)))
}
//implicit def arbitrarySet[T](implicit arb : Arbitrary[T]) : Arbitrary[immutable.Set[T]] = Arbitrary(arbitrary[List[T]].map((x : List[T]) => immutable.Set(x :_*)));
- implicit def arbitraryArray[T](implicit arb : Arbitrary[T], mf: scala.reflect.Manifest[T]) : Arbitrary[Array[T]] =
- Arbitrary(arbitrary[List[T]].map((x : List[T]) => x.toArray[T]));
-
- implicit val arbitraryEnumeration : Arbitrary[Enumeration] = Arbitrary(arbitrary[List[String]].map(x => new Enumeration(x : _*){}));
-
- implicit def orderedOption[T](opt : Option[T])(implicit ord : Ordering[T]) : Ordered[Option[T]] = new Ordered[Option[T]]{
- def compare(that : Option[T]) = (opt, that) match {
- case (None, None) => 0;
- case (None, Some(_)) => -1;
- case (Some(_), None) => 1;
- case (Some(x), Some(y)) => ord.compare(x,y);
+ implicit def arbitraryArray[T](
+ implicit
+ arb: Arbitrary[T],
+ mf: scala.reflect.Manifest[T]
+ ): Arbitrary[Array[T]] =
+ Arbitrary(arbitrary[List[T]].map((x: List[T]) => x.toArray[T]));
+
+ def enum(names: Seq[String]): Enumeration = new Enumeration { names foreach (n => Value(n)) }
+
+ implicit val arbitraryEnumeration: Arbitrary[Enumeration] =
+ Arbitrary(arbitrary[List[String]].map(enum));
+
+ implicit def orderedOption[T](opt: Option[T])(implicit ord: Ordering[T]): Ordered[Option[T]] =
+ new Ordered[Option[T]] {
+ def compare(that: Option[T]) = (opt, that) match {
+ case (None, None) => 0;
+ case (None, Some(_)) => -1;
+ case (Some(_), None) => 1;
+ case (Some(x), Some(y)) => ord.compare(x, y);
+ }
}
- }
trait Foo;
case object Bar extends Foo;
- case class Baz(override val toString : String) extends Foo;
- case class Bif(i : Int, j : Long) extends Foo;
+ case class Baz(override val toString: String) extends Foo;
+ case class Bif(i: Int, j: Long) extends Foo;
implicit val eqFoo = allAreEqual[Foo]
- implicit val BazFormat : Format[Baz] = viaString(Baz)
- implicit val BifFormat : Format[Bif] = asProduct2(Bif)(Bif.unapply(_).get)
- implicit val FooFormat : Format[Foo] = asUnion[Foo](Bar, classOf[Baz], classOf[Bif])
-
- implicit val arbitraryFoo : Arbitrary[Foo] = Arbitrary[Foo](
- oneOf(value(Bar),
- arbitrary[(Int, Long)].map{case (i, j) => Bif(i, j)},
- arbitrary[String].map(Baz(_))))
-
+ implicit val BazFormat: Format[Baz] = viaString(Baz)
+ implicit val BifFormat: Format[Bif] = asProduct2(Bif)(Bif.unapply(_).get)
+ implicit val FooFormat: Format[Foo] = asUnion[Foo](Bar, classOf[Baz], classOf[Bif])
+ implicit val arbitraryFoo: Arbitrary[Foo] = Arbitrary[Foo](
+ oneOf(
+ Bar: Gen[Foo],
+ arbitrary[(Int, Long)].map { case (i, j) => Bif(i, j) },
+ arbitrary[String].map(Baz(_))
+ )
+ )
sealed abstract class BinaryTree;
- case class Split(left : BinaryTree, right : BinaryTree) extends BinaryTree;
- case class Leaf extends BinaryTree;
+ case class Split(left: BinaryTree, right: BinaryTree) extends BinaryTree;
+ case class Leaf() extends BinaryTree;
implicit val eqBinaryTree = allAreEqual[BinaryTree]
- implicit val BinaryTreeIsFormat : Format[BinaryTree] = lazyFormat({
+ implicit val BinaryTreeIsFormat: Format[BinaryTree] = lazyFormat({
implicit val formatLeaf = asSingleton(Leaf());
- implicit val formatSplit : Format[Split] = asProduct2((x : BinaryTree, y : BinaryTree) => Split(x, y))((s : Split) => (s.left, s.right));
+ implicit val formatSplit: Format[Split] =
+ asProduct2((x: BinaryTree, y: BinaryTree) => Split(x, y))((s: Split) => (s.left, s.right));
asUnion[BinaryTree](classOf[Leaf], classOf[Split]);
})
- implicit val arbitraryTree : Arbitrary[BinaryTree] = {
- def sizedArbitraryTree(n : Int) : Gen[BinaryTree] =
- if (n <= 1) value(Leaf());
- else for (i <- choose(1, n - 1);
- left <- sizedArbitraryTree(i);
- right <- sizedArbitraryTree(n - i)
- ) yield (Split(left, right));
- Arbitrary[BinaryTree](sized(sizedArbitraryTree(_ : Int)))
+ implicit val arbitraryTree: Arbitrary[BinaryTree] = {
+ def sizedArbitraryTree(n: Int): Gen[BinaryTree] =
+ if (n <= 1) (Leaf(): Gen[BinaryTree])
+ else
+ for {
+ i <- choose(1, n - 1);
+ left <- sizedArbitraryTree(i);
+ right <- sizedArbitraryTree(n - i)
+ } yield (Split(left, right));
+ Arbitrary[BinaryTree](sized(sizedArbitraryTree(_: Int)))
}
- object SomeEnum extends Enumeration{
+ object SomeEnum extends Enumeration {
val Foo, Bar, Baz = Value;
def items: List[Value] = Foo :: Bar :: Baz :: Nil
}
@@ -222,7 +259,7 @@ object FormatTests extends Properties("Formats"){
formatSpec[Option[String]]("Option[String]");
formatSpec[(Option[String], String)]("(Option[String], String)");
formatSpec[Option[Option[Int]]]("Option[Option[Int]]");
-
+
formatSpec[List[String]]("List[String]");
formatSpec[List[(String, Int)]]("List[(String, Int)]");
formatSpec[List[Option[Int]]]("List[Option[Int]]");
@@ -263,6 +300,6 @@ object FormatTests extends Properties("Formats"){
formatSpec[BinaryTree]("BinaryTree");
formatSpec[(BinaryTree, BinaryTree)]("(BinaryTree, BinaryTree)")
-
+
formatSpec[SomeEnum.Value]("SomeEnum.Value")
}
=====================================
examples/bt/BT.scala
=====================================
@@ -4,58 +4,58 @@ import sbinary._
import DefaultProtocol._
import Operations._
- // Binary tree data types that will be
- // created and converted to/from byte arrays
+// Binary tree data types that will be
+// created and converted to/from byte arrays
sealed abstract class BT;
-case class Bin(left : BT, right : BT) extends BT;
-case class Leaf(label : String) extends BT;
+case class Bin(left: BT, right: BT) extends BT;
+case class Leaf(label: String) extends BT;
- // Custom protocol for (de)serializing binary trees
+// Custom protocol for (de)serializing binary trees
object MyProtocol extends DefaultProtocol {
- implicit object BTFormat extends Format[BT]{
- def reads(in : Input) = read[Byte](in) match {
- case 0 => Bin(reads(in), reads(in));
- case _ => Leaf(read[String](in))
- }
-
- def writes(out : Output, value : BT) = value match {
- case Bin(left, right) => write[Byte](out, 0); writes(out, left); writes(out, right);
- case Leaf(label) => write[Byte](out, 1); write(out, label);
- }
- }
+ implicit object BTFormat extends Format[BT] {
+ def reads(in: Input) = read[Byte](in) match {
+ case 0 => Bin(reads(in), reads(in));
+ case _ => Leaf(read[String](in))
+ }
+
+ def writes(out: Output, value: BT) = value match {
+ case Bin(left, right) => write[Byte](out, 0); writes(out, left); writes(out, right);
+ case Leaf(label) => write[Byte](out, 1); write(out, label);
+ }
+ }
}
- // test runner
+// test runner
object main {
- def main(args : Array[String]) : Unit = {
- val input = List("foo", "bar", "baz")
- println(input)
+ def main(args: Array[String]): Unit = {
+ val input = List("foo", "bar", "baz")
+ println(input)
- val binary = toByteArray(input)
- println(showArray(binary))
+ val binary = toByteArray(input)
+ println(showArray(binary))
- val normalAgain = fromByteArray[List[String]](binary)
- println(normalAgain)
+ val normalAgain = fromByteArray[List[String]](binary)
+ println(normalAgain)
- toFile(input)(new java.io.File("foo.bin"))
- println(fromFile[List[String]](new java.io.File("foo.bin")))
+ toFile(input)(new java.io.File("foo.bin"))
+ println(fromFile[List[String]](new java.io.File("foo.bin")))
- import MyProtocol._
+ import MyProtocol._
- val someTree = Bin(Leaf("foo"), Bin(Leaf("bar"), Leaf("baz")))
- println(someTree)
+ val someTree = Bin(Leaf("foo"), Bin(Leaf("bar"), Leaf("baz")))
+ println(someTree)
- val someTreeInAByteArray = toByteArray[BT](someTree)
- println(showArray(someTreeInAByteArray))
+ val someTreeInAByteArray = toByteArray[BT](someTree)
+ println(showArray(someTreeInAByteArray))
- val theSameTree = fromByteArray[BT](someTreeInAByteArray)
- println(theSameTree)
- }
- // utility methods for printing a byte array
- def showArray(b: Array[Byte]) = b.map(showByte).mkString(" ")
- def showByte(b: Byte) = pad( ((b+256) % 256).toHexString )
- def pad(s: String) = if(s.length == 1) "0" + s else s
-}
\ No newline at end of file
+ val theSameTree = fromByteArray[BT](someTreeInAByteArray)
+ println(theSameTree)
+ }
+ // utility methods for printing a byte array
+ def showArray(b: Array[Byte]) = b.map(showByte).mkString(" ")
+ def showByte(b: Byte) = pad(((b + 256) % 256).toHexString)
+ def pad(s: String) = if (s.length == 1) "0" + s else s
+}
=====================================
project/Dependencies.scala
=====================================
@@ -0,0 +1,19 @@
+import sbt._
+
+object Dependencies {
+ val scala210 = "2.10.7"
+ val scala211 = "2.11.12"
+ val scala212 = "2.12.11"
+ val scala213 = "2.13.1"
+
+ val scalacheck = "org.scalacheck" %% "scalacheck" % "1.14.3"
+ def scalaXmlDep(scalaV: String): List[ModuleID] =
+ CrossVersion.partialVersion(scalaV) match {
+ case Some((2, minor)) if minor <= 10 =>
+ Nil
+ case Some((2, 11 | 12)) =>
+ List("org.scala-lang.modules" %% "scala-xml" % "1.0.6")
+ case _ =>
+ List("org.scala-lang.modules" %% "scala-xml" % "1.2.0")
+ }
+}
=====================================
project/Fmpp.scala
=====================================
@@ -0,0 +1,42 @@
+import sbt._
+import Keys._
+
+object Fmpp {
+
+ /*** Templating **/
+ lazy val fmpp = TaskKey[Seq[File]]("fmpp")
+ lazy val fmppOptions = SettingKey[Seq[String]]("fmpp-options")
+ lazy val FmppConfig = config("fmpp") hide
+
+ lazy val templateSettings = fmppConfig(Test) ++ fmppConfig(Compile) ++ templateBase
+ lazy val templateBase = Seq(
+ libraryDependencies += "net.sourceforge.fmpp" % "fmpp" % "0.9.16" % FmppConfig,
+ ivyConfigurations += FmppConfig,
+ fmppOptions := "--ignore-temporary-files" :: Nil,
+ fullClasspath in FmppConfig := update.value select configurationFilter(FmppConfig.name) map Attributed.blank
+ )
+
+ import sbt.io.Path._
+ def fmppConfig(c: Configuration): Seq[Setting[_]] =
+ inConfig(c)(
+ Seq(
+ sourceGenerators += fmpp,
+ fmpp := fmppTask.value,
+ mappings in packageSrc ++= managedSources.value pair relativeTo(sourceManaged.value)
+ )
+ )
+ lazy val fmppTask =
+ Def.task {
+ val cp = (fullClasspath in FmppConfig).value
+ val r = (runner in fmpp).value
+ val srcRoot = baseDirectory.value / "src" / "main" / "fmpp"
+ val sources = (srcRoot ** "*.scala").get
+ val output = sourceManaged.value
+ val args = fmppOptions.value
+ val s = streams.value
+ IO.delete(output)
+ val arguments = "-U" +: "all" +: "-S" +: srcRoot.getAbsolutePath +: "-O" +: output.getAbsolutePath +: (args ++ sources.getPaths)
+ r.run("fmpp.tools.CommandLine", cp.files, arguments, s.log) // .foreach(sys.error)
+ (output ** "*.scala").get
+ }
+}
=====================================
project/HouseRulesPlugins.scala
=====================================
@@ -0,0 +1,58 @@
+import sbt._
+import Keys._
+import bintray.BintrayPlugin
+import bintray.BintrayPlugin.autoImport._
+
+object HouseRulesPlugin extends AutoPlugin {
+ override def requires = plugins.JvmPlugin && BintrayPlugin
+ override def trigger = allRequirements
+
+ override def buildSettings: Seq[Def.Setting[_]] = baseBuildSettings
+ override def projectSettings: Seq[Def.Setting[_]] = baseSettings
+
+ lazy val baseBuildSettings: Seq[Def.Setting[_]] = Seq(
+ bintrayOrganization := Some("sbt"),
+ bintrayRepository := "maven-releases",
+ )
+
+ lazy val baseSettings: Seq[Def.Setting[_]] = Seq(
+ bintrayPackage := (ThisBuild / bintrayPackage).value,
+ bintrayRepository := (ThisBuild / bintrayRepository).value,
+ scalacOptions ++= Seq("-encoding", "utf8"),
+ scalacOptions ++= Seq("-deprecation", "-feature", "-unchecked", "-Xlint"),
+ scalacOptions += "-language:higherKinds",
+ scalacOptions += "-language:implicitConversions",
+ scalacOptions ++= "-Xfuture".ifScala213OrMinus.value.toList,
+ scalacOptions += "-Xlint",
+ scalacOptions ++= "-Xfatal-warnings"
+ .ifScala(v => {
+ sys.props.get("sbt.build.fatal") match {
+ case Some(_) => java.lang.Boolean.getBoolean("sbt.build.fatal")
+ case _ => v == 12
+ }
+ })
+ .value
+ .toList,
+ scalacOptions ++= "-Yinline-warnings".ifScala211OrMinus.value.toList,
+ scalacOptions ++= "-Yno-adapted-args".ifScala212OrMinus.value.toList,
+ scalacOptions += "-Ywarn-dead-code",
+ scalacOptions += "-Ywarn-numeric-widen",
+ scalacOptions += "-Ywarn-value-discard",
+ scalacOptions ++= "-Ywarn-unused-import".ifScala(v => 11 <= v && v <= 12).value.toList
+ ) ++ Seq(Compile, Test).flatMap(
+ c => scalacOptions in (c, console) --= Seq("-Ywarn-unused-import", "-Xlint")
+ )
+
+ private def scalaPartV = Def setting (CrossVersion partialVersion scalaVersion.value)
+
+ private implicit final class AnyWithIfScala[A](val __x: A) {
+ def ifScala(p: Long => Boolean) =
+ Def setting (scalaPartV.value collect { case (2, y) if p(y) => __x })
+ def ifScalaLte(v: Long) = ifScala(_ <= v)
+ def ifScalaGte(v: Long) = ifScala(_ >= v)
+ def ifScala211OrMinus = ifScalaLte(11)
+ def ifScala211OrPlus = ifScalaGte(11)
+ def ifScala212OrMinus = ifScalaLte(12)
+ def ifScala213OrMinus = ifScalaLte(13)
+ }
+}
=====================================
project/SBinaryProject.scala deleted
=====================================
@@ -1,64 +0,0 @@
- import sbt._
- import Keys._
-
-object SBinaryProject extends Build
-{
- lazy val root = Project("root", file(".")) settings( aux("SBinary Parent") : _*) aggregate(core, treeExample)
- lazy val core = Project("core", file("core")) settings(coreSettings : _*)
- lazy val treeExample = Project("examples", file("examples") / "bt") settings( aux("SBinary Tree Example") : _*) dependsOn(core)
-
- lazy val commonSettings: Seq[Setting[_]] = Seq(
- organization := "org.scala-tools.sbinary",
- version := "0.4.2",
- scalaVersion := "2.11.0-M4",
- crossVersion := CrossVersion.full,
- includeTestDependencies <<= scalaVersion(_.startsWith("2.10."))
- )
-
- lazy val includeTestDependencies = SettingKey[Boolean]("include-test-dependencies")
- lazy val scalaCheck = libraryDependencies <++= includeTestDependencies( incl =>
- if(incl)
- List("org.scalacheck" %% "scalacheck" % "1.10.0" % "test")
- else
- Nil
- )
- lazy val coreSettings = commonSettings ++ template ++ Seq(
- name := "SBinary",
- scalaCheck,
- libraryDependencies <++= scalaVersion(scalaXmlDep),
- unmanagedResources in Compile <+= baseDirectory map { _ / "LICENSE" }
- )
- def aux(nameString: String) = commonSettings ++ Seq( publish := (), name := nameString )
-
- def scalaXmlDep(scalaV: String): List[ModuleID] =
- if(scalaV.startsWith("2.11.")) List("org.scala-lang.modules" %% "scala-xml" % "1.0-RC2") else Nil
-
- /*** Templating **/
-
- lazy val fmpp = TaskKey[Seq[File]]("fmpp")
- lazy val fmppOptions = SettingKey[Seq[String]]("fmpp-options")
- lazy val fmppConfig = config("fmpp") hide
-
- lazy val template = fmppConfig(Test) ++ fmppConfig(Compile) ++ templateBase
- lazy val templateBase = Seq(
- libraryDependencies += "net.sourceforge.fmpp" % "fmpp" % "0.9.14" % fmppConfig.name,
- ivyConfigurations += fmppConfig,
- fmppOptions := "--ignore-temporary-files" :: Nil,
- fullClasspath in fmppConfig <<= update map { _ select configurationFilter(fmppConfig.name) map Attributed.blank }
- )
-
- def fmppConfig(c: Configuration): Seq[Setting[_]] = inConfig(c)(Seq(
- sourceGenerators <+= fmpp(x => x),
- fmpp <<= fmppTask,
- scalaSource <<= (baseDirectory, configuration) { (base,c) => base / (Defaults.prefix(c.name) + "src") },
- mappings in packageSrc <<= (managedSources, sourceManaged) map { (srcs, base) => srcs x relativeTo(base) },
- sources <<= managedSources(x => x)
- ))
- lazy val fmppTask =
- (fullClasspath in fmppConfig, runner in fmpp, unmanagedSources, scalaSource, sourceManaged, fmppOptions, streams) map { (cp, r, sources, srcRoot, output, args, s) =>
- IO.delete(output)
- val arguments = "-U" +: "all" +: "-S" +: srcRoot.getAbsolutePath +: "-O" +: output.getAbsolutePath +: (args ++ sources.getPaths)
- toError(r.run("fmpp.tools.CommandLine", cp.files, arguments, s.log))
- (output ** "*.scala").get
- }
-}
=====================================
project/build.properties
=====================================
@@ -1 +1 @@
-sbt.version=0.12.4
+sbt.version=1.3.9
=====================================
project/plugins.sbt
=====================================
@@ -0,0 +1,5 @@
+addSbtPlugin("org.foundweekends" % "sbt-bintray" % "0.5.6")
+addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.0.0")
+addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.3.0")
+addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.6.1")
+addSbtPlugin("com.eed3si9n" % "sbt-nocomma" % "0.1.0")
View it on GitLab: https://salsa.debian.org/java-team/scala-tools-sbinary/-/commit/c5f9e4f7c49deef55c4574b09b00fc3fd6ee9fe6
--
View it on GitLab: https://salsa.debian.org/java-team/scala-tools-sbinary/-/commit/c5f9e4f7c49deef55c4574b09b00fc3fd6ee9fe6
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261117/daf3b4dc/attachment.htm>
More information about the pkg-java-commits
mailing list