libcoap  4.1.2
prng.h
Go to the documentation of this file.
1 /*
2  * prng.h -- Pseudo Random Numbers
3  *
4  * Copyright (C) 2010-2011 Olaf Bergmann <bergmann@tzi.org>
5  *
6  * This file is part of the CoAP library libcoap. Please see README for terms
7  * of use.
8  */
9 
15 #ifndef _COAP_PRNG_H_
16 #define _COAP_PRNG_H_
17 
23 #if defined(WITH_POSIX) || (defined(WITH_LWIP) && !defined(LWIP_RAND))
24 #include <stdlib.h>
25 
31 static inline int
32 coap_prng_impl(unsigned char *buf, size_t len) {
33  while (len--)
34  *buf++ = rand() & 0xFF;
35  return 1;
36 }
37 #endif /* WITH_POSIX */
38 
39 #ifdef WITH_CONTIKI
40 #include <string.h>
41 
47 static inline int
48 contiki_prng_impl(unsigned char *buf, size_t len) {
49  unsigned short v = random_rand();
50  while (len > sizeof(v)) {
51  memcpy(buf, &v, sizeof(v));
52  len -= sizeof(v);
53  buf += sizeof(v);
54  v = random_rand();
55  }
56 
57  memcpy(buf, &v, len);
58  return 1;
59 }
60 
61 #define prng(Buf,Length) contiki_prng_impl((Buf), (Length))
62 #define prng_init(Value) random_init((unsigned short)(Value))
63 #endif /* WITH_CONTIKI */
64 
65 #if defined(WITH_LWIP) && defined(LWIP_RAND)
66 static inline int
67 lwip_prng_impl(unsigned char *buf, size_t len) {
68  u32_t v = LWIP_RAND();
69  while (len > sizeof(v)) {
70  memcpy(buf, &v, sizeof(v));
71  len -= sizeof(v);
72  buf += sizeof(v);
73  v = LWIP_RAND();
74  }
75 
76  memcpy(buf, &v, len);
77  return 1;
78 }
79 
80 #define prng(Buf,Length) lwip_prng_impl((Buf), (Length))
81 #define prng_init(Value)
82 
83 #endif /* WITH_LWIP */
84 
85 #ifndef prng
86 
91 #define prng(Buf,Length) coap_prng_impl((Buf), (Length))
92 #endif
93 
94 #ifndef prng_init
95 
101 #define prng_init(Value) srand((unsigned long)(Value))
102 #endif
103 
106 #endif /* _COAP_PRNG_H_ */
static int coap_prng_impl(unsigned char *buf, size_t len)
Fills buf with len random bytes.
Definition: prng.h:32