1 /**
2 * @file lv_utils.c
3 *
4 */
5
6 /*********************
7 * INCLUDES
8 *********************/
9 #include <stdbool.h>
10
11 #include "lv_utils.h"
12 #include "lv_math.h"
13
14 /*********************
15 * DEFINES
16 *********************/
17
18 /**********************
19 * TYPEDEFS
20 **********************/
21
22 /**********************
23 * STATIC PROTOTYPES
24 **********************/
25
26 /**********************
27 * STATIC VARIABLES
28 **********************/
29
30 /**********************
31 * MACROS
32 **********************/
33
34 /**********************
35 * GLOBAL FUNCTIONS
36 **********************/
37
38 /**
39 * Convert a number to string
40 * @param num a number
41 * @param buf pointer to a `char` buffer. The result will be stored here (max 10 elements)
42 * @return same as `buf` (just for convenience)
43 */
lv_utils_num_to_str(int32_t num,char * buf)44 char * lv_utils_num_to_str(int32_t num, char * buf)
45 {
46 if(num == 0) {
47 buf[0] = '0';
48 buf[1] = '\0';
49 return buf;
50 }
51 int8_t digitCount = 0;
52 int8_t i = 0;
53 if(num < 0) {
54 buf[digitCount++] = '-';
55 num = LV_MATH_ABS(num);
56 ++i;
57 }
58 while(num) {
59 char digit = num % 10;
60 buf[digitCount++] = digit + 48;
61 num /= 10;
62 }
63 buf[digitCount] = '\0';
64 digitCount--;
65 while(digitCount > i) {
66 char temp = buf[i];
67 buf[i] = buf[digitCount];
68 buf[digitCount] = temp;
69 digitCount--;
70 i++;
71 }
72 return buf;
73 }
74
75 /** Searches base[0] to base[n - 1] for an item that matches *key.
76 *
77 * @note The function cmp must return negative if its first
78 * argument (the search key) is less that its second (a table entry),
79 * zero if equal, and positive if greater.
80 *
81 * @note Items in the array must be in ascending order.
82 *
83 * @param key Pointer to item being searched for
84 * @param base Pointer to first element to search
85 * @param n Number of elements
86 * @param size Size of each element
87 * @param cmp Pointer to comparison function (see #lv_font_codeCompare as a comparison function
88 * example)
89 *
90 * @return a pointer to a matching item, or NULL if none exists.
91 */
lv_utils_bsearch(const void * key,const void * base,uint32_t n,uint32_t size,int32_t (* cmp)(const void * pRef,const void * pElement))92 void * lv_utils_bsearch(const void * key, const void * base, uint32_t n, uint32_t size,
93 int32_t (*cmp)(const void * pRef, const void * pElement))
94 {
95 const char * middle;
96 int32_t c;
97
98 for(middle = base; n != 0;) {
99 middle += (n / 2) * size;
100 if((c = (*cmp)(key, middle)) > 0) {
101 n = (n / 2) - ((n & 1) == 0);
102 base = (middle += size);
103 } else if(c < 0) {
104 n /= 2;
105 middle = base;
106 } else {
107 return (char *)middle;
108 }
109 }
110 return NULL;
111 }
112
113 /**********************
114 * STATIC FUNCTIONS
115 **********************/
116