MCPcopy Create free account
hub / github.com/Effect-TS/effect / make

Function make

packages/effect/src/Crypto.ts:213–279  ·  view source on GitHub ↗
(
  impl: {
    readonly randomBytes: (size: number) => Uint8Array
    readonly digest: (
      algorithm: DigestAlgorithm,
      data: Uint8Array
    ) => Effect.Effect<Uint8Array, PlatformError.PlatformError>
  }
)

Source from the content-addressed store, hash-verified

211 * @since 4.0.0
212 */
213export const make = (
214 impl: {
215 readonly randomBytes: (size: number) => Uint8Array
216 readonly digest: (
217 algorithm: DigestAlgorithm,
218 data: Uint8Array
219 ) => Effect.Effect<Uint8Array, PlatformError.PlatformError>
220 }
221): Crypto => {
222 const randomBytesUnsafe = impl.randomBytes
223
224 const randomBytes: Crypto["randomBytes"] = (size) => Effect.map(validateSize("randomBytes", size), randomBytesUnsafe)
225
226 const readUint53 = (bytes: Uint8Array): number =>
227 ((bytes[0] & 0x1f) * 2 ** 48) + (bytes[1] * 2 ** 40) + (bytes[2] * 2 ** 32) +
228 (bytes[3] * 2 ** 24) + (bytes[4] * 2 ** 16) + (bytes[5] * 2 ** 8) + bytes[6]
229
230 const nextDoubleUnsafe = (): number => readUint53(randomBytesUnsafe(7)) / 2 ** 53
231
232 const nextIntUnsafe = (): number => {
233 while (true) {
234 const bytes = randomBytesUnsafe(7)
235 const value = readUint53(bytes)
236 if ((bytes[0] & 0x20) === 0) {
237 return value + Number.MIN_SAFE_INTEGER
238 }
239 if (value < Number.MAX_SAFE_INTEGER) {
240 return value + 1
241 }
242 }
243 }
244
245 return Crypto.of({
246 [TypeId]: TypeId,
247 randomBytes,
248 nextDoubleUnsafe,
249 nextIntUnsafe,
250 digest: impl.digest,
251 random: Effect.sync(() => nextDoubleUnsafe()),
252 randomBoolean: Effect.sync(() => nextDoubleUnsafe() > 0.5),
253 randomInt: Effect.sync(() => nextIntUnsafe()),
254 randomBetween: (min, max) => Effect.sync(() => nextDoubleUnsafe() * (max - min) + min),
255 randomIntBetween(min, max, options) {
256 const extra = options?.halfOpen === true ? 0 : 1
257 return Effect.sync(() => {
258 const minInt = Math.ceil(min)
259 const maxInt = Math.floor(max)
260 return Math.floor(nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt
261 })
262 },
263 randomShuffle: (elements) =>
264 Effect.sync(() => {
265 const buffer = Array.from(elements)
266 for (let i = buffer.length - 1; i >= 1; i = i - 1) {
267 const index = Math.min(i, Math.floor(nextDoubleUnsafe() * (i + 1)))
268 const value = buffer[i]!
269 buffer[i] = buffer[index]!
270 buffer[index] = value

Callers

nothing calls this directly

Calls 6

nextDoubleUnsafeFunction · 0.70
nextIntUnsafeFunction · 0.70
ofMethod · 0.65
syncMethod · 0.45
succeedMethod · 0.45

Tested by

no test coverage detected