Skip to content

Commit

Permalink
Make 30bit nanoseconds field always positive
Browse files Browse the repository at this point in the history
  • Loading branch information
jarmuszz committed Jul 10, 2024
1 parent fba395b commit 74323c6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 4 additions & 1 deletion msgpack/src/main/scala/fs2/data/msgpack/low/model.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ object MsgpackItem {
* @param combined [[nanoseconds]] and [[seconds]] combined into a signle 64-bit value
*/
case class Timestamp64(combined: Long) extends MsgpackItem {
val nanoseconds: Int = (combined >> 34).toInt // we are sure that (x: Long) >> 34 fits in an int
/* We are sure that (x: Long) >> 34 fits in an int but we also need to add a mask so that we don't end up with
* a negative number.
*/
val nanoseconds: Int = (0x000000003fffffffL & (combined >> 34)).toInt
val seconds: Long = combined & 0x00000003ffffffffL
}
case class Timestamp96(nanoseconds: Int, seconds: Long) extends MsgpackItem
Expand Down
9 changes: 9 additions & 0 deletions msgpack/src/test/scala/fs2/data/msgpack/ParserSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import scodec.bits.*
import weaver.SimpleIOSuite
import fs2.*
import fs2.data.msgpack.low.MsgpackItem

import java.nio.charset.StandardCharsets

object ParserSpec extends SimpleIOSuite {
Expand Down Expand Up @@ -323,4 +324,12 @@ object ParserSpec extends SimpleIOSuite {

(s1 ++ s2).compile.foldMonoid
}

pureTest("Timestamp64 nanoseconds field should always be positive") {
val nums = List(
0xFFFFFFFFFFFFFFFFL,
0b1000000000000000000000000000000000000000000000000000000000000000L
)
forEach(nums)(x => expect(MsgpackItem.Timestamp64(x).nanoseconds > 0))
}
}

0 comments on commit 74323c6

Please sign in to comment.