Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
date_format.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
21
22#include <stdlib.h>
23#include <string.h>
24#include <time.h>
25
27 Value fmt = pop_value(vm);
28 Value ms = pop_value(vm);
29 if (ms.type != VAL_INT || fmt.type != VAL_STRING) {
30 fprintf(stderr, "DATE_FORMAT expects (fmt:string, ms:int)\n");
31 if (ms.type != VAL_NIL) free_value(ms);
32 if (fmt.type != VAL_NIL) free_value(fmt);
33 push_value(vm, make_string(""));
34 break;
35 }
36 time_t secs = (time_t)(ms.i / 1000);
37 struct tm tmv;
38#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1
39 localtime_r(&secs, &tmv);
40#else
41 struct tm *ptm = localtime(&secs);
42 if (!ptm) {
44 free_value(fmt);
45 push_value(vm, make_string(""));
46 break;
47 }
48 tmv = *ptm;
49#endif
50 /* Determine buffer size by attempting once with a reasonable size and retrying if needed */
51 size_t cap = 128;
52 char *buf = (char *)malloc(cap);
53 size_t n = strftime(buf, cap, fmt.s, &tmv);
54 if (n == 0) {
55 /* try larger */
56 cap = 512;
57 buf = (char *)realloc(buf, cap);
58 n = strftime(buf, cap, fmt.s, &tmv);
59 }
61 if (n == 0) {
62 out = make_string("");
63 } else {
65 }
70 break;
71}
Value out
Definition apop.c:38
@ OP_DATE_FORMAT
Definition bytecode.h:146
struct tm tmv
Definition date_format.c:37
push_value(vm, out)
struct tm * ptm
Definition date_format.c:41
free(buf)
time_t secs
Definition date_format.c:36
free_value(ms)
size_t cap
Definition input_line.c:101
char * buf
Definition input_line.c:103
int n
Definition insert.c:41
Tagged union representing a Fun value.
Definition value.h:68
ValueType type
Definition value.h:69
char * s
Definition value.h:73
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
@ VAL_STRING
Definition value.h:53
@ VAL_NIL
Definition value.h:57
@ VAL_INT
Definition value.h:51
#define fprintf
Definition vm.c:200