summaryrefslogtreecommitdiffstats
path: root/sal/osl/w32/random.cxx
blob: ce495a8e3dc482b3cfb11b2ea03b36597d8ddf64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#if !defined _CRT_RAND_S
#define _CRT_RAND_S
#endif

#include <stdlib.h>
#include <memory.h>

#include <oslrandom.h>

int osl_get_system_random_data(char* buffer, size_t desired_len)
{
    unsigned int val;

    /* if unaligned fill to alignment */
    if(reinterpret_cast<uintptr_t>(buffer) & 3)
    {
        size_t len = 4 - (reinterpret_cast<size_t>(buffer) & 3);

        if(len > desired_len)
        {
            len = desired_len;
        }
        if(rand_s(&val))
        {
            return 0;
        }
        memcpy(buffer, &val, len);
        buffer += len;
        desired_len -= len;
    }
    /* fill directly into the buffer as long as we can */
    while(desired_len >= 4)
    {
        if(rand_s(reinterpret_cast<unsigned int*>(buffer)))
        {
            return 0;
        }
        else
        {
            buffer += 4;
            desired_len -= 4;
        }
    }
    /* deal with the partial int reminder to fill */
    if(desired_len)
    {
        if(rand_s(&val))
        {
            return 0;
        }
        memcpy(buffer, &val, desired_len);
    }
    return 1;
}


/* vim:set shiftwidth=4 softtabstop=4 expandtab: */