Fun
0.41.5
The programming language that makes You have fun
Main Page
Data Structures
Files
File List
Globals
Loading...
Searching...
No Matches
src
vm
os
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
26
case
OP_DATE_FORMAT
: {
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
) {
43
free_value
(
ms
);
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
}
60
Value
out
;
61
if
(
n
== 0) {
62
out
=
make_string
(
""
);
63
}
else
{
64
out
=
make_string
(
buf
);
65
}
66
free
(
buf
);
67
free_value
(
ms
);
68
free_value
(fmt);
69
push_value
(vm,
out
);
70
break
;
71
}
out
Value out
Definition
apop.c:38
OP_DATE_FORMAT
@ OP_DATE_FORMAT
Definition
bytecode.h:146
ms
ms
Definition
clock_mono_ms.c:33
tmv
struct tm tmv
Definition
date_format.c:37
push_value
push_value(vm, out)
ptm
struct tm * ptm
Definition
date_format.c:41
free
free(buf)
secs
time_t secs
Definition
date_format.c:36
free_value
free_value(ms)
cap
size_t cap
Definition
input_line.c:101
buf
char * buf
Definition
input_line.c:103
n
int n
Definition
insert.c:41
Value
Tagged union representing a Fun value.
Definition
value.h:68
Value::type
ValueType type
Definition
value.h:69
Value::s
char * s
Definition
value.h:73
make_string
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition
value.c:95
VAL_STRING
@ VAL_STRING
Definition
value.h:53
VAL_NIL
@ VAL_NIL
Definition
value.h:57
VAL_INT
@ VAL_INT
Definition
value.h:51
fprintf
#define fprintf
Definition
vm.c:200
Generated on
for Fun by
1.16.1