RandomKit is a Swift framework that makes random data generation simple and easy.

Overview

RandomKit

RandomKit is a Swift framework that makes random data generation simple and easy.

Build Status

Branch Status
master Build Status

Installation

Compatibility

  • Platforms:
    • macOS 10.9+
    • iOS 8.0+
    • watchOS 2.0+
    • tvOS 9.0+
    • Linux
  • Xcode 8.0+
  • Swift 3.0.2+ & 4.0

RandomKit is possibly also compatible with FreeBSD, Android, and Windows (under Cygwin) but has not been tested for those platforms.

Install Using Swift Package Manager

The Swift Package Manager is a decentralized dependency manager for Swift.

  1. Add the project to your Package.swift.

    import PackageDescription
    
    let package = Package(
        name: "MyAwesomeProject",
        dependencies: [
            .Package(url: "https://github.com/nvzqz/RandomKit.git",
                     majorVersion: 5)
        ]
    )
  2. Import the RandomKit module.

    import RandomKit

Install Using CocoaPods

CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.

  1. Add the project to your Podfile.

    use_frameworks!
    
    pod 'RandomKit', '~> 5.2.3'

    If you want to be on the bleeding edge, replace the last line with:

    pod 'RandomKit', :git => 'https://github.com/nvzqz/RandomKit.git'
  2. Run pod install and open the .xcworkspace file to launch Xcode.

  3. Import the RandomKit framework.

    import RandomKit

Install Using Carthage

Carthage is a decentralized dependency manager for Objective-C and Swift.

  1. Add the project to your Cartfile.

    github "nvzqz/RandomKit"
    
  2. Run carthage update and follow the additional steps in order to add RandomKit to your project.

  3. Import the RandomKit framework.

    import RandomKit

Benchmark

Various components of RandomKit can be easily benchmarked by running benchmark.sh.

./benchmark.sh [FLAGS] [PROTOCOLS]

Use the --help flag for information regarding how to use it.

Note: The default count is 10000000, which is A LOT if using the --array flag. This can be changed by passing an argument into --count or -c.

Usage

Try it out for yourself! Download the repo and open 'RandomKit.playground'.

RandomGenerator

The RandomGenerator protocol defines basic methods for generating primitive values and randomizing a buffer.

All provided types that conform to RandomGenerator have a static default value that can be passed as an inout argument to generation functions.

let value = Int.random(using: &Xoroshiro.default)

Available Generators

  • ARC4Random

    • Because the symbols for the arc4random family of functions aren't exported with Foundation on Linux and other platforms, they're dynamically loaded at runtime.
  • DeviceRandom

    • Reads from "/dev/random" or "/dev/urandom" as its source.
  • MersenneTwister

  • Xoroshiro

  • Xorshift

  • XorshiftStar

  • ChaCha

SeedableRandomGenerator

SeedableRandomGenerator is for types that can be seeded with some associated Seed type.

RandomBytesGenerator

The RandomBytesGenerator protocol is for types that specialize in generating a specific type that fills up a number of bytes. For example, MersenneTwister specializes in generating UInt64 while Xorshift generates UInt32 values.

Thread Safety

For single-threaded programs, it is safe to use a global generator instance such as Xoroshiro.default as a source of randomness.

For multi-threaded programs, the thread-local instances should be used. This allows for different threads to use their own separate random generators without a shared mutable state.

In the following example, randomGenerator is unique to each thread.

let randomBytes = Xoroshiro.withThreadLocal { randomGenerator in
    return [UInt8](randomCount: 1000, using: &randomGenerator)
}

Thread-local generators are deallocated upon thread exit, so there's no need to worry about cleanup.

It's recommended to not call withThreadLocal(_:) or get the threadLocal pointer each individual time it's needed. Retrieving the thread-local instance incurs avoidable overhead.

// Bad
let value = Int.random(using: &Xoroshiro.threadLocal.pointee)
array.shuffle(using: &Xoroshiro.threadLocal.pointee)

// Good
let threadLocal = Xoroshiro.threadLocal
let value = Int.random(using: &threadLocal.pointee)
array.shuffle(using: &threadLocal.pointee)

// Better
Xoroshiro.withThreadLocal { randomGenerator in
    let value = Int.random(using: &randomGenerator)
    array.shuffle(using: &randomGenerator)
}

As a shortcut, you can even apply a function directly as a parameter.

let value = Xoroshiro.withThreadLocal(Int.random)

Prior to v4.4.0, thread safety could be achieved by instantiating a new seeded instance of a given RandomGenerator type. The problem with this is that unnecessary seeding occurs each time. With this, the generator is seeded once and can then be reused at later points.

Shortcuts to the reseeding version of a generator are also available:

Xoroshiro.withThreadLocalReseeding {
    ...
}

Which is way better than writing:

ReseedingRandomGenerator.withThreadLocal(createdWith: { Xoroshiro.reseeding }) {
    ...
}

Protocols

RandomKit is very protocol-oriented, which gives it the ability to be very flexible and modular.

Random

A protocol for types that can generate random values using a RandomGenerator.

RandomInRange

A protocol for types that can generate optional random values within a range using a RandomGenerator.

Int.random(in: 0 ..< 0, using: &randomGenerator) // nil

RandomInClosedRange

A protocol for types that can generate random values within a closed range using a RandomGenerator.

Int.random(in: -100 ... 100, using: &randomGenerator) // -79

RandomToValue

A protocol for types that can generate random values from a base value to another value, noninclusive.

The base value for integers is 0. This means that calling random(to:using:) on a negative value will yield a random negative value or zero whereas a positive value will yield a random positive value or zero.

If value == randomBase, value will be returned for random(to:using:).

Int.random(to:  2, using: &randomGenerator)  // Either 0 or 1
Int.random(to:  0, using: &randomGenerator)  // Always 0
Int.random(to: 32, using: &randomGenerator)  // 15
Int.random(to: -5, using: &randomGenerator)  // -3

RandomThroughValue

A protocol for types that can generate random values from a base value through another value, inclusive.

The same rules regarding the base value of RandomToValue apply to RandomThroughValue.

RandomRetrievable

A protocol for types whose instances can have random elements retrieved.

