xref: /haiku/src/system/libroot/posix/musl/time/wcsftime.c (revision 4a55cc230cf7566cadcbb23b1928eefff8aea9a2)
1 #include <wchar.h>
2 #include <stdlib.h>
3 #include <time.h>
4 #include <locale.h>
5 #include "locale_impl.h"
6 #include "time_impl.h"
7 
8 size_t __wcsftime_l(wchar_t *restrict s, size_t n, const wchar_t *restrict f, const struct tm *restrict tm, locale_t loc)
9 {
10 	size_t l, k;
11 	char buf[100];
12 	wchar_t wbuf[100];
13 	wchar_t *p;
14 	const char *t_mb;
15 	const wchar_t *t;
16 	int pad, plus;
17 	unsigned long width;
18 	for (l=0; l<n; f++) {
19 		if (!*f) {
20 			s[l] = 0;
21 			return l;
22 		}
23 		if (*f != '%') {
24 			s[l++] = *f;
25 			continue;
26 		}
27 		f++;
28 		pad = 0;
29 		if (*f == '-' || *f == '_' || *f == '0') pad = *f++;
30 		if ((plus = (*f == '+'))) f++;
31 		width = wcstoul(f, &p, 10);
32 		if (*p == 'C' || *p == 'F' || *p == 'G' || *p == 'Y') {
33 			if (!width && p!=f) width = 1;
34 		} else {
35 			width = 0;
36 		}
37 		f = p;
38 		if (*f == 'E' || *f == 'O') f++;
39 		t_mb = __strftime_fmt_1(&buf, &k, *f, tm, loc, pad);
40 		if (!t_mb) break;
41 		k = mbstowcs(wbuf, t_mb, sizeof wbuf / sizeof *wbuf);
42 		if (k == (size_t)-1) return 0;
43 		t = wbuf;
44 		if (width) {
45 			for (; *t=='+' || *t=='-' || (*t=='0'&&t[1]); t++, k--);
46 			width--;
47 			if (plus && tm->tm_year >= 10000-1900)
48 				s[l++] = '+';
49 			else if (tm->tm_year < -1900)
50 				s[l++] = '-';
51 			else
52 				width++;
53 			for (; width > k && l < n; width--)
54 				s[l++] = '0';
55 		}
56 		if (k >= n-l) k = n-l;
57 		wmemcpy(s+l, t, k);
58 		l += k;
59 	}
60 	if (n) {
61 		if (l==n) l=n-1;
62 		s[l] = 0;
63 	}
64 	return 0;
65 }
66 
67 size_t wcsftime(wchar_t *restrict wcs, size_t n, const wchar_t *restrict f, const struct tm *restrict tm)
68 {
69 	return __wcsftime_l(wcs, n, f, tm, CURRENT_LOCALE);
70 }
71 
72 weak_alias(__wcsftime_l, wcsftime_l);
73