1use core::future::Future;
2
3use alloc::vec;
4
5use jvm::{Array, ClassInstanceRef, JavaChar, Jvm, Result};
6use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
7use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
8
9use crate::{
10 RuntimeClassProto, RuntimeContext,
11 classes::java::{
12 io::Writer,
13 lang::{Object, String},
14 },
15};
16
17const DEFAULT_INITIAL_BUFFER_SIZE: i32 = 32;
18
19pub struct CharArrayWriter;
21
22impl CharArrayWriter {
23 pub fn as_proto() -> RuntimeClassProto {
24 RuntimeClassProto {
25 name: "java/io/CharArrayWriter",
26 parent_class: Some("java/io/Writer"),
27 interfaces: vec![],
28 methods: vec![
29 JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
30 JavaMethodProto::new("<init>", "(I)V", Self::init_with_size, MethodAccessFlags::PUBLIC),
31 JavaMethodProto::new("write", "(I)V", Self::write_char, MethodAccessFlags::PUBLIC),
32 JavaMethodProto::new("write", "([CII)V", Self::write_chars, MethodAccessFlags::PUBLIC),
33 JavaMethodProto::new("write", "(Ljava/lang/String;II)V", Self::write_string, MethodAccessFlags::PUBLIC),
34 JavaMethodProto::new("writeTo", "(Ljava/io/Writer;)V", Self::write_to, MethodAccessFlags::PUBLIC),
35 JavaMethodProto::new("reset", "()V", Self::reset, MethodAccessFlags::PUBLIC),
36 JavaMethodProto::new("toCharArray", "()[C", Self::to_char_array, MethodAccessFlags::PUBLIC),
37 JavaMethodProto::new("size", "()I", Self::size, MethodAccessFlags::PUBLIC),
38 JavaMethodProto::new("toString", "()Ljava/lang/String;", Self::to_string, MethodAccessFlags::PUBLIC),
39 JavaMethodProto::new("flush", "()V", Self::flush, MethodAccessFlags::PUBLIC),
40 JavaMethodProto::new("close", "()V", Self::close, MethodAccessFlags::PUBLIC),
41 ],
42 fields: vec![
43 JavaFieldProto::new("buf", "[C", FieldAccessFlags::PROTECTED),
44 JavaFieldProto::new("count", "I", FieldAccessFlags::PROTECTED),
45 ],
46 access_flags: ClassAccessFlags::PUBLIC,
47 }
48 }
49
50 async fn init(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
51 tracing::debug!("java.io.CharArrayWriter::<init>({this:?})");
52 jvm.invoke_special(&this, "java/io/CharArrayWriter", "<init>", "(I)V", (DEFAULT_INITIAL_BUFFER_SIZE,))
53 .await
54 }
55
56 async fn init_with_size(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, size: i32) -> Result<()> {
57 tracing::debug!("java.io.CharArrayWriter::<init>({this:?}, {size})");
58
59 if size < 0 {
60 return Err(jvm.exception("java/lang/IllegalArgumentException", "Negative initial size").await);
61 }
62 let _: () = jvm.invoke_special(&this, "java/io/Writer", "<init>", "()V", ()).await?;
63 let buffer = jvm.instantiate_array("C", size as usize).await?;
64 jvm.put_field(&mut this, "java/io/CharArrayWriter", "buf", "[C", buffer).await?;
65 jvm.put_field(&mut this, "java/io/CharArrayWriter", "count", "I", 0).await
66 }
67
68 async fn with_lock<T, F>(jvm: &Jvm, lock: &ClassInstanceRef<Object>, operation: F) -> Result<T>
69 where
70 F: Future<Output = Result<T>>,
71 {
72 jvm.monitor_enter(lock).await?;
73 match operation.await {
74 Ok(value) => {
75 jvm.monitor_exit(lock).await?;
76 Ok(value)
77 }
78 Err(error) => {
79 if let Err(exit_error) = jvm.monitor_exit(lock).await {
80 tracing::error!(?exit_error, "failed to release CharArrayWriter lock");
81 }
82 Err(error)
83 }
84 }
85 }
86
87 async fn ensure_capacity(jvm: &Jvm, this: &mut ClassInstanceRef<Self>, minimum: i32) -> Result<()> {
88 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(this, "java/io/CharArrayWriter", "buf", "[C").await?;
89 let current = jvm.array_length(&buffer).await? as i32;
90 if minimum > current {
91 let new_length = current.saturating_mul(2).max(minimum).max(1);
92 let new_buffer = jvm.instantiate_array("C", new_length as usize).await?;
93 let count: i32 = jvm.get_field(this, "java/io/CharArrayWriter", "count", "I").await?;
94 let _: () = jvm
95 .invoke_static(
96 "java/lang/System",
97 "arraycopy",
98 "(Ljava/lang/Object;ILjava/lang/Object;II)V",
99 (buffer, 0, new_buffer.clone(), 0, count),
100 )
101 .await?;
102 jvm.put_field(this, "java/io/CharArrayWriter", "buf", "[C", new_buffer).await?;
103 }
104 Ok(())
105 }
106
107 async fn write_char(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
108 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
109 Self::with_lock(jvm, &lock, Self::write_char_locked(jvm, this, value)).await
110 }
111
112 async fn write_char_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
113 tracing::debug!("java.io.CharArrayWriter::write({this:?}, {value})");
114
115 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
116 Self::ensure_capacity(jvm, &mut this, count + 1).await?;
117 let mut buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
118 jvm.store_array(&mut buffer, count as usize, [value as JavaChar]).await?;
119 jvm.put_field(&mut this, "java/io/CharArrayWriter", "count", "I", count + 1).await
120 }
121
122 async fn write_chars(
123 jvm: &Jvm,
124 _: &mut RuntimeContext,
125 this: ClassInstanceRef<Self>,
126 chars: ClassInstanceRef<Array<JavaChar>>,
127 offset: i32,
128 length: i32,
129 ) -> Result<()> {
130 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
131 Self::with_lock(jvm, &lock, Self::write_chars_locked(jvm, this, chars, offset, length)).await
132 }
133
134 async fn write_chars_locked(
135 jvm: &Jvm,
136 mut this: ClassInstanceRef<Self>,
137 chars: ClassInstanceRef<Array<JavaChar>>,
138 offset: i32,
139 length: i32,
140 ) -> Result<()> {
141 tracing::debug!("java.io.CharArrayWriter::write({this:?}, {chars:?}, {offset}, {length})");
142
143 if chars.is_null() {
144 return Err(jvm.exception("java/lang/NullPointerException", "character array is null").await);
145 }
146 let source_length = jvm.array_length(&chars).await? as i32;
147 if offset < 0 || length < 0 || offset > source_length - length {
148 return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
149 }
150 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
151 Self::ensure_capacity(jvm, &mut this, count + length).await?;
152 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
153 let _: () = jvm
154 .invoke_static(
155 "java/lang/System",
156 "arraycopy",
157 "(Ljava/lang/Object;ILjava/lang/Object;II)V",
158 (chars, offset, buffer, count, length),
159 )
160 .await?;
161 jvm.put_field(&mut this, "java/io/CharArrayWriter", "count", "I", count + length).await
162 }
163
164 async fn write_string(
165 jvm: &Jvm,
166 _: &mut RuntimeContext,
167 this: ClassInstanceRef<Self>,
168 value: ClassInstanceRef<String>,
169 offset: i32,
170 length: i32,
171 ) -> Result<()> {
172 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
173 Self::with_lock(jvm, &lock, Self::write_string_locked(jvm, this, value, offset, length)).await
174 }
175
176 async fn write_string_locked(
177 jvm: &Jvm,
178 mut this: ClassInstanceRef<Self>,
179 value: ClassInstanceRef<String>,
180 offset: i32,
181 length: i32,
182 ) -> Result<()> {
183 tracing::debug!("java.io.CharArrayWriter::write({this:?}, {value:?}, {offset}, {length})");
184
185 if value.is_null() {
186 return Err(jvm.exception("java/lang/NullPointerException", "string is null").await);
187 }
188 let source_length: i32 = jvm.invoke_virtual(&value, "java/lang/String", "length", "()I", ()).await?;
189 if offset < 0 || length < 0 || offset > source_length - length {
190 return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
191 }
192 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
193 Self::ensure_capacity(jvm, &mut this, count + length).await?;
194 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
195 let _: () = jvm
196 .invoke_virtual(
197 &value,
198 "java/lang/String",
199 "getChars",
200 "(II[CI)V",
201 (offset, offset + length, buffer, count),
202 )
203 .await?;
204 jvm.put_field(&mut this, "java/io/CharArrayWriter", "count", "I", count + length).await
205 }
206
207 async fn write_to(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, out: ClassInstanceRef<Writer>) -> Result<()> {
208 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
209 Self::with_lock(jvm, &lock, Self::write_to_locked(jvm, this, out)).await
210 }
211
212 async fn write_to_locked(jvm: &Jvm, this: ClassInstanceRef<Self>, out: ClassInstanceRef<Writer>) -> Result<()> {
213 tracing::debug!("java.io.CharArrayWriter::writeTo({this:?}, {out:?})");
214
215 if out.is_null() {
216 return Err(jvm.exception("java/lang/NullPointerException", "writer is null").await);
217 }
218 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
219 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
220 jvm.invoke_virtual(&out, "java/io/Writer", "write", "([CII)V", (buffer, 0, count)).await
221 }
222
223 async fn reset(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
224 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
225 Self::with_lock(jvm, &lock, Self::reset_locked(jvm, this)).await
226 }
227
228 async fn reset_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>) -> Result<()> {
229 tracing::debug!("java.io.CharArrayWriter::reset({this:?})");
230 jvm.put_field(&mut this, "java/io/CharArrayWriter", "count", "I", 0).await
231 }
232
233 async fn to_char_array(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<Array<JavaChar>>> {
234 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
235 Self::with_lock(jvm, &lock, Self::to_char_array_locked(jvm, this)).await
236 }
237
238 async fn to_char_array_locked(jvm: &Jvm, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<Array<JavaChar>>> {
239 tracing::debug!("java.io.CharArrayWriter::toCharArray({this:?})");
240
241 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
242 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
243 let copy = jvm.instantiate_array("C", count as usize).await?;
244 let _: () = jvm
245 .invoke_static(
246 "java/lang/System",
247 "arraycopy",
248 "(Ljava/lang/Object;ILjava/lang/Object;II)V",
249 (buffer, 0, copy.clone(), 0, count),
250 )
251 .await?;
252 Ok(copy.into())
253 }
254
255 async fn size(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<i32> {
256 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
257 Self::with_lock(jvm, &lock, Self::size_locked(jvm, this)).await
258 }
259
260 async fn size_locked(jvm: &Jvm, this: ClassInstanceRef<Self>) -> Result<i32> {
261 tracing::debug!("java.io.CharArrayWriter::size({this:?})");
262 jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await
263 }
264
265 async fn to_string(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<String>> {
266 let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/CharArrayWriter", "lock", "Ljava/lang/Object;").await?;
267 Self::with_lock(jvm, &lock, Self::to_string_locked(jvm, this)).await
268 }
269
270 async fn to_string_locked(jvm: &Jvm, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<String>> {
271 tracing::debug!("java.io.CharArrayWriter::toString({this:?})");
272
273 let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/CharArrayWriter", "buf", "[C").await?;
274 let count: i32 = jvm.get_field(&this, "java/io/CharArrayWriter", "count", "I").await?;
275 Ok(jvm.new_class("java/lang/String", "([CII)V", (buffer, 0, count)).await?.into())
276 }
277
278 async fn flush(_: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
279 tracing::debug!("java.io.CharArrayWriter::flush({this:?})");
280 Ok(())
281 }
282
283 async fn close(_: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
284 tracing::debug!("java.io.CharArrayWriter::close({this:?})");
285 Ok(())
286 }
287}