["Bob", "Cindy", "May", "Charles", "Javier"].random(using: &randomGenerator)  // "Charles"

"Hello".characters.random(using: &randomGenerator)  // "e"

Some Foundation types like NSArray conform to this protocol.

RandomRetrievableInRange

A protocol for types whose instances can have random elements retrieved from within a Range.

[20, 37, 42].random(in: 1 ..< 3, using: &randomGenerator)  // Either 37 or 42

Shuffleable

A protocol for types whose elements can be shuffled.

// Array
[1, 2, 3, 4, 5].shuffled(using: &randomGenerator)  // [3, 4, 1, 5, 2]

// Dictionary
["a": 1, "b": 2, "c": 3].shuffled(using: &randomGenerator)  // ["a": 3, "b": 1, "c": 2]

The mutable counterpart of shuffled(using:) is shuffle(using:).

For better Array shuffling performance, consider shuffling in-place with shuffle(using:).

UniqueShuffleable

Similar to Shuffleable, except no element is ever in its initial position.

Swift Types

Integers

All of Swift's native integer types conform to the Random- protocols.

The random(using:) function creates an integer of any value. As a result, negative values can result for signed integers.

Int.random(using: &randomGenerator)               // An Int within Int.min and Int.max
Int.random(in: 10...20, using: &randomGenerator)  // An Int within 10 and 20

To create a positive signed integer, use random(to:using:) or random(through:using:).

Int.random(to: 1000, using: &randomGenerator)     // 731
Int.random(through: 10, using: &randomGenerator)  // 4

Signed integers can be created from any range, without danger of overflow.

Int.random(in: (.min + 1000)...(.max - 200), using: &randomGenerator)  // 5698527899712144154

Floating Point Numbers

Generate a random floating point value from within a range or 0.0...1.0 by default.

Double.random(using: &randomGenerator)                 //  0.9813615573117475
Double.random(in:  -10...10, using: &randomGenerator)  // -4.03042337718197
Float.random(in:   -10...10, using: &randomGenerator)  //  5.167088
Float80.random(in: -10...10, using: &randomGenerator)  // -3.63204542399198874

All FloatingPoint types can also conform to RandomInClosedRange out-of-the-box.

Bool

Bool.random(using:) has a 50/50 chance of being true.

If you need different probability, there's also random(withWeight:using:), which has 1 in weight chance of being true.

String, Character, and UnicodeScalar

String, Character, and UnicodeScalar generate values within " "..."~" by default.

