iotivity 0.9.0
[platform/upstream/iotivity.git] / resource / csdk / 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 #include <ocrandom.h>
19
20 /** 
21  * @defgroup prng Pseudo Random Numbers
22  * @{
23  */
24
25 #ifndef WITH_CONTIKI
26 #include <stdlib.h>
27
28 /**
29  * Fills \p buf with \p len random bytes. This is the default
30  * implementation for prng().  You might want to change prng() to use
31  * a better PRNG on your specific platform.
32  */
33 static inline int
34 coap_prng_impl(unsigned char *buf, size_t len) {
35 #if 0
36   while (len--)
37     *buf++ = rand() & 0xFF;
38 #endif
39   OCFillRandomMem(buf, len);
40   return 1;
41 }
42 #else /* WITH_CONTIKI */
43 #include <string.h>
44
45 /**
46  * Fills \p buf with \p len random bytes. This is the default
47  * implementation for prng().  You might want to change prng() to use
48  * a better PRNG on your specific platform.
49  */
50 static inline int
51 contiki_prng_impl(unsigned char *buf, size_t len) {
52   unsigned short v = random_rand();
53   while (len > sizeof(v)) {
54     memcpy(buf, &v, sizeof(v));
55     len -= sizeof(v);
56     buf += sizeof(v);
57     v = random_rand();
58   }
59
60   memcpy(buf, &v, len);
61   return 1;
62 }
63
64 #define prng(Buf,Length) contiki_prng_impl((Buf), (Length))
65 #define prng_init(Value) random_init((unsigned short)(Value))
66 #endif /* WITH_CONTIKI */
67
68 #ifndef prng
69 /** 
70  * Fills \p Buf with \p Length bytes of random data. 
71  * 
72  * @hideinitializer
73  */
74 #define prng(Buf,Length) coap_prng_impl((Buf), (Length))
75 #endif
76
77 #ifndef prng_init
78 /** 
79  * Called to set the PRNG seed. You may want to re-define this to
80  * allow for a better PRNG.
81  *
82  * @hideinitializer
83  */
84 #define prng_init(Value) OCSeedRandom()//srand((unsigned long)(Value))
85 #endif
86
87 /** @} */
88
89 #endif /* _COAP_PRNG_H_ */