SPB Git

Repository Public

SystemRandom.swift 3.4 KB 82 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMath/SystemRandom.swift8// Module           : Qyvora Math9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Security4344/// The only entropy source of the engine: the operating system generator (`SecRandomCopyBytes`).45/// QYVORA never implements its own random generator.46public enum SystemRandom {47    /// Returns `count` random bytes. Traps if the system generator reports a failure:48    /// continuing with weak randomness would be worse than stopping.49    public static func bytes(_ count: Int) -> Bytes {50        var out = Bytes(repeating: 0, count: count)51        guard count > 0 else { return out }52        let status = out.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, count, $0.baseAddress!) }53        precondition(status == errSecSuccess, "system random generator failed")54        return out55    }5657    /// A uniform integer in `0..<upperBound` drawn from `bytes` (rejection sampling: no modulo bias).58    /// A bound that is not positive has a single possible answer, 0.59    public static func uniform(below upperBound: Int) -> Int {60        guard upperBound > 1 else { return 0 }61        let bound = UInt64(upperBound)62        // largest multiple of `bound` that fits: values at or above it are drawn again63        let limit = UInt64.max - (UInt64.max % bound + 1) % bound64        while true {65            let b = bytes(8)66            var value: UInt64 = 067            for byte in b { value = value << 8 | UInt64(byte) }68            if value <= limit { return Int(value % bound) }69        }70    }7172    /// The elements in a uniformly random order (Fisher–Yates with `uniform`).73    public static func permutation<T>(of items: [T]) -> [T] {74        var out = items75        guard out.count > 1 else { return out }76        for i in stride(from: out.count - 1, to: 0, by: -1) {77            out.swapAt(i, uniform(below: i + 1))78        }79        return out80    }81}82
Files main
Menu

Theme