libcoap  4.3.1
coap_prng.h
Go to the documentation of this file.
1 /*
2  * coap_prng.h -- Pseudo Random Numbers
3  *
4  * Copyright (C) 2010-2020 Olaf Bergmann <bergmann@tzi.org>
5  *
6  * SPDX-License-Identifier: BSD-2-Clause
7  *
8  * This file is part of the CoAP library libcoap. Please see README for terms
9  * of use.
10  */
11 
17 #ifndef COAP_PRNG_H_
18 #define COAP_PRNG_H_
19 
27 #if defined(WITH_CONTIKI)
28 #include <string.h>
29 
36 contiki_prng_impl(unsigned char *buf, size_t len) {
37  uint16_t v = random_rand();
38  while (len > sizeof(v)) {
39  memcpy(buf, &v, sizeof(v));
40  len -= sizeof(v);
41  buf += sizeof(v);
42  v = random_rand();
43  }
44 
45  memcpy(buf, &v, len);
46  return 1;
47 }
48 
49 #define coap_prng(Buf,Length) contiki_prng_impl((Buf), (Length))
50 #define coap_prng_init(Value) random_init((uint16_t)(Value))
51 
52 #elif defined(WITH_LWIP) && defined(LWIP_RAND)
53 
55 lwip_prng_impl(unsigned char *buf, size_t len) {
56  u32_t v = LWIP_RAND();
57  while (len > sizeof(v)) {
58  memcpy(buf, &v, sizeof(v));
59  len -= sizeof(v);
60  buf += sizeof(v);
61  v = LWIP_RAND();
62  }
63 
64  memcpy(buf, &v, len);
65  return 1;
66 }
67 
68 #define coap_prng(Buf,Length) lwip_prng_impl((Buf), (Length))
69 #define coap_prng_init(Value) (void)Value
70 
71 #else
72 
78 typedef int (*coap_rand_func_t)(void *out, size_t len);
79 
87 
95 void coap_prng_init(unsigned int seed);
96 
108 int coap_prng(void *buf, size_t len);
109 
110 #endif /* POSIX */
111 
114 #endif /* COAP_PRNG_H_ */
int(* coap_rand_func_t)(void *out, size_t len)
Data type for random number generator function.
Definition: coap_prng.h:78
void coap_set_prng(coap_rand_func_t rng)
Replaces the current random number generation function with the default function rng.
Definition: coap_prng.c:89
int coap_prng(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition: coap_prng.c:105
void coap_prng_init(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition: coap_prng.c:94
#define COAP_STATIC_INLINE
Definition: libcoap.h:45