SDL_utils.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #if defined(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS)
  20. #include <unistd.h>
  21. #endif
  22. // Common utility functions that aren't in the public API
  23. int SDL_powerof2(int x)
  24. {
  25. int value;
  26. if (x <= 0) {
  27. // Return some sane value - we shouldn't hit this in our use cases
  28. return 1;
  29. }
  30. // This trick works for 32-bit values
  31. {
  32. SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32));
  33. }
  34. value = x;
  35. value -= 1;
  36. value |= value >> 1;
  37. value |= value >> 2;
  38. value |= value >> 4;
  39. value |= value >> 8;
  40. value |= value >> 16;
  41. value += 1;
  42. return value;
  43. }
  44. Uint32 SDL_CalculateGCD(Uint32 a, Uint32 b)
  45. {
  46. if (b == 0) {
  47. return a;
  48. }
  49. return SDL_CalculateGCD(b, (a % b));
  50. }
  51. // Algorithm adapted with thanks from John Cook's blog post:
  52. // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation
  53. void SDL_CalculateFraction(float x, int *numerator, int *denominator)
  54. {
  55. const int N = 1000;
  56. int a = 0, b = 1;
  57. int c = 1, d = 0;
  58. while (b <= N && d <= N) {
  59. float mediant = (float)(a + c) / (b + d);
  60. if (x == mediant) {
  61. if (b + d <= N) {
  62. *numerator = a + c;
  63. *denominator = b + d;
  64. } else if (d > b) {
  65. *numerator = c;
  66. *denominator = d;
  67. } else {
  68. *numerator = a;
  69. *denominator = b;
  70. }
  71. return;
  72. } else if (x > mediant) {
  73. a = a + c;
  74. b = b + d;
  75. } else {
  76. c = a + c;
  77. d = b + d;
  78. }
  79. }
  80. if (b > N) {
  81. *numerator = c;
  82. *denominator = d;
  83. } else {
  84. *numerator = a;
  85. *denominator = b;
  86. }
  87. }
  88. bool SDL_startswith(const char *string, const char *prefix)
  89. {
  90. if (SDL_strncmp(string, prefix, SDL_strlen(prefix)) == 0) {
  91. return true;
  92. }
  93. return false;
  94. }
  95. bool SDL_endswith(const char *string, const char *suffix)
  96. {
  97. size_t string_length = string ? SDL_strlen(string) : 0;
  98. size_t suffix_length = suffix ? SDL_strlen(suffix) : 0;
  99. if (suffix_length > 0 && suffix_length <= string_length) {
  100. if (SDL_memcmp(string + string_length - suffix_length, suffix, suffix_length) == 0) {
  101. return true;
  102. }
  103. }
  104. return false;
  105. }
  106. SDL_COMPILE_TIME_ASSERT(sizeof_object_id, sizeof(int) == sizeof(Uint32));
  107. Uint32 SDL_GetNextObjectID(void)
  108. {
  109. static SDL_AtomicInt last_id;
  110. Uint32 id = (Uint32)SDL_AtomicIncRef(&last_id) + 1;
  111. if (id == 0) {
  112. id = (Uint32)SDL_AtomicIncRef(&last_id) + 1;
  113. }
  114. return id;
  115. }
  116. static SDL_InitState SDL_objects_init;
  117. static SDL_HashTable *SDL_objects;
  118. static Uint32 SDL_HashObject(const void *key, void *unused)
  119. {
  120. return (Uint32)(uintptr_t)key;
  121. }
  122. static bool SDL_KeyMatchObject(const void *a, const void *b, void *unused)
  123. {
  124. return (a == b);
  125. }
  126. void SDL_SetObjectValid(void *object, SDL_ObjectType type, bool valid)
  127. {
  128. SDL_assert(object != NULL);
  129. if (valid && SDL_ShouldInit(&SDL_objects_init)) {
  130. SDL_objects = SDL_CreateHashTable(NULL, 32, SDL_HashObject, SDL_KeyMatchObject, NULL, true, false);
  131. if (!SDL_objects) {
  132. SDL_SetInitialized(&SDL_objects_init, false);
  133. }
  134. SDL_SetInitialized(&SDL_objects_init, true);
  135. }
  136. if (valid) {
  137. SDL_InsertIntoHashTable(SDL_objects, object, (void *)(uintptr_t)type);
  138. } else {
  139. SDL_RemoveFromHashTable(SDL_objects, object);
  140. }
  141. }
  142. bool SDL_ObjectValid(void *object, SDL_ObjectType type)
  143. {
  144. if (!object) {
  145. return false;
  146. }
  147. const void *object_type;
  148. if (!SDL_FindInHashTable(SDL_objects, object, &object_type)) {
  149. return false;
  150. }
  151. return (((SDL_ObjectType)(uintptr_t)object_type) == type);
  152. }
  153. void SDL_SetObjectsInvalid(void)
  154. {
  155. if (SDL_ShouldQuit(&SDL_objects_init)) {
  156. // Log any leaked objects
  157. const void *object, *object_type;
  158. void *iter = NULL;
  159. while (SDL_IterateHashTable(SDL_objects, &object, &object_type, &iter)) {
  160. const char *type;
  161. switch ((SDL_ObjectType)(uintptr_t)object_type) {
  162. case SDL_OBJECT_TYPE_WINDOW:
  163. type = "SDL_Window";
  164. break;
  165. case SDL_OBJECT_TYPE_RENDERER:
  166. type = "SDL_Renderer";
  167. break;
  168. case SDL_OBJECT_TYPE_TEXTURE:
  169. type = "SDL_Texture";
  170. break;
  171. case SDL_OBJECT_TYPE_JOYSTICK:
  172. type = "SDL_Joystick";
  173. break;
  174. case SDL_OBJECT_TYPE_GAMEPAD:
  175. type = "SDL_Gamepad";
  176. break;
  177. case SDL_OBJECT_TYPE_HAPTIC:
  178. type = "SDL_Haptic";
  179. break;
  180. case SDL_OBJECT_TYPE_SENSOR:
  181. type = "SDL_Sensor";
  182. break;
  183. case SDL_OBJECT_TYPE_HIDAPI_DEVICE:
  184. type = "hidapi device";
  185. break;
  186. case SDL_OBJECT_TYPE_HIDAPI_JOYSTICK:
  187. type = "hidapi joystick";
  188. break;
  189. case SDL_OBJECT_TYPE_THREAD:
  190. type = "thread";
  191. break;
  192. default:
  193. type = "unknown object";
  194. break;
  195. }
  196. SDL_Log("Leaked %s (%p)\n", type, object);
  197. }
  198. SDL_assert(SDL_HashTableEmpty(SDL_objects));
  199. SDL_DestroyHashTable(SDL_objects);
  200. SDL_objects = NULL;
  201. SDL_SetInitialized(&SDL_objects_init, false);
  202. }
  203. }
  204. static int SDL_URIDecode(const char *src, char *dst, int len)
  205. {
  206. int ri, wi, di;
  207. char decode = '\0';
  208. if (!src || !dst || len < 0) {
  209. return -1;
  210. }
  211. if (len == 0) {
  212. len = (int)SDL_strlen(src);
  213. }
  214. for (ri = 0, wi = 0, di = 0; ri < len && wi < len; ri += 1) {
  215. if (di == 0) {
  216. // start decoding
  217. if (src[ri] == '%') {
  218. decode = '\0';
  219. di += 1;
  220. continue;
  221. }
  222. // normal write
  223. dst[wi] = src[ri];
  224. wi += 1;
  225. } else if (di == 1 || di == 2) {
  226. char off = '\0';
  227. char isa = src[ri] >= 'a' && src[ri] <= 'f';
  228. char isA = src[ri] >= 'A' && src[ri] <= 'F';
  229. char isn = src[ri] >= '0' && src[ri] <= '9';
  230. if (!(isa || isA || isn)) {
  231. // not a hexadecimal
  232. int sri;
  233. for (sri = ri - di; sri <= ri; sri += 1) {
  234. dst[wi] = src[sri];
  235. wi += 1;
  236. }
  237. di = 0;
  238. continue;
  239. }
  240. // itsy bitsy magicsy
  241. if (isn) {
  242. off = 0 - '0';
  243. } else if (isa) {
  244. off = 10 - 'a';
  245. } else if (isA) {
  246. off = 10 - 'A';
  247. }
  248. decode |= (src[ri] + off) << (2 - di) * 4;
  249. if (di == 2) {
  250. dst[wi] = decode;
  251. wi += 1;
  252. di = 0;
  253. } else {
  254. di += 1;
  255. }
  256. }
  257. }
  258. dst[wi] = '\0';
  259. return wi;
  260. }
  261. int SDL_URIToLocal(const char *src, char *dst)
  262. {
  263. if (SDL_memcmp(src, "file:/", 6) == 0) {
  264. src += 6; // local file?
  265. } else if (SDL_strstr(src, ":/") != NULL) {
  266. return -1; // wrong scheme
  267. }
  268. bool local = src[0] != '/' || (src[0] != '\0' && src[1] == '/');
  269. // Check the hostname, if present. RFC 3986 states that the hostname component of a URI is not case-sensitive.
  270. if (!local && src[0] == '/' && src[2] != '/') {
  271. char *hostname_end = SDL_strchr(src + 1, '/');
  272. if (hostname_end) {
  273. const size_t src_len = hostname_end - (src + 1);
  274. size_t hostname_len;
  275. #if defined(HAVE_GETHOSTNAME) && !defined(SDL_PLATFORM_WINDOWS)
  276. char hostname[257];
  277. if (gethostname(hostname, 255) == 0) {
  278. hostname[256] = '\0';
  279. hostname_len = SDL_strlen(hostname);
  280. if (hostname_len == src_len && SDL_strncasecmp(src + 1, hostname, src_len) == 0) {
  281. src = hostname_end + 1;
  282. local = true;
  283. }
  284. }
  285. #endif
  286. if (!local) {
  287. static const char *localhost = "localhost";
  288. hostname_len = SDL_strlen(localhost);
  289. if (hostname_len == src_len && SDL_strncasecmp(src + 1, localhost, src_len) == 0) {
  290. src = hostname_end + 1;
  291. local = true;
  292. }
  293. }
  294. }
  295. }
  296. if (local) {
  297. // Convert URI escape sequences to real characters
  298. if (src[0] == '/') {
  299. src++;
  300. } else {
  301. src--;
  302. }
  303. return SDL_URIDecode(src, dst, 0);
  304. }
  305. return -1;
  306. }
  307. // This is a set of per-thread persistent strings that we can return from the SDL API.
  308. // This is used for short strings that might persist past the lifetime of the object
  309. // they are related to.
  310. static SDL_TLSID SDL_string_storage;
  311. static void SDL_FreePersistentStrings( void *value )
  312. {
  313. SDL_HashTable *strings = (SDL_HashTable *)value;
  314. SDL_DestroyHashTable(strings);
  315. }
  316. const char *SDL_GetPersistentString(const char *string)
  317. {
  318. if (!string) {
  319. return NULL;
  320. }
  321. if (!*string) {
  322. return "";
  323. }
  324. SDL_HashTable *strings = (SDL_HashTable *)SDL_GetTLS(&SDL_string_storage);
  325. if (!strings) {
  326. strings = SDL_CreateHashTable(NULL, 32, SDL_HashString, SDL_KeyMatchString, SDL_NukeFreeValue, false, false);
  327. if (!strings) {
  328. return NULL;
  329. }
  330. SDL_SetTLS(&SDL_string_storage, strings, SDL_FreePersistentStrings);
  331. }
  332. const char *result;
  333. if (!SDL_FindInHashTable(strings, string, (const void **)&result)) {
  334. char *new_string = SDL_strdup(string);
  335. if (!new_string) {
  336. return NULL;
  337. }
  338. // If the hash table insert fails, at least we can return the string we allocated
  339. SDL_InsertIntoHashTable(strings, new_string, new_string);
  340. result = new_string;
  341. }
  342. return result;
  343. }