Skip to main content

rustjava_runtime/classes/java/util/
date.rs

1use alloc::{format, vec};
2
3use chrono::{DateTime, Datelike, Timelike, Utc};
4
5use jvm::{ClassInstanceRef, Jvm, Result, runtime::JavaLangString};
6use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
7use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
8
9use crate::{
10    RuntimeClassProto, RuntimeContext,
11    classes::java::lang::{Object, String},
12};
13
14// class java.util.Date
15pub struct Date;
16
17impl Date {
18    pub fn as_proto() -> RuntimeClassProto {
19        RuntimeClassProto {
20            name: "java/util/Date",
21            parent_class: Some("java/lang/Object"),
22            interfaces: vec!["java/io/Serializable", "java/lang/Cloneable", "java/lang/Comparable"],
23            methods: vec![
24                JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
25                JavaMethodProto::new("<init>", "(J)V", Self::init_with_time, MethodAccessFlags::PUBLIC),
26                JavaMethodProto::new("getTime", "()J", Self::get_time, MethodAccessFlags::PUBLIC),
27                JavaMethodProto::new("setTime", "(J)V", Self::set_time, MethodAccessFlags::PUBLIC),
28                JavaMethodProto::new("before", "(Ljava/util/Date;)Z", Self::before, MethodAccessFlags::PUBLIC),
29                JavaMethodProto::new("after", "(Ljava/util/Date;)Z", Self::after, MethodAccessFlags::PUBLIC),
30                JavaMethodProto::new("compareTo", "(Ljava/util/Date;)I", Self::compare_to, MethodAccessFlags::PUBLIC),
31                JavaMethodProto::new("compareTo", "(Ljava/lang/Object;)I", Self::compare_to, MethodAccessFlags::PUBLIC),
32                JavaMethodProto::new("equals", "(Ljava/lang/Object;)Z", Self::equals, MethodAccessFlags::PUBLIC),
33                JavaMethodProto::new("hashCode", "()I", Self::hash_code, MethodAccessFlags::PUBLIC),
34                JavaMethodProto::new("toString", "()Ljava/lang/String;", Self::to_string, MethodAccessFlags::PUBLIC),
35            ],
36            fields: vec![JavaFieldProto::new("value", "J", FieldAccessFlags::PRIVATE)],
37            access_flags: ClassAccessFlags::PUBLIC,
38        }
39    }
40
41    async fn init(jvm: &Jvm, context: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
42        tracing::debug!("java.util.Date::<init>({this:?})");
43
44        let now: u64 = context.now();
45
46        let _: () = jvm.invoke_special(&this, "java/util/Date", "<init>", "(J)V", (now as i64,)).await?;
47
48        Ok(())
49    }
50
51    async fn init_with_time(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, time: i64) -> Result<()> {
52        tracing::debug!("java.util.Date::<init>({this:?}, {time:?})");
53
54        let _: () = jvm.invoke_special(&this, "java/lang/Object", "<init>", "()V", ()).await?;
55
56        jvm.put_field(&mut this, "java/util/Date", "value", "J", time).await?;
57
58        Ok(())
59    }
60
61    async fn get_time(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<i64> {
62        tracing::debug!("java.util.Date::getTime({this:?})");
63
64        let time = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
65
66        Ok(time)
67    }
68
69    async fn set_time(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, time: i64) -> Result<()> {
70        tracing::debug!("java.util.Date::setTime({this:?}, {time:?})");
71
72        jvm.put_field(&mut this, "java/util/Date", "value", "J", time).await?;
73
74        Ok(())
75    }
76
77    async fn before(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, when: ClassInstanceRef<Object>) -> Result<bool> {
78        tracing::debug!("java.util.Date::before({this:?}, {when:?})");
79
80        if when.is_null() {
81            return Err(jvm.exception("java/lang/NullPointerException", "when is null").await);
82        }
83
84        let when: ClassInstanceRef<Self> = ClassInstanceRef::new(when.instance);
85        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
86        let when_time: i64 = jvm.get_field(&when, "java/util/Date", "value", "J").await?;
87        Ok(time < when_time)
88    }
89
90    async fn after(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, when: ClassInstanceRef<Object>) -> Result<bool> {
91        tracing::debug!("java.util.Date::after({this:?}, {when:?})");
92
93        if when.is_null() {
94            return Err(jvm.exception("java/lang/NullPointerException", "when is null").await);
95        }
96
97        let when: ClassInstanceRef<Self> = ClassInstanceRef::new(when.instance);
98        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
99        let when_time: i64 = jvm.get_field(&when, "java/util/Date", "value", "J").await?;
100        Ok(time > when_time)
101    }
102
103    async fn compare_to(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, other: ClassInstanceRef<Object>) -> Result<i32> {
104        tracing::debug!("java.util.Date::compareTo({this:?}, {other:?})");
105
106        if other.is_null() {
107            return Err(jvm.exception("java/lang/NullPointerException", "anotherDate is null").await);
108        }
109        if !jvm.is_instance(&**other, "java/util/Date") {
110            return Err(jvm.exception("java/lang/ClassCastException", &other.class_definition().name()).await);
111        }
112
113        let other: ClassInstanceRef<Self> = ClassInstanceRef::new(other.instance);
114        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
115        let other_time: i64 = jvm.get_field(&other, "java/util/Date", "value", "J").await?;
116        Ok(if time < other_time {
117            -1
118        } else if time == other_time {
119            0
120        } else {
121            1
122        })
123    }
124
125    async fn equals(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, other: ClassInstanceRef<Object>) -> Result<bool> {
126        tracing::debug!("java.util.Date::equals({this:?}, {other:?})");
127
128        if other.is_null() || !jvm.is_instance(&**other, "java/util/Date") {
129            return Ok(false);
130        }
131
132        let other: ClassInstanceRef<Date> = ClassInstanceRef::new(other.instance);
133        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
134        let other_time: i64 = jvm.get_field(&other, "java/util/Date", "value", "J").await?;
135        Ok(time == other_time)
136    }
137
138    async fn hash_code(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<i32> {
139        tracing::debug!("java.util.Date::hashCode({this:?})");
140
141        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
142        Ok((time ^ ((time as u64 >> 32) as i64)) as i32)
143    }
144
145    async fn to_string(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<String>> {
146        tracing::debug!("java.util.Date::toString({this:?})");
147
148        let time: i64 = jvm.get_field(&this, "java/util/Date", "value", "J").await?;
149        let text = if let Some(date_time) = DateTime::<Utc>::from_timestamp_millis(time) {
150            let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
151            let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
152            format!(
153                "{} {} {:02} {:02}:{:02}:{:02} GMT {:04}",
154                weekdays[date_time.weekday().num_days_from_sunday() as usize],
155                months[date_time.month0() as usize],
156                date_time.day(),
157                date_time.hour(),
158                date_time.minute(),
159                date_time.second(),
160                date_time.year()
161            )
162        } else {
163            format!("Date({time})")
164        };
165
166        Ok(JavaLangString::from_rust_string(jvm, &text).await?.into())
167    }
168}