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