blob: 2fcda65c642c87c0294cea5c6685d92ed12057f7 [file] [log] [blame]
Stefan Tauner6ad6e012014-06-12 00:04:32 +00001/*
2 * This file is part of the flashrom project.
3 *
4 * Copyright (C) 2009-2010 Carl-Daniel Hailfinger
5 * Copyright (C) 2013 Stefan Tauner
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
Stefan Tauner6ad6e012014-06-12 00:04:32 +000016 */
17
18#include <ctype.h>
19#include <stdlib.h>
20#include <string.h>
21#include "flash.h"
22
23/* Returns the minimum number of bits needed to represent the given address.
24 * FIXME: use mind-blowing implementation. */
25uint32_t address_to_bits(uint32_t addr)
26{
27 unsigned int lzb = 0;
28 while (((1 << (31 - lzb)) & ~addr) != 0)
29 lzb++;
30 return 32 - lzb;
31}
32
33int bitcount(unsigned long a)
34{
35 int i = 0;
36 for (; a != 0; a >>= 1)
37 if (a & 1)
38 i++;
39 return i;
40}
41
42int max(int a, int b)
43{
44 return (a > b) ? a : b;
45}
46
47int min(int a, int b)
48{
49 return (a < b) ? a : b;
50}
51
52char *strcat_realloc(char *dest, const char *src)
53{
54 dest = realloc(dest, strlen(dest) + strlen(src) + 1);
55 if (!dest) {
56 msg_gerr("Out of memory!\n");
57 return NULL;
58 }
59 strcat(dest, src);
60 return dest;
61}
62
63void tolower_string(char *str)
64{
65 for (; *str != '\0'; str++)
66 *str = (char)tolower((unsigned char)*str);
67}
68
Stefan Taunerb41d8472014-11-01 22:56:06 +000069/* FIXME: Find a better solution for MinGW. Maybe wrap strtok_s (C11) if it becomes available */
70#ifdef __MINGW32__
71char* strtok_r(char *str, const char *delim, char **nextp)
72{
73 if (str == NULL)
74 str = *nextp;
75
76 str += strspn(str, delim); /* Skip leading delimiters */
77 if (*str == '\0')
78 return NULL;
79
80 char *ret = str;
81 str += strcspn(str, delim); /* Find end of token */
82 if (*str != '\0')
83 *str++ = '\0';
84
85 *nextp = str;
86 return ret;
87}
88#endif
89
Stefan Taunerdc627932015-01-27 18:07:50 +000090/* There is no strnlen in DJGPP */
Nico Huber2d625722016-05-03 10:48:02 +020091#if defined(__DJGPP__) || (!defined(__LIBPAYLOAD__) && !defined(HAVE_STRNLEN))
Stefan Taunerdc627932015-01-27 18:07:50 +000092size_t strnlen(const char *str, size_t n)
93{
94 size_t i;
95 for (i = 0; i < n && str[i] != '\0'; i++)
96 ;
97 return i;
98}
99#endif