src/util/formatting.c (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include <mgba-util/formatting.h>
7
8#include <float.h>
9
10int ftostr_l(char* restrict str, size_t size, float f, locale_t locale) {
11#ifdef HAVE_SNPRINTF_L
12 return snprintf_l(str, size, locale, "%.*g", FLT_DIG, f);
13#elif defined(HAVE_LOCALE)
14 locale_t old = uselocale(locale);
15 int res = snprintf(str, size, "%.*g", FLT_DIG, f);
16 uselocale(old);
17 return res;
18#elif defined(HAVE_SETLOCALE)
19 char* old = setlocale(LC_NUMERIC, locale);
20 int res = snprintf(str, size, "%.*g", FLT_DIG, f);
21 setlocale(LC_NUMERIC, old);
22 return res;
23#else
24 UNUSED(locale);
25 return snprintf(str, size, "%.*g", FLT_DIG, f);
26#endif
27}
28
29#ifndef HAVE_STRTOF_L
30float strtof_l(const char* restrict str, char** restrict end, locale_t locale) {
31#ifdef HAVE_LOCALE
32 locale_t old = uselocale(locale);
33 float res = strtof(str, end);
34 uselocale(old);
35 return res;
36#elif defined(HAVE_SETLOCALE)
37 char* old = setlocale(LC_NUMERIC, locale);
38 float res = strtof(str, end);
39 setlocale(LC_NUMERIC, old);
40 return res;
41#else
42 UNUSED(locale);
43 return strtof(str, end);
44#endif
45}
46#endif
47
48int ftostr_u(char* restrict str, size_t size, float f) {
49#if HAVE_LOCALE
50 locale_t l = newlocale(LC_NUMERIC_MASK, "C", 0);
51#else
52 locale_t l = "C";
53#endif
54 int res = ftostr_l(str, size, f, l);
55#if HAVE_LOCALE
56 freelocale(l);
57#endif
58 return res;
59}
60
61float strtof_u(const char* restrict str, char** restrict end) {
62#if HAVE_LOCALE
63 locale_t l = newlocale(LC_NUMERIC_MASK, "C", 0);
64#else
65 locale_t l = "C";
66#endif
67 float res = strtof_l(str, end, l);
68#if HAVE_LOCALE
69 freelocale(l);
70#endif
71 return res;
72}
73
74#ifndef HAVE_LOCALTIME_R
75struct tm* localtime_r(const time_t* t, struct tm* date) {
76#ifdef _WIN32
77 localtime_s(date, t);
78 return date;
79#elif defined(PSP2)
80 extern struct tm* sceKernelLibcLocaltime_r(const time_t* t, struct tm* date);
81 return sceKernelLibcLocaltime_r(t, date);
82#else
83#warning localtime_r not emulated on this platform
84 return 0;
85#endif
86}
87#endif