Skip to content

Commit

Permalink
add Random.nextLong(Long)
Browse files Browse the repository at this point in the history
  • Loading branch information
xuwei-k committed Feb 24, 2024
1 parent 12350e9 commit d5c6497
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
Expand Up @@ -25,6 +25,7 @@ import scala.collection.{
mutable => m
}
import scala.runtime.{Tuple2Zipped, Tuple3Zipped}
import scala.util.Random
import scala.{collection => c}

/** The collection compatibility API */
Expand Down Expand Up @@ -351,6 +352,9 @@ private[compat] trait PackageShared {

implicit def toOptionCompanionExtension(fact: Option.type): OptionCompanionExtensionMethods =
new OptionCompanionExtensionMethods(fact)

implicit def toRandomExtensions(self: Random): RandomExtensions =
new RandomExtensions(self)
}

class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal {
Expand Down
@@ -0,0 +1,36 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package scala.collection.compat

import scala.util.Random

final class RandomExtensions(private val self: Random) extends AnyVal {
def nextLong(n: Long): Long = {
require(n > 0, "n must be positive")

var offset = 0L
var _n = n

while (_n >= Integer.MAX_VALUE) {
val bits = self.nextInt(2)
val halfn = _n >>> 1
val nextn =
if ((bits & 2) == 0) halfn
else _n - halfn
if ((bits & 1) == 0)
offset += _n - nextn
_n = nextn
}
offset + self.nextInt(_n.toInt)
}
}
34 changes: 34 additions & 0 deletions compat/src/test/scala/test/scala/util/RandomTest.scala
@@ -0,0 +1,34 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package test.scala.util

import org.junit.Assert._
import org.junit.Test
import scala.collection.compat._
import scala.util.Random
import test.scala.collection.AssertThrown

class RandomTest extends AssertThrown {
@Test
def nextLong(): Unit = {
val rand = new Random(12345)

assertEquals(4896762128577075113L, rand.nextLong(Long.MaxValue))
assertEquals(2005076556L, rand.nextLong(Int.MaxValue))
assertEquals(0L, rand.nextLong(1L))

assertThrows[IllegalArgumentException](rand.nextLong(0L))
assertThrows[IllegalArgumentException](rand.nextLong(-2L))
assertThrows[IllegalArgumentException](rand.nextLong(Long.MinValue))
}
}

0 comments on commit d5c6497

Please sign in to comment.