$w1" String.random(ofLength: 10, in: "A"..."z", using: &randomGenerator) // "poUtXJIbv[" Character.random(using: &randomGenerator) // "#" Character.random(in: "A"..."z", using: &randomGenerator) // "s" ">
String.random(ofLength: 10, using: &randomGenerator)                 // "}+[=Ng>$w1"
String.random(ofLength: 10, in: "A"..."z", using: &randomGenerator)  // "poUtXJIbv["

Character.random(using: &randomGenerator)                 // "#"
Character.random(in: "A"..."z", using: &randomGenerator)  // "s"

Arrays

An array of random values can be generated for types conforming to Random with init(randomCount:using:).

Similar initializers exist for all other Random- protocols.

let randoms = Array<Int>(randomCount: 100, using: &randomGenerator)  // [8845477344689834233, -957454203475087100, ...]

For types conforming to UnsafeRandom, a faster alternative is init(unsafeRandomCount:using:). This initializer fills the buffer directly rather than using random(using:).

let unsafeRandoms = Array<Int>(unsafeRandomCount: 100, using: &randomGenerator)  // [759709806207883991, 4618491969012429761, ...]
Arrays Benchmark

A benchmark of generating 1000 random Int arrays of 10000 count:

Generator Time (in seconds)
Xoroshiro 0.0271
Xorshift 0.0568
XorshiftStar 0.0319
ChaCha 0.2027
MersenneTwister 0.0432
ARC4Random 0.2416
DeviceRandom 5.3348

Note: Results may vary due to various factors.

This same benchmark can be run with:

./benchmark.sh --all-generators --array 10000 --count 1000

Foundation Types

Date

A random Date can be generated between two Date or TimeInterval values.

The default random(using:) function returns a Date within Date.distantPast and Date.distantFuture.

Date.random(using: &randomGenerator)  // "Aug 28, 2006, 3:38 AM"
Date.random(in: Date.distantPast...Date(), using: &randomGenerator)  // "Feb 7, 472, 5:40 AM"

Decimal

The Decimal type conforms to various Random- protocols.

The random(using:) function returns a Decimal between 0 and 1 by default.

Decimal.random(using: &randomGenerator)                  // 0.87490000409886706715888973957833129437
Decimal.random(in: 0.0...10.0, using: &randomGenerator)  // 6.5464639772070720738747790627821299859

NSNumber

A random number can be generated from within an integer or double range, or 0...100 by default.

NSNumber.random(using: &randomGenerator)                 // 79
NSNumber.random(in: -50...100, using: &randomGenerator)  // -27
NSNumber.random(in: 100...200, using: &randomGenerator)  // 149.6156950363926

Cocoa and UIKit Types

NSColor and UIColor

A random color can be generated, with or without random alpha.

NSColor.random(using: &randomGenerator)              // r 0.694 g 0.506 b 0.309 a 1.0
NSColor.random(alpha: true, using: &randomGenerator) // r 0.859 g 0.57  b 0.409 a 0.047

UIColor.random(using: &randomGenerator)              // r 0.488 g 0.805 b 0.679 a 1.0
UIColor.random(alpha: true, using: &randomGenerator) // r 0.444 g 0.121 b 0.602 a 0.085

CoreGraphics Types

CGFloat

Because CGFloat conforms to FloatingPoint, it conforms to RandomInClosedRange just like how Double and Float do.

CGFloat.random(using: &randomGenerator)               // 0.699803650379181
CGFloat.random(in: 0...100, using: &randomGenerator)  // 43.27969591675319

CGPoint

A random point can be generated from within ranges for x and y.

CGPoint.random(using: &randomGenerator) // {x 70.093 y 95.721}
CGPoint.random(xRange: 0...200, yRange: 0...10, using: &randomGenerator) // {x 73.795 y 0.991}

CGSize

A random size can be generated from within ranges for width and height.

CGSize.random(using: &randomGenerator) // {w 3.744  h 35.932}
CGSize.random(widthRange: 0...50, heightRange: 0...400, using: &randomGenerator) // {w 38.271 h 239.636}

CGRect

A random rectangle can be generated from within ranges for x, y, width, and height.

CGRect.random(using: &randomGenerator)  // {x 3.872  y 46.15  w 8.852  h 20.201}
CGRect.random(xRange: 0...50,
              yRange: 0...100,
              widthRange: 0...25,
              heightRange: 0...10,
              using: &randomGenerator)  // {x 13.212 y 79.147 w 20.656 h 5.663}

CGVector

A random vector can be generated from within ranges for dx and dy.

CGVector.random(using: &randomGenerator) // {dx 13.992 dy 89.376}
CGVector.random(dxRange: 0...50, dyRange: 0...10, using: &randomGenerator) // {dx 35.224 dy 13.463}

Extra

BigInt

RandomKit extensions for Károly's BigInt library are available in RandomKitBigInt.

License

RandomKit and its assets are released under the MIT License. Assets can be found in the assets branch.

Parts of this project utilize code written by Matt Gallagher and, in conjunction with the MIT License, are licensed with that found here.

Comments
  • Xcode 9/iOS 11 generating errors

    Xcode 9/iOS 11 generating errors

    Hi guys! I have been compiling on of my projects in Xcode 9 (beta) and there's a few errors being generated by RandomKit. any chance you can have a look at that?

    More specifically: screenshot 2017-07-05 09 45 02

    Thanks in advance!

    opened by danipralea 18
  • RandomKit does not compile with Xcode 9.0

    RandomKit does not compile with Xcode 9.0

    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomRawRepresentable.swift:41:20: warning: redeclaration of associated type 'RawValue' from protocol 'RawRepresentable' is better expressed as a 'where' clause on the protocol
        associatedtype RawValue: Random
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
        
    Swift.RawRepresentable:96:20: note: 'RawValue' declared here
        associatedtype RawValue
                       ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/Seedable.swift:131:37: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func reseeding<R: RandomGenerator>(with reseeder: R) -> ReseedingRandomGenerator<Self, R> {
                                        ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/Seedable.swift:131:75: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func reseeding<R: RandomGenerator>(with reseeder: R) -> ReseedingRandomGenerator<Self, R> {
                                                                              ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomThroughValue.swift:74:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> RandomsThroughValue<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomThroughValue.swift:74:108: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(through value: Self, using randomGenerator: inout R) -> RandomsThroughValue<Self, R> {
                                                                                                               ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomThroughValue.swift:79:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, through value: Self, using randomGenerator: inout R) -> LimitedRandomsThroughValue<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomThroughValue.swift:79:130: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, through value: Self, using randomGenerator: inout R) -> LimitedRandomsThroughValue<Self, R> {
                                                                                                                                     ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomToValue.swift:74:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> RandomsToValue<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomToValue.swift:74:103: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(to value: Self, using randomGenerator: inout R) -> RandomsToValue<Self, R> {
                                                                                                          ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomToValue.swift:79:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, to value: Self, using randomGenerator: inout R) -> LimitedRandomsToValue<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomToValue.swift:79:125: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, to value: Self, using randomGenerator: inout R) -> LimitedRandomsToValue<Self, R> {
                                                                                                                                ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/ThreadLocal.swift:138:48: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func threadLocalReseeding<R: RandomGenerator>(
                                                   ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/ThreadLocal.swift:141:10: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        ) -> UnsafeMutablePointer<ReseedingRandomGenerator<Self, R>> {
             ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/ThreadLocal.swift:177:52: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func withThreadLocalReseeding<R: RandomGenerator, T>(
                                                       ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomGenerator/ThreadLocal.swift:180:17: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
            _ body: (inout ReseedingRandomGenerator<Self, R>) throws -> T
                    ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/Random.swift:53:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(using randomGenerator: inout R) -> Randoms<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/Random.swift:53:87: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(using randomGenerator: inout R) -> Randoms<Self, R> {
                                                                                          ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/Random.swift:58:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, using randomGenerator: inout R) -> LimitedRandoms<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/Random.swift:58:109: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, using randomGenerator: inout R) -> LimitedRandoms<Self, R> {
                                                                                                                ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInRange.swift:81:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(in range: Range<Self>, using randomGenerator: inout R) -> RandomsWithinRange<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInRange.swift:81:110: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(in range: Range<Self>, using randomGenerator: inout R) -> RandomsWithinRange<Self, R> {
                                                                                                                 ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInRange.swift:86:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, in range: Range<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinRange<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInRange.swift:86:132: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, in range: Range<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinRange<Self, R> {
                                                                                                                                       ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInClosedRange.swift:63:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> RandomsWithinClosedRange<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInClosedRange.swift:63:122: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> RandomsWithinClosedRange<Self, R> {
                                                                                                                             ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInClosedRange.swift:68:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinClosedRange<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomInClosedRange.swift:68:144: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, in closedRange: ClosedRange<Self>, using randomGenerator: inout R) -> LimitedRandomsWithinClosedRange<Self, R> {
                                                                                                                                                   ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithMaxWidth.swift:53:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(withMaxWidth width: Int, using randomGenerator: inout R) -> RandomsWithMaxWidth<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithMaxWidth.swift:53:112: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(withMaxWidth width: Int, using randomGenerator: inout R) -> RandomsWithMaxWidth<Self, R> {
                                                                                                                   ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithMaxWidth.swift:58:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, withMaxWidth width: Int, using randomGenerator: inout R) -> LimitedRandomsWithMaxWidth<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithMaxWidth.swift:58:134: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, withMaxWidth width: Int, using randomGenerator: inout R) -> LimitedRandomsWithMaxWidth<Self, R> {
                                                                                                                                         ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithExactWidth.swift:53:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(withExactWidth width: Int, using randomGenerator: inout R) -> RandomsWithExactWidth<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithExactWidth.swift:53:114: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(withExactWidth width: Int, using randomGenerator: inout R) -> RandomsWithExactWidth<Self, R> {
                                                                                                                     ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithExactWidth.swift:58:35: warning: redundant conformance constraint 'R': 'RandomGenerator'
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, withExactWidth width: Int, using randomGenerator: inout R) -> LimitedRandomsWithExactWidth<Self, R> {
                                      ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Types/RandomWithExactWidth.swift:58:136: note: conformance constraint 'R': 'RandomGenerator' inferred from type here
        public static func randoms<R: RandomGenerator>(limitedBy limit: Int, withExactWidth width: Int, using randomGenerator: inout R) -> LimitedRandomsWithExactWidth<Self, R> {
                                                                                                                                           ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:237:64: error: binary operator '&-' cannot be applied to two 'Self' operands
            return range.lowerBound &+ random(to: range.upperBound &- range.lowerBound, using: &randomGenerator)
                                                  ~~~~~~~~~~~~~~~~ ^  ~~~~~~~~~~~~~~~~
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:237:64: note: expected an argument list of type '(Self, Self)'
            return range.lowerBound &+ random(to: range.upperBound &- range.lowerBound, using: &randomGenerator)
                                                                   ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:270:45: error: binary operator '&+' cannot be applied to operands of type 'Self' and 'Int'
                return _randomGreater(to: value &+ 1, using: &randomGenerator)
                                          ~~~~~ ^  ~
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:270:45: note: expected an argument list of type '(Self, Self)'
                return _randomGreater(to: value &+ 1, using: &randomGenerator)
                                                ^
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:293:44: error: binary operator '&-' cannot be applied to two 'Self' operands
            let bound = closedRange.upperBound &- closedRange.lowerBound
                        ~~~~~~~~~~~~~~~~~~~~~~ ^  ~~~~~~~~~~~~~~~~~~~~~~
    /Users/nachosoto/dev/ios/AsyncImageView/Carthage/Checkouts/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:293:44: note: expected an argument list of type '(Self, Self)'
            let bound = closedRange.upperBound &- closedRange.lowerBound
                                               ^
    
    opened by NachoSoto 10
  • [WIP] Migrate to Swift 4.1

    [WIP] Migrate to Swift 4.1

    TODO:

    • [x] Deal with IndexDistance deprecation (it's always Int now)
    • [ ] Deal with other deprecation warnings
    • [x] Wait for compiler crash (I found https://bugs.swift.org/browse/SR-6797 while working on this).
    • [x] Tests passing
    • [ ] Wait for Xcode 9.3
    • [ ] Update .travis.yml
    opened by NachoSoto 8
  • Crashes in simulator and iOS9

    Crashes in simulator and iOS9

    Somehow since the last Xcode update (8.1) randomkit crashes for me when I run my app in the Simulator and also on iOS9 devices.I'm using the latest version 2.1.0 through CocoaPods. It worked before but somehow since the last update something changed/

    The crash occurs in this method on the return statement:

    extension UInt: RandomWithMax, RandomWithMin, RandomToValue, RandomThroughValue, RandomWithinRange, RandomWithinClosedRange {
    
        fileprivate var _resigned: UInt {
            return UInt(UIntMax(self)._resigned)
        }
    
    }
    

    More info: http://crashes.to/s/ac28a42158e

    Any help would be appreciated.

    opened by hufkens 8
  • Copyright violation

    Copyright violation

    This repository uses the Xoroshiro, MersenneTwister and possibly other implementations taken from Cocoa with Love, first featured from here:

    https://www.cocoawithlove.com/blog/2016/05/19/random-numbers.html

    As they appear in this repository, all copyright and credit has been removed from this code.

    You're required, as per the terms of the copyrights on the website and my github repository to keep the original copyright message. Please return the original copyright to these files and the top-level LICENSE file or remove the copied code which is currently used without license.

    opened by mattgallagher 4
  • Build errors on Xcode 9 beta 4 with Swift 3.2

    Build errors on Xcode 9 beta 4 with Swift 3.2

    image

    RandomKit/Extensions/Swift/Strideable+RandomKit.swift:48:1: Type 'String.UTF16Index' (aka 'String.Index') does not conform to protocol 'RandomInRange'
    
    RandomKit/Extensions/Swift/Strideable+RandomKit.swift:48:1: Type 'String.UTF16Index' (aka 'String.Index') does not conform to protocol 'RandomInClosedRange'
    
    RandomKit/Extensions/Swift/Strideable+RandomKit.swift:48:1: Type 'String.UTF16Index' (aka 'String.Index') does not conform to protocol 'RandomInRange'
    

    via cocoapods

    pod 'RandomKit', '5.2.0'
    
    opened by ldiqual 3
  • Generate random values using different distributions

    Generate random values using different distributions

    • a RandomDistribution enum to describe the type of distribution
    • a protocol RandomDistribuableType implemented by Double and Float
    • functions to generate random values using specific distributions
    opened by phimage 3
  • New pod version for swift 3.0

    New pod version for swift 3.0

    @nvzqz Now that Xcode 8 GM is out and that RandomKit is compatible with the latest version of swift 3.0, how about releasing a new version of the library and publish it on cocoapods? That'd make dependency management a lot easier :)

    opened by ldiqual 3
  • Consider supporting Xcode 10 / Swift 4.2

    Consider supporting Xcode 10 / Swift 4.2

    Currently building in Xcode 10 / Swift 4.2 results in a number of errors such as:

    Type 'UnsafeBufferPointer<Element>' does not conform to protocol 'RandomRetrievableInRange'

    in Collection+RandomKit.swift

    opened by DanielAsher 2
  • Does not compile with swift 4.1

    Does not compile with swift 4.1

    /Users/josanchez/prog/SecretSanta/App/Code/Pods/RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:84:17: Invalid redeclaration of 'uncheckedRandom(in:using:)'

    /Users/josanchez/prog/SecretSanta/App/Code/Pods/RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:90:73: Type 'Collection.IndexDistance' (aka 'Int') in conformance requirement does not refer to a generic parameter or associated type

    opened by buscarini 2
  • Build errors with Xcode 9 beta 5

    Build errors with Xcode 9 beta 5

    On 5.2.2 (via cocoapods):

    INFO [2017-08-08 11:13:36.61]: ▸ Signing /Users/distiller/Library/Developer/Xcode/DerivedData/Scoop-apzwymdrenvrifcyulsguqmakzdj/Build/Products/Debug-iphonesimulator/RxSwift/RxSwift.framework
    INFO [2017-08-08 11:13:36.61]: ▸ Building Pods/RandomKit [Debug]
    INFO [2017-08-08 11:13:36.61]: ▸ Check Dependencies
    INFO [2017-08-08 11:13:36.62]: ▸ Compiling ARC4Random.swift
    INFO [2017-08-08 11:13:36.63]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ARC4Random.swift:67:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.63]: ▸ return UInt16(extendingOrTruncating: random32())
    INFO [2017-08-08 11:13:36.63]: ▸                    ~~~~~~~~~^~~~~~~~~~~~
    INFO [2017-08-08 11:13:36.68]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ARC4Random.swift:76:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.68]: ▸ return UInt8(extendingOrTruncating: random32())
    INFO [2017-08-08 11:13:36.68]: ▸                    ^
    INFO [2017-08-08 11:13:36.77]: ▸ Compiling ChaCha.swift
    INFO [2017-08-08 11:13:36.78]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift:134:25: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.78]: ▸ _state.12 = UInt32(extendingOrTruncating: low)
    INFO [2017-08-08 11:13:36.78]: ▸                    ^
    INFO [2017-08-08 11:13:36.84]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift:135:25: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.84]: ▸ _state.13 = UInt32(extendingOrTruncating: low &>> 32)
    INFO [2017-08-08 11:13:36.84]: ▸                         ^
    INFO [2017-08-08 11:13:36.91]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift:136:25: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.91]: ▸ _state.14 = UInt32(extendingOrTruncating: high)
    INFO [2017-08-08 11:13:36.91]: ▸                         ^
    INFO [2017-08-08 11:13:36.95]: ▸ 2017-08-08 11:13:36.955 xcodebuild[1480:17340] Error Domain=IDETestOperationsObserverErrorDomain Code=14 "Test operation was canceled. If you believe this error represents a bug, please attach the log file at /var/folders/42/bp51_0vn1kv6lqhv0wmfjrqw0000gn/T/com.apple.dt.XCTest/IDETestRunSession-4BA227F8-1C2D-4764-96CF-6535D7354DF3/ScoopTests-2CB9ACA0-44E2-4AA0-9C74-3BC465ABC5A9/Session-ScoopTests-2017-08-08_111333-MOGaxv.log" UserInfo={NSLocalizedDescription=Test operation was canceled. If you believe this error represents a bug, please attach the log file at /var/folders/42/bp51_0vn1kv6lqhv0wmfjrqw0000gn/T/com.apple.dt.XCTest/IDETestRunSession-4BA227F8-1C2D-4764-96CF-6535D7354DF3/ScoopTests-2CB9ACA0-44E2-4AA0-9C74-3BC465ABC5A9/Session-ScoopTests-2017-08-08_111333-MOGaxv.log}
    INFO [2017-08-08 11:13:36.95]: ▸ Testing failed:
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Non-nominal type 'Self' does not support explicit initialization
    INFO [2017-08-08 11:13:36.95]: ▸ Binary operator '|' cannot be applied to operands of type 'Self' and 'Int'
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.95]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.96]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.96]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.96]: ▸ Argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.96]: ▸ Expression type 'Bool' is ambiguous without more context
    INFO [2017-08-08 11:13:36.96]: ▸ ** TEST FAILED **
    INFO [2017-08-08 11:13:36.96]: ▸ The following build commands failed:
    INFO [2017-08-08 11:13:36.96]: ▸ CompileSwiftSources normal i386 com.apple.xcode.tools.swift.compiler
    INFO [2017-08-08 11:13:36.96]: ▸ CompileSwift normal i386 /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ARC4Random.swift
    INFO [2017-08-08 11:13:36.96]: ▸ CompileSwift normal i386 /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift
    INFO [2017-08-08 11:13:36.96]: ▸ CompileSwift normal i386 /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift
    INFO [2017-08-08 11:13:36.96]: ▸ CompileSwift normal i386 /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift
    INFO [2017-08-08 11:13:36.96]: ▸ (5 failures)
    INFO [2017-08-08 11:13:36.97]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift:137:25: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:36.97]: ▸ _state.15 = UInt32(extendingOrTruncating: high &>> 32)
    INFO [2017-08-08 11:13:36.97]: ▸                         ^
    INFO [2017-08-08 11:13:37.02]: ▸ Compiling Integer+RandomKit.swift
    INFO [2017-08-08 11:13:37.02]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:580:20: non-nominal type 'Self' does not support explicit initialization
    INFO [2017-08-08 11:13:37.03]: ▸ let bits = Self(extendingOrTruncating: MemoryLayout<Self>.size * 8 - 1)
    INFO [2017-08-08 11:13:37.03]: ▸                         ^
    INFO [2017-08-08 11:13:37.03]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Extensions/Swift/Integer+RandomKit.swift:359:69: binary operator '|' cannot be applied to operands of type 'Self' and 'Int'
    INFO [2017-08-08 11:13:37.03]: ▸ return random(withMaxWidth: width, using: &randomGenerator) | (1 &<< Self(width - 1))
    INFO [2017-08-08 11:13:37.03]: ▸                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    INFO [2017-08-08 11:13:37.03]: ▸ Compiling RandomBytesGenerator.swift
    INFO [2017-08-08 11:13:37.03]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift:49:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:37.03]: ▸ return UInt32(extendingOrTruncating: randomBytes())
    INFO [2017-08-08 11:13:37.03]: ▸                                                                     ^
    INFO [2017-08-08 11:13:37.08]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift:58:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:37.08]: ▸ return UInt16(extendingOrTruncating: randomBytes())
    INFO [2017-08-08 11:13:37.08]: ▸                    ^
    INFO [2017-08-08 11:13:37.14]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift:67:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:37.14]: ▸ return UInt8(extendingOrTruncating: randomBytes())
    INFO [2017-08-08 11:13:37.14]: ▸                    ^
    INFO [2017-08-08 11:13:37.22]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift:90:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:37.23]: ▸ return UInt16(extendingOrTruncating: randomBytes())
    INFO [2017-08-08 11:13:37.23]: ▸                    ^
    INFO [2017-08-08 11:13:37.28]: ▸ ❌  /Users/distiller/scoop-ios/Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/RandomBytesGenerator.swift:99:20: argument labels '(extendingOrTruncating:)' do not match any available overloads
    INFO [2017-08-08 11:13:37.28]: ▸ return UInt8(extendingOrTruncating: randomBytes())
    INFO [2017-08-08 11:13:37.28]: ▸    
    
    opened by ldiqual 2
  • Xcscheme with xcode9.3

    Xcscheme with xcode9.3

    With Xcode9.3, If I change Show checkbox on scheme management window, Xcode make a little diff on xccheme files.

    I use this library by gitsubmodule + carthage and add xcodeproj to xcworkspace for application development. So this diff makes work repository state dirty. Please merge this.

    This PR includes my other PR (#56)

    opened by omochi 0
  • use Swift 4

    use Swift 4

    My environment

    macOS High Sierra 10.13.4 Xcode9.3

    Problem

    I just cloned master and got compile error below.

    /Users/omochi/github/omochi/RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:100:17: Invalid redeclaration of 'uncheckedRandom(in:using:)'
    /Users/omochi/github/omochi/RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:75:17: 'uncheckedRandom(in:using:)' previously declared here
    /Users/omochi/github/omochi/RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:106:73: Type 'Collection.IndexDistance' (aka 'Int') in conformance requirement does not refer to a generic parameter or associated type
    

    The lines with error is in macro section for Swift less than 4.1. And a xcodeproj set swift version to 3.

    Solution

    This PR changes Swift version from 3 to 4 and avoid this error.

    opened by omochi 0
  • Type 'Collection.IndexDistance' (aka 'Int') in conformance requirement does not refer to a generic parameter or associated type

    Type 'Collection.IndexDistance' (aka 'Int') in conformance requirement does not refer to a generic parameter or associated type

    When using the latest Xcode (9.3) I get this error:

    RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:90:73: Type 'Collection.IndexDistance' (aka 'Int') in conformance requirement does not refer to a generic parameter or associated type

    in:

    extension Collection where Self: RandomRetrievableInRange, IndexDistance: RandomToValue {
    
        /// Returns a random element of `self`, or `nil` if `self` is empty.
        public func uncheckedRandom<R: RandomGenerator>(in range: Range<Index>, using randomGenerator: inout R) -> Iterator.Element {
            let upper = range.upperBound
            let lower = range.lowerBound
            let elementIndex = IndexDistance.random(to: distance(from: lower, to: upper), using: &randomGenerator)
            return self[index(lower, offsetBy: elementIndex)]
        }
    
    }
    
    opened by hufkens 1
  • Invalid redeclaration of 'uncheckedRandom(in:using:)

    Invalid redeclaration of 'uncheckedRandom(in:using:)

    When using the latest Xcode (9.3) I get this error:

    RandomKit/Sources/RandomKit/Extensions/Swift/Collection+RandomKit.swift:84:17:` Invalid redeclaration of 'uncheckedRandom(in:using:)

    in:

    extension RandomRetrievableInRange where Self: Collection, Self.Index: RandomInRange, Self.IndexDistance: RandomToValue {
    
        /// Returns a random element in range without checking whether self or range is empty.
        public func uncheckedRandom<R: RandomGenerator>(in range: Range<Index>, using randomGenerator: inout R) -> Iterator.Element {
            return self[Index.uncheckedRandom(in: range, using: &randomGenerator)]
        }
    
    }
    
    opened by hufkens 3
  • Strategy for getting threadLocal pointer in each thread

    Strategy for getting threadLocal pointer in each thread

    From the docs: "It's recommended to not call withThreadLocal(_:) or get the threadLocal pointer each individual time it's needed. Retrieving the thread-local instance incurs avoidable overhead."

    That means right now I'm passing the: let threadLocal = Xoroshiro.threadLocal

    From the thread into my functions e.g.: init(_ theadLocalRandom: UnsafeMutablePointer<Xoroshiro>) { ..

    Is there a better way? Could RandomKit cache the UnsafeMutablePointer for each thread so that the application programmer didn't have to think about passing the thread owned pointer to each function called by the thread?

    Thanks for the awesome repository and software 👍

    opened by peheje 1
Releases(v5.2.3)
  • v5.2.3(Aug 8, 2017)

  • v5.2.2(Jul 28, 2017)

  • v5.2.1(Jul 28, 2017)

    Fixes

    • Removed String.UTF16Index conformances to RandomInRange and RandomInClosedRange for Swift 3.2 and after
      • This was enabled by an implementation based on Strideable, which the type no longer conforms to as of Swift 3.2
    Source code(tar.gz)
    Source code(zip)
  • v5.2.0(Jul 25, 2017)

    New Features

    • Made Trivial protocol public, allowing for library users to enable related optimizations for their own types
    • Added jump(count:) variant of jump() to Xoroshiro and XorshiftStar

    Improvements

    • Made jump() for XorshiftStar 20%+ faster
    • Made reseed(with:) for ChaCha 550%+ faster
      • init(seed:) is also faster due to reliance on reseed(with:)
    Source code(tar.gz)
    Source code(zip)
  • v5.1.0(Jun 24, 2017)

    Improvements

    • Initial Swift 4 compatibility :tada:
    • Improved time to access a thread-local generator by ~22%

    Changes

    • The ShiftOperations package is not required for Swift 3.2 and above
    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Jul 24, 2017)

    New Features

    • Added RandomRetrievable and RandomRetrievableInRange protocols (see 793e473e4a7d21a6777f131c5bf47fc6f0907f73)
    • Added SeedableFromSequence protocol (see 71094375cee72f99a6cadd1f1195c5dba6369da1)

    Changes

    • Removed random(using:) method that applied to all Sequence types
    • Removed Double random(within:using:) for TimeInterval ranges
    • Renamed RandomWithinRange and RandomWithinClosedRange to RandomInRange and RandomInClosedRange respectively
      • Functions that had a within: argument now use in:
    • SeedableFromRandomGenerator no longer requires Seedable
    • Changed ChaCha.Seed to [UInt32]
    Source code(tar.gz)
    Source code(zip)
  • v4.5.2(Apr 13, 2017)

  • v4.5.1(Apr 12, 2017)

  • v4.5.0(Apr 12, 2017)

    New Features

    • ChaCha random number generator (see: 9ca66ec72ce1d36e788e61d6793b149346bc9167)
    • Added reseed() method to SeedableFromOtherRandomGenerator

    Improvements

    • Make random Array initializers 5-10% faster
    Source code(tar.gz)
    Source code(zip)
  • v4.4.1(Mar 30, 2017)

  • v4.4.0(Mar 30, 2017)

    New Features

    • Added initializers to ReseedingRandomGenerator that take 1 or 0 arguments
      • If Reseeder conforms to SeedableFromOtherRandomGenerator, the reseeder is created from Reseeder.seeded (see a7d1b9ba06c93c01d02a9eb2fc3cb3d75fa8694a)
      • For Swift >= 3.1, if Reseeder is DeviceRandom or ARC4Random, the reseeder is just Reseeder.default (see da576454c4e13895d3607384cded36e275274544)
    • Added floating-point value generation methods for open, half open, and closed intervals (see 59182e5b25f3a3bed1cf88682af7727651d0a906)
    • Added thread-local random generators (see fde214b1c24b9d9d5bc6835aca4744a4331de195) :tada:

    Improvements

    • Made Double and Float random(using:) about 27 times faster (see 8799af7d6538f9da1835037e070d7afa66d99e29)
    • Made CGFloat.random(using:) faster , in turn making (NS|UI)Color.random(using:) faster (see a1b60d13e322abaaa6c6520c9c97cc1f96f56e9b)

    Fixes

    • Made randomClosed methods be truly on the [0, 1] interval (see 9b0d56bf4be175612b765b7f37b44e8115577789)
    Source code(tar.gz)
    Source code(zip)
  • v4.3.1(Mar 21, 2017)

    Changes

    • Random Dates are internally relative to timeIntervalSinceReferenceDate
    • Deprecated Date random(within:using:) for TimeInterval ranges (see 2d3075567acd0a7b9cbf4ab7bb1c0f87d1ae914e)
    Source code(tar.gz)
    Source code(zip)
  • v4.3.0(Mar 21, 2017)

    New Features

    • Added SeedableFromOtherRandomGenerator protocol
      • Allows for creating a RandomGenerator seeded from another RandomGenerator
    • Added ReseedingRandomGenerator struct for reseeding a base RandomGenerator with another after a certain number of bytes have been generated

    Improvements

    • Much faster Array random(using:) for Swift versions before 3.1

    Fixes

    • Fix compilation issues by not using API unavailable in Swift 3.1
    Source code(tar.gz)
    Source code(zip)
  • v4.2.0(Mar 15, 2017)

    Improvements

    • Made Array init(randomCount:using:) about 4 times faster for integer types by having it safely call init(unsafeRandomCount:using:) (see 350ce9da66889e4976a6a4794a44eef40ef010eb)

    • Made Dictionary shuffling faster (see 1977f86ee139c38b87613fb459179e3372cb63cf)

    Changes

    • Made Array init(unsafeRandomCount:using:) available for all element types, regardless if they conform to UnsafeRandom (see 71d4bc6b20b2b9634244ea15f273a87703bf5723)
    Source code(tar.gz)
    Source code(zip)
  • v4.1.0(Mar 15, 2017)

    New Features

    • Added seeded static variable to Xoroshiro, Xorshift, XorshiftStar, and MersenneTwister

    Improvements

    • Made the init(randomCount:using:) family of Array initializers significantly faster
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0(Mar 7, 2017)

    New Features

    • Added randoms(using:) methods to Random- types that return a sequence of random values according to the protocol's specialization
    • Added Bool.random(withWeight:using:) for probability
    • Added more random number generators:
      • Xorshift
      • XorshiftStar
    • NSMutableArray now conforms to Shuffleable and UniqueShuffleable
    • Added randomTuple(using:) global functions for creating tuples of up to six random elements
    • Added ShuffleableInRange and UniqueShuffleableInRange protocols

    Improvements

    • Much better init(randomCount:using:) performance for Array and Dictionary
    • Array shuffling is ten times faster
    • Much better performance for random(within:using:) for signed integers

    Changes

    • Changed RandomGenerator from an enum to a protocol type
      • As a result, there is no default generator, meaning a generator must be specified as a parameter
    • Random generation functions take a generic RandomGenerator type as an inout argument
    • Removed URL conformance to Random
    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Dec 10, 2016)

    New Features

    • Mersenne Twister random generator
    • All integer types conform to UnsafeRandom
    • Array(unsafeRandomCount:using:) for types conforming to UnsafeRandom
      • For much better performance with integer types, this should be used
    • Added a benchmark target that can be built with the Swift package manager
    • Created RandomWithMaxWidth and RandomWithExactWidth protocols
    • Added randomize(buffer:maxWidth:) and randomize(buffer:exactWidth:) methods to RandomGenerator

    Improvements

    • Generating RandomEnum values is significantly faster

    Fixes

    • UnicodeScalar now produces a uniform distribution when the Range or ClosedRange spans below 0xD7FF and above 0xE000

    Changes

    • Removed RandomDistribution (#29)
    • The devRandom and devURandom cases for RandomGenerator are now a single device case with a DeviceSource parameter
    • The arc4random case for RandomGenerator is now camel-cased arc4Random
    • Float80 extension now available for i386 and x86_64 architectures, not only for macOS
    • URL.random(fromValues:) now returns an Optional<URL>
    • Added ShiftOperations dependency
    • Uses Strideable instead of _Strideable
    Source code(tar.gz)
    Source code(zip)
  • v2.3.0(Nov 21, 2016)

    New Features

    • Date now conforms to RandomWithinRange
    • Made unicode scalar based string generation faster
    • Created UnsafeRandom, RandomEnum, RandomWithAll, and RandomRawRepresentable protocols

    Fixes

    • Fix which random generator is used for random String. Previously used the default instead of the one passed into the function.
    Source code(tar.gz)
    Source code(zip)
  • v2.2.1(Nov 8, 2016)

  • v2.2.0(Nov 7, 2016)

    Fixes

    • Random Int generation would rely on the size of UIntMax which was apparently not reliable (#28)

    Changes

    • If on Linux, Android, or Windows, the arc4random_buf function will be dynamically loaded, making the RandomGenerator.arc4random option more widely available
    • Removed default parameter for randomGenerator for the random(using:) function of Range types
    • Removed Random protocol dependency from Random- protocols
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Mar 12, 2017)

    Improvements

    • Range types now have random and random(using:) for when bounds are RandomWithinRange and RandomWithinClosedRange types
    • Improved performance for retrieving random elements from collections

    Fixes

    • Fixed random(within:) for unsigned integers
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Oct 28, 2016)

  • v1.6.0(Nov 21, 2015)

    New Features

    • randomGenerator() and randomSequence() for RandomType that return an infinite number of random values
    • New ShuffleType protocol for types that can return its values shuffled
      • Array and Dictionary can be shuffled
    • New RandomIntervalType protocol that allows for getting a random value within a closed interval
      • Random generators and sequences can be made within a closed interval
    • Getting random slices of an Array Phi Mage #10

    Changes

    • Deleted String.RandomLength and NSURL.RandomValues
    Source code(tar.gz)
    Source code(zip)
    RandomKit.framework.zip(2.05 MB)
  • v1.5.0(Oct 25, 2015)

    New Features

    • tvOS support :tv:
    • Added random generators to types in the CoreGraphics module as well as NSNumber
    • Removed the Foundation import for extensions of Swift types (only 'stdlib.h' is needed for arc4random)

    Changes

    • Relevant Objective-C types now conform to RandomType
    Source code(tar.gz)
    Source code(zip)
    RandomKit.framework.zip(1.45 MB)
  • v1.4.0(Oct 17, 2015)

    New Features

    • Random phone number generator
    • Random gender generator
    • Random English honorific generator according to type and gender
    • Another CGFloat random generator with interval parameter

    Changes

    • Faster Double, Float, and CGFloat generation
    • CGFloat value generation is now dependent on its NativeType
    Source code(tar.gz)
    Source code(zip)
    RandomKit.framework.zip(1.08 MB)
  • v1.3.0(Oct 15, 2015)

  • v1.2.0(Oct 13, 2015)

  • v1.1.0(Oct 12, 2015)

Owner
Nikolai Vazquez
conducts curses, breaks things, and uses the oxford comma
Nikolai Vazquez
A tiny generator of random data for swift

SwiftRandom SwiftRandom is a tiny help suite for generating random data such as Random human stuff like: names, gender, titles, tags, conversations Ra

Kan Yilmaz 559 Dec 29, 2022
Generates Heroku-style random project names in Swift

RandomProjectName.swift Generates Heroku-style random project names in Swift. Usage Just call String.randomProjectName(), and specify the optional suf

NLUDB 0 Dec 6, 2021
Generates a random photo after you click the button

Swift Random Photo Generator Generates a random photo after you click the button! Things you need to do ?? clone this repository git clone https://git

Tsuen Hsueh 2 Aug 16, 2022
*Random Smooth Cloudy* Noise for SwiftUI

Noise Generate random smooth cloudy noise. Install Swift Package .

Anton Heestand 7 Dec 7, 2022
An offline random passcode generator.

Passcode-Generator An offline random passcode generator. Usage Generates random passcode. Install Files and source code could be found in releases. Pr

Vaida 0 Dec 10, 2021
FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias. Storable protocol Actionable protocol Dispatch

Taiki Suzuki 123 Aug 23, 2022
It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.

Link Previewer for iOS, macOS, watchOS and tvOS It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.

Leonardo Cardoso 1.3k Jan 2, 2023
Framework for easily parsing your JSON data directly to Swift object.

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes

Mukesh 11 Oct 17, 2022
Swift 3 framework for accessing data in Event Registry

Swift 3 framework for accessing data in Event Registry

Pavel Pantus 8 Nov 1, 2016
A simple Pokedex app written in Swift that implements the PokeAPI, using Combine and data driven UI.

SwiftPokedex SwiftPokedex is a simple Pokedex app written by Viktor Gidlöf in Swift that implements the PokeAPI. For full documentation and implementa

Viktor G 26 Dec 14, 2022
Zip - A Swift framework for zipping and unzipping files. Simple and quick to use. Built on top of minizip.

Zip A Swift framework for zipping and unzipping files. Simple and quick to use. Built on top of minizip. Usage Import Zip at the top of the Swift file

Roy Marmelstein 2.3k Jan 3, 2023
Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Apple 833 Jan 3, 2023
swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

kelvin 4 Aug 14, 2022
Functional data types and functions for any project

Swiftx Swiftx is a Swift library containing functional abstractions and extensions to the Swift Standard Library. Swiftx is a smaller and simpler way

TypeLift 219 Aug 30, 2022
Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data.

Pigeon ?? Introduction Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data. It is heavily inspired by React Qu

Fernando Martín Ortiz 369 Dec 30, 2022
Measure the power output from a car or any moving vehicle from GPS data and weight

GPSDyno Measure the power output from a car or any moving vehicle from weight and GPS data of your iOS device. This is just a example project and shou

Marcelo Ferreira Barreto 0 Jan 7, 2022
Easier sharing of structured data between iOS applications and share extensions

XExtensionItem XExtensionItem is a tiny library allowing for easier sharing of structured data between iOS applications and share extensions. It is ta

Tumblr 86 Nov 23, 2022
Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings)

Swift .csv parser Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings). Par

Matthias 0 Dec 29, 2021
Easy CBOR encoding and decoding for iOS, macOS, tvOS and watchOS.

CBORCoding CBORCoding is a lightweight framework containing a coder pair for encoding and decoding Codable conforming types to and from CBOR document

Joe Newton 23 Nov 8, 2022