Skip to content

Instantly share code, notes, and snippets.

@soc
Created March 29, 2012 11:44
Show Gist options
  • Select an option

  • Save soc/2236359 to your computer and use it in GitHub Desktop.

Select an option

Save soc/2236359 to your computer and use it in GitHub Desktop.
final class SBigInt private(final val signum: Int, final private[math] val arr: Array[Int]) {
...
/**
* Standard Serialization would work, but we have to make sure
* that we sanitize the array to verify our invariant of no leading
* “zeroes” in our magnitude.
*
* Otherwise all methods depending on it will be broken.
*
* TODO: It probably makes sense to write an independent sanitizing method,
* which can be shared and call it from here...
*/
@throws(classOf[java.io.IOException]) @throws(classOf[java.lang.ClassNotFoundException])
private def readObject(in: java.io.ObjectInputStream): Unit = {
@inline def setField(name: String, value: Any): Unit = {
val field = this.getClass.getDeclaredField(name)
field.setAccessible(true)
field.set(this, value)
field.setAccessible(false)
}
var sign = in.readByte
if(sign > 1 || sign < -1)
throw new java.io.StreamCorruptedException
setField("signum", sign)
var inArr = in.readObject.asInstanceOf[Array[UInt]]
if(sign == 0 && inArr.length != 0)
throw new java.io.StreamCorruptedException
setField("arr", stripLeadingZeroes(inArr))
}
@throws(classOf[java.io.ObjectStreamException])
private def readReplace(): Object = {
if(signum == 0) return SBigInt.Zero
else this
}
@throws(classOf[java.io.IOException])
private def writeObject(out: java.io.ObjectOutputStream): Unit = {
out.writeByte(signum)
out.writeObject(arr)
out.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment