Imported Upstream version 1.1.1
[platform/upstream/iotivity.git] / resource / csdk / connectivity / lib / libcoap-4.1.1 / prng.h
1 /* prng.h -- Pseudo Random Numbers
2  *
3  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8
9 /**
10  * @file prng.h
11  * @brief Pseudo Random Numbers
12  */
13
14 #ifndef _COAP_PRNG_H_
15 #define _COAP_PRNG_H_
16
17 #include "config.h"
18
19 /**
20  * @defgroup prng Pseudo Random Numbers
21  * @{
22  */
23
24 #ifndef WITH_CONTIKI
25 #include <stdlib.h>
26
27 /**
28  * Fills \p buf with \p len random bytes. This is the default
29  * implementation for prng().  You might want to change prng() to use
30  * a better PRNG on your specific platform.
31  */
32 static inline int coap_prng_impl(unsigned char *buf, size_t len)
33 {
34     while (len--)
35         *buf++ = rand() & 0xFF;
36     return 1;
37 }
38 #else /* WITH_CONTIKI */
39 #include <string.h>
40
41 /**
42  * Fills \p buf with \p len random bytes. This is the default
43  * implementation for prng().  You might want to change prng() to use
44  * a better PRNG on your specific platform.
45  */
46 static inline int
47 contiki_prng_impl(unsigned char *buf, size_t len)
48 {
49     unsigned short v = random_rand();
50     while (len > sizeof(v))
51     {
52         memcpy(buf, &v, sizeof(v));
53         len -= sizeof(v);
54         buf += sizeof(v);
55         v = random_rand();
56     }
57
58     memcpy(buf, &v, len);
59     return 1;
60 }
61
62 #define prng(Buf,Length) contiki_prng_impl((Buf), (Length))
63 #define prng_init(Value) random_init((unsigned short)(Value))
64 #endif /* WITH_CONTIKI */
65
66 #ifndef prng
67 /**
68  * Fills \p Buf with \p Length bytes of random data.
69  *
70  * @hideinitializer
71  */
72 #define prng(Buf,Length) coap_prng_impl((Buf), (Length))
73 #endif
74
75 #ifndef prng_init
76 /**
77  * Called to set the PRNG seed. You may want to re-define this to
78  * allow for a better PRNG.
79  *
80  * @hideinitializer
81  */
82 #define prng_init(Value) srand((unsigned long)(Value))
83 #endif
84
85 /** @} */
86
87 #endif /* _COAP_PRNG_H_ */