Skip to content

nixberg/chacha-rng-swift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swift

ChaCha

ChaCha-based RandomNumberGenerator for Swift. Compatible with Rust’s rand_chacha.

Usage

CSRNG

You should almost certainly use SystemRandomNumberGenerator instead.

import ChaCha

var rng = ChaCha() // ChaCha8, random seed, stream: 0.

SIMD2.random(in: 0..<1234, using: &rng)

CSPRNG

var rng = ChaCha(seed: .zero) // Seeded ChaCha8, stream: 0.

Int.random(in: 0..<1234, using: &rng) // 1032

Fill ArraySlice

var rng = ChaCha(rounds: .twenty, seed: .zero, stream: 0)

var array = [UInt8](repeating: 0, count: 4)
rng.fill(&array[...]) // [118, 184, 224, 173]

Generate Array

var rng = ChaCha(rounds: .twenty, seed: .zero, stream: 0)

let array: [UInt8] = rng.generateArray(count: 4) // [118, 184, 224, 173]

Append

To a MutableDataProtocol or RangeReplaceableCollection:

var rng = ChaCha(rounds: .twenty, seed: .zero, stream: 0)

var array: [UInt8] = [0]
rng.append(to: &array, count: 4) // [0, 118, 184, 224, 173]