Skip to main content

shape_jit/ffi/call_method/
time.rs

1// Heap allocation audit (PR-9 V8 Gap Closure):
2//   Category A (NaN-boxed returns): 2 sites
3//     jit_box(HK_STRING, ...) — format, toString
4//   Category B (intermediate/consumed): 0 sites
5//   Category C (heap islands): 0 sites
6//!
7//! Time method implementations for JIT
8
9use crate::nan_boxing::*;
10use chrono::{Datelike, TimeZone, Timelike, Utc};
11
12/// Call a method on a time value
13#[inline(always)]
14pub fn call_time_method(receiver_bits: u64, method_name: &str, _args: &[u64]) -> u64 {
15    // Time is heap-allocated as i64 timestamp
16    if !is_heap_kind(receiver_bits, HK_TIME) {
17        return TAG_NULL;
18    }
19    let timestamp = unsafe { *jit_unbox::<i64>(receiver_bits) };
20
21    // Try to create DateTime from timestamp (treating as seconds)
22    let dt = match Utc.timestamp_opt(timestamp, 0) {
23        chrono::LocalResult::Single(dt) => dt,
24        _ => {
25            // Try milliseconds
26            match Utc.timestamp_millis_opt(timestamp) {
27                chrono::LocalResult::Single(dt) => dt,
28                _ => return TAG_NULL,
29            }
30        }
31    };
32
33    match method_name {
34        "format" => {
35            // Default format
36            let formatted = dt.format("%Y-%m-%d").to_string();
37            jit_box(HK_STRING, formatted)
38        }
39        "year" => box_number(dt.year() as f64),
40        "month" => box_number(dt.month() as f64),
41        "day" => box_number(dt.day() as f64),
42        "hour" => box_number(dt.hour() as f64),
43        "minute" => box_number(dt.minute() as f64),
44        "second" => box_number(dt.second() as f64),
45        "weekday" | "dayOfWeek" | "day_of_week" => {
46            // Monday = 0, Sunday = 6
47            box_number(dt.weekday().num_days_from_monday() as f64)
48        }
49        "timestamp" | "unix" => box_number(timestamp as f64),
50        "toString" | "to_string" => {
51            let s = dt.to_rfc3339();
52            jit_box(HK_STRING, s)
53        }
54        _ => TAG_NULL,
55    }
56}