; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: OS independent part of different random number generators.
;
;  Target OS: Any
;
;  Dependencies: memory.asm, strlib.asm
;
;  Notes:
;
;_________________________________________________________________________________________

module "Random library"


; Cryptographically strong random generator. Possibly slow. OS dependent implementation.
; Returns:
;   eax - pointer to memory block of random bytes.

interface GetRandomBytes, .count




proc GetRandomString, .size
begin
        pushad

        mov     eax, [.size]
        shr     eax, 1
        adc     eax, 0
        jz      .error

        stdcall GetRandomBytes, eax
        jc      .error

        mov     esi, eax
        mov     edi, eax

        stdcall StrNew
        mov     ebx, eax

        mov     ecx, [.size]
        xor     eax, eax

.loop:
        lodsb
        mov     dl, al
        and     al, $0f
        shr     dl, 4

        cmp     al,$0a
        sbb     al,$69
        das

        stdcall StrCharCat, ebx, eax

        dec     ecx
        jz      .string_ok

        mov     al, dl
        cmp     al,$0a
        sbb     al,$69
        das

        stdcall StrCharCat, ebx, eax

        dec     ecx
        jnz     .loop

.string_ok:
        stdcall FreeMem, edi

        mov     [esp+4*regEAX], ebx
        clc
        popad
        return

.error:
        stc
        popad
        return

endp



include '%TargetOS%/random.asm'



endmodule