xref: /3.0.3-GA/platform/include/platform/random.h (revision fc705f79)
1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2014 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17#pragma once
18#ifdef WIN32
19#include <windows.h>
20#include <wincrypt.h>
21#endif
22
23#include <platform/visibility.h>
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
29#ifdef WIN32
30    typedef HCRYPTPROV cb_rand_t;
31#else
32    typedef int cb_rand_t;
33#endif
34    /*
35     * Upon errors windows users should look at GetLastError, and
36     * others should look at errno if they want more detailed
37     * information.
38     */
39
40    /**
41     * Open a random generator
42     *
43     * @param handle pointer to the handle to open
44     * @param return 0 on success -1 on failure
45     */
46    PLATFORM_PUBLIC_API
47    int cb_rand_open(cb_rand_t *handle);
48
49    /**
50     * Get random bytes from the random generator
51     *
52     * @param handle the handle used to read data from
53     * @param dest where to store the random bytes
54     * @param nbytes the number of bytes to get
55     * @param return 0 on success -1 on failure
56     */
57    PLATFORM_PUBLIC_API
58    int cb_rand_get(cb_rand_t handle, void *dest, size_t nbytes);
59
60    /**
61     * Close a random generator
62     *
63     * @param handle The random generator to close
64     */
65    PLATFORM_PUBLIC_API
66    int cb_rand_close(cb_rand_t handle);
67
68#ifdef __cplusplus
69}
70
71namespace Couchbase {
72    class RandomGeneratorProvider;
73
74    class RandomGenerator {
75    public:
76        PLATFORM_PUBLIC_API
77        RandomGenerator(bool);
78
79        PLATFORM_PUBLIC_API
80        ~RandomGenerator();
81
82        PLATFORM_PUBLIC_API
83        uint64_t next(void);
84
85        PLATFORM_PUBLIC_API
86        bool getBytes(void *dest, size_t size);
87
88        PLATFORM_PUBLIC_API
89        const RandomGeneratorProvider *getProvider(void) const;
90
91    private:
92        bool shared;
93        RandomGeneratorProvider *provider;
94    };
95}
96
97#endif
98