1 /* SPDX-License-Identifier: GPL-3.0-or-later
2  * Copyright © 2016-2018 The TokTok team.
3  * Copyright © 2013 Tox project.
4  * Copyright © 2013 plutooo
5  */
6 
7 /*
8  * Utilities.
9  */
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13 
14 #ifndef _XOPEN_SOURCE
15 #define _XOPEN_SOURCE 600
16 #endif
17 
18 #include "util.h"
19 
20 #include <stdlib.h>
21 #include <string.h>
22 #include <time.h>
23 
24 #include "crypto_core.h" /* for CRYPTO_PUBLIC_KEY_SIZE */
25 
26 
27 /* id functions */
id_equal(const uint8_t * dest,const uint8_t * src)28 bool id_equal(const uint8_t *dest, const uint8_t *src)
29 {
30     return public_key_cmp(dest, src) == 0;
31 }
32 
id_copy(uint8_t * dest,const uint8_t * src)33 uint32_t id_copy(uint8_t *dest, const uint8_t *src)
34 {
35     memcpy(dest, src, CRYPTO_PUBLIC_KEY_SIZE);
36     return CRYPTO_PUBLIC_KEY_SIZE;
37 }
38 
create_recursive_mutex(pthread_mutex_t * mutex)39 int create_recursive_mutex(pthread_mutex_t *mutex)
40 {
41     pthread_mutexattr_t attr;
42 
43     if (pthread_mutexattr_init(&attr) != 0) {
44         return -1;
45     }
46 
47     if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
48         pthread_mutexattr_destroy(&attr);
49         return -1;
50     }
51 
52     /* Create queue mutex */
53     if (pthread_mutex_init(mutex, &attr) != 0) {
54         pthread_mutexattr_destroy(&attr);
55         return -1;
56     }
57 
58     pthread_mutexattr_destroy(&attr);
59 
60     return 0;
61 }
62 
max_s16(int16_t a,int16_t b)63 int16_t max_s16(int16_t a, int16_t b)
64 {
65     return a > b ? a : b;
66 }
max_s32(int32_t a,int32_t b)67 int32_t max_s32(int32_t a, int32_t b)
68 {
69     return a > b ? a : b;
70 }
max_s64(int64_t a,int64_t b)71 int64_t max_s64(int64_t a, int64_t b)
72 {
73     return a > b ? a : b;
74 }
75 
min_s16(int16_t a,int16_t b)76 int16_t min_s16(int16_t a, int16_t b)
77 {
78     return a < b ? a : b;
79 }
min_s32(int32_t a,int32_t b)80 int32_t min_s32(int32_t a, int32_t b)
81 {
82     return a < b ? a : b;
83 }
min_s64(int64_t a,int64_t b)84 int64_t min_s64(int64_t a, int64_t b)
85 {
86     return a < b ? a : b;
87 }
88 
max_u16(uint16_t a,uint16_t b)89 uint16_t max_u16(uint16_t a, uint16_t b)
90 {
91     return a > b ? a : b;
92 }
max_u32(uint32_t a,uint32_t b)93 uint32_t max_u32(uint32_t a, uint32_t b)
94 {
95     return a > b ? a : b;
96 }
max_u64(uint64_t a,uint64_t b)97 uint64_t max_u64(uint64_t a, uint64_t b)
98 {
99     return a > b ? a : b;
100 }
101 
min_u16(uint16_t a,uint16_t b)102 uint16_t min_u16(uint16_t a, uint16_t b)
103 {
104     return a < b ? a : b;
105 }
min_u32(uint32_t a,uint32_t b)106 uint32_t min_u32(uint32_t a, uint32_t b)
107 {
108     return a < b ? a : b;
109 }
min_u64(uint64_t a,uint64_t b)110 uint64_t min_u64(uint64_t a, uint64_t b)
111 {
112     return a < b ? a : b;
113 }
114