|
| 1 | +# cython: language_level=3 |
| 2 | +# cython: boundscheck=False |
| 3 | +# cython: wraparound=False |
| 4 | +# cython: cdivision=True |
| 5 | +""" |
| 6 | +TrueEntropy - Cython Accelerated Core Functions |
| 7 | +
|
| 8 | +This module provides Cython-accelerated versions of performance-critical |
| 9 | +functions in TrueEntropy. The speedup comes from: |
| 10 | +
|
| 11 | +1. Static typing - No Python object overhead |
| 12 | +2. Direct C memory access - No bounds checking |
| 13 | +3. Native C operations - No Python interpreter overhead |
| 14 | +
|
| 15 | +To build: |
| 16 | + pip install cython |
| 17 | + python setup.py build_ext --inplace |
| 18 | +
|
| 19 | +Or with pip: |
| 20 | + pip install -e ".[cython]" |
| 21 | +""" |
| 22 | + |
| 23 | +from libc.stdlib cimport malloc, free |
| 24 | +from libc.string cimport memcpy |
| 25 | +from cpython.bytes cimport PyBytes_FromStringAndSize |
| 26 | + |
| 27 | +import struct |
| 28 | + |
| 29 | + |
| 30 | +# ============================================================================= |
| 31 | +# Fast Byte Operations |
| 32 | +# ============================================================================= |
| 33 | + |
| 34 | +def xor_bytes_fast(bytes data, bytes key): |
| 35 | + """ |
| 36 | + Fast XOR of two byte strings using C-level operations. |
| 37 | + |
| 38 | + This is ~10-50x faster than the pure Python version for large inputs. |
| 39 | + |
| 40 | + Args: |
| 41 | + data: The data to XOR |
| 42 | + key: The key (will be repeated if shorter than data) |
| 43 | + |
| 44 | + Returns: |
| 45 | + XOR'd bytes |
| 46 | + """ |
| 47 | + cdef: |
| 48 | + Py_ssize_t data_len = len(data) |
| 49 | + Py_ssize_t key_len = len(key) |
| 50 | + unsigned char* result |
| 51 | + const unsigned char* d = data |
| 52 | + const unsigned char* k = key |
| 53 | + Py_ssize_t i |
| 54 | + |
| 55 | + if data_len == 0: |
| 56 | + return b"" |
| 57 | + |
| 58 | + if key_len == 0: |
| 59 | + return data |
| 60 | + |
| 61 | + result = <unsigned char*>malloc(data_len) |
| 62 | + if result == NULL: |
| 63 | + raise MemoryError("Failed to allocate memory") |
| 64 | + |
| 65 | + try: |
| 66 | + for i in range(data_len): |
| 67 | + result[i] = d[i] ^ k[i % key_len] |
| 68 | + |
| 69 | + return PyBytes_FromStringAndSize(<char*>result, data_len) |
| 70 | + finally: |
| 71 | + free(result) |
| 72 | + |
| 73 | + |
| 74 | +def bytes_to_int_fast(bytes data): |
| 75 | + """ |
| 76 | + Convert bytes to integer using C-level operations. |
| 77 | + |
| 78 | + Args: |
| 79 | + data: Bytes to convert (big-endian) |
| 80 | + |
| 81 | + Returns: |
| 82 | + Integer value |
| 83 | + """ |
| 84 | + cdef: |
| 85 | + Py_ssize_t n = len(data) |
| 86 | + const unsigned char* d = data |
| 87 | + unsigned long long result = 0 |
| 88 | + Py_ssize_t i |
| 89 | + |
| 90 | + # Handle up to 8 bytes (64 bits) |
| 91 | + if n > 8: |
| 92 | + n = 8 |
| 93 | + |
| 94 | + for i in range(n): |
| 95 | + result = (result << 8) | d[i] |
| 96 | + |
| 97 | + return result |
| 98 | + |
| 99 | + |
| 100 | +def int_to_bytes_fast(unsigned long long value, int length): |
| 101 | + """ |
| 102 | + Convert integer to bytes using C-level operations. |
| 103 | + |
| 104 | + Args: |
| 105 | + value: Integer to convert |
| 106 | + length: Number of bytes in output |
| 107 | + |
| 108 | + Returns: |
| 109 | + Big-endian bytes |
| 110 | + """ |
| 111 | + cdef: |
| 112 | + unsigned char* result |
| 113 | + int i |
| 114 | + |
| 115 | + result = <unsigned char*>malloc(length) |
| 116 | + if result == NULL: |
| 117 | + raise MemoryError("Failed to allocate memory") |
| 118 | + |
| 119 | + try: |
| 120 | + for i in range(length - 1, -1, -1): |
| 121 | + result[i] = value & 0xFF |
| 122 | + value >>= 8 |
| 123 | + |
| 124 | + return PyBytes_FromStringAndSize(<char*>result, length) |
| 125 | + finally: |
| 126 | + free(result) |
| 127 | + |
| 128 | + |
| 129 | +# ============================================================================= |
| 130 | +# Fast Random Number Scaling |
| 131 | +# ============================================================================= |
| 132 | + |
| 133 | +def scale_to_range_fast(unsigned long long value, int a, int b): |
| 134 | + """ |
| 135 | + Scale a random value to a range [a, b] with rejection sampling. |
| 136 | + |
| 137 | + This avoids modulo bias by rejecting values outside the valid range. |
| 138 | + |
| 139 | + Args: |
| 140 | + value: Random value (0 to 2^64-1) |
| 141 | + a: Lower bound (inclusive) |
| 142 | + b: Upper bound (inclusive) |
| 143 | + |
| 144 | + Returns: |
| 145 | + Tuple of (scaled_value, needs_retry) |
| 146 | + """ |
| 147 | + cdef: |
| 148 | + unsigned long long range_size |
| 149 | + unsigned long long threshold |
| 150 | + int bits_needed |
| 151 | + unsigned long long mask |
| 152 | + unsigned long long scaled |
| 153 | + |
| 154 | + if a > b: |
| 155 | + raise ValueError("a must be <= b") |
| 156 | + |
| 157 | + if a == b: |
| 158 | + return (a, False) |
| 159 | + |
| 160 | + range_size = <unsigned long long>(b - a + 1) |
| 161 | + |
| 162 | + # Calculate bits needed |
| 163 | + bits_needed = 0 |
| 164 | + temp = range_size - 1 |
| 165 | + while temp > 0: |
| 166 | + bits_needed += 1 |
| 167 | + temp >>= 1 |
| 168 | + |
| 169 | + # Create mask |
| 170 | + mask = (1ULL << bits_needed) - 1 |
| 171 | + |
| 172 | + # Apply mask |
| 173 | + scaled = value & mask |
| 174 | + |
| 175 | + # Check if in range |
| 176 | + if scaled < range_size: |
| 177 | + return (a + <int>scaled, False) |
| 178 | + else: |
| 179 | + return (0, True) # Needs retry |
| 180 | + |
| 181 | + |
| 182 | +def uniform_float_fast(unsigned long long value): |
| 183 | + """ |
| 184 | + Convert 64-bit integer to float in [0.0, 1.0). |
| 185 | + |
| 186 | + Args: |
| 187 | + value: 64-bit random value |
| 188 | + |
| 189 | + Returns: |
| 190 | + Float in [0.0, 1.0) |
| 191 | + """ |
| 192 | + # 2^64 = 18446744073709551616 |
| 193 | + return <double>value / 18446744073709551616.0 |
| 194 | + |
| 195 | + |
| 196 | +# ============================================================================= |
| 197 | +# Fast Fisher-Yates Shuffle (indices only) |
| 198 | +# ============================================================================= |
| 199 | + |
| 200 | +def fisher_yates_indices(int n, random_func): |
| 201 | + """ |
| 202 | + Generate Fisher-Yates shuffle indices. |
| 203 | + |
| 204 | + Args: |
| 205 | + n: Length of sequence to shuffle |
| 206 | + random_func: Function that returns random int in range [0, i] |
| 207 | + |
| 208 | + Returns: |
| 209 | + List of swap pairs [(i, j), ...] |
| 210 | + """ |
| 211 | + cdef: |
| 212 | + int i, j |
| 213 | + list swaps = [] |
| 214 | + |
| 215 | + for i in range(n - 1, 0, -1): |
| 216 | + j = random_func(0, i) |
| 217 | + if i != j: |
| 218 | + swaps.append((i, j)) |
| 219 | + |
| 220 | + return swaps |
| 221 | + |
| 222 | + |
| 223 | +# ============================================================================= |
| 224 | +# Module Info |
| 225 | +# ============================================================================= |
| 226 | + |
| 227 | +def is_accelerated(): |
| 228 | + """Check if Cython acceleration is available.""" |
| 229 | + return True |
| 230 | + |
| 231 | + |
| 232 | +def get_version(): |
| 233 | + """Get Cython module version.""" |
| 234 | + return "1.0.0" |
0 commit comments