Skip to main content

rustjava_runtime/classes/java/io/
buffered_writer.rs

1use core::future::Future;
2
3use alloc::vec;
4
5use jvm::{Array, ClassInstanceRef, JavaChar, 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::{
12        io::Writer,
13        lang::{Object, String},
14    },
15};
16
17const DEFAULT_CHAR_BUFFER_SIZE: i32 = 8192;
18
19// class java.io.BufferedWriter
20pub struct BufferedWriter;
21
22impl BufferedWriter {
23    pub fn as_proto() -> RuntimeClassProto {
24        RuntimeClassProto {
25            name: "java/io/BufferedWriter",
26            parent_class: Some("java/io/Writer"),
27            interfaces: vec![],
28            methods: vec![
29                JavaMethodProto::new("<init>", "(Ljava/io/Writer;)V", Self::init, MethodAccessFlags::PUBLIC),
30                JavaMethodProto::new("<init>", "(Ljava/io/Writer;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("newLine", "()V", Self::new_line, MethodAccessFlags::PUBLIC),
35                JavaMethodProto::new("flush", "()V", Self::flush, MethodAccessFlags::PUBLIC),
36                JavaMethodProto::new("close", "()V", Self::close, MethodAccessFlags::PUBLIC),
37            ],
38            fields: vec![
39                JavaFieldProto::new("out", "Ljava/io/Writer;", FieldAccessFlags::PRIVATE),
40                JavaFieldProto::new("cb", "[C", FieldAccessFlags::PRIVATE),
41                JavaFieldProto::new("nChars", "I", FieldAccessFlags::PRIVATE),
42                JavaFieldProto::new("nextChar", "I", FieldAccessFlags::PRIVATE),
43                JavaFieldProto::new("lineSeparator", "Ljava/lang/String;", FieldAccessFlags::PRIVATE),
44            ],
45            access_flags: ClassAccessFlags::PUBLIC,
46        }
47    }
48
49    async fn init(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, out: ClassInstanceRef<Writer>) -> Result<()> {
50        tracing::debug!("java.io.BufferedWriter::<init>({this:?}, {out:?})");
51        jvm.invoke_special(
52            &this,
53            "java/io/BufferedWriter",
54            "<init>",
55            "(Ljava/io/Writer;I)V",
56            (out, DEFAULT_CHAR_BUFFER_SIZE),
57        )
58        .await
59    }
60
61    async fn init_with_size(
62        jvm: &Jvm,
63        _: &mut RuntimeContext,
64        mut this: ClassInstanceRef<Self>,
65        out: ClassInstanceRef<Writer>,
66        size: i32,
67    ) -> Result<()> {
68        tracing::debug!("java.io.BufferedWriter::<init>({this:?}, {out:?}, {size})");
69
70        if out.is_null() {
71            return Err(jvm.exception("java/lang/NullPointerException", "writer is null").await);
72        }
73        if size <= 0 {
74            return Err(jvm.exception("java/lang/IllegalArgumentException", "Buffer size <= 0").await);
75        }
76
77        let _: () = jvm
78            .invoke_special(&this, "java/io/Writer", "<init>", "(Ljava/lang/Object;)V", (out.clone(),))
79            .await?;
80        let buffer = jvm.instantiate_array("C", size as usize).await?;
81        let key = JavaLangString::from_rust_string(jvm, "line.separator").await?;
82        let mut line_separator: ClassInstanceRef<String> = jvm
83            .invoke_static("java/lang/System", "getProperty", "(Ljava/lang/String;)Ljava/lang/String;", (key,))
84            .await?;
85        if line_separator.is_null() {
86            line_separator = JavaLangString::from_rust_string(jvm, "\n").await?.into();
87        }
88
89        jvm.put_field(&mut this, "out", "Ljava/io/Writer;", out).await?;
90        jvm.put_field(&mut this, "cb", "[C", buffer).await?;
91        jvm.put_field(&mut this, "nChars", "I", size).await?;
92        jvm.put_field(&mut this, "nextChar", "I", 0).await?;
93        jvm.put_field(&mut this, "lineSeparator", "Ljava/lang/String;", line_separator).await
94    }
95
96    async fn with_lock<T, F>(jvm: &Jvm, lock: &ClassInstanceRef<Object>, operation: F) -> Result<T>
97    where
98        F: Future<Output = Result<T>>,
99    {
100        jvm.monitor_enter(lock).await?;
101        match operation.await {
102            Ok(value) => {
103                jvm.monitor_exit(lock).await?;
104                Ok(value)
105            }
106            Err(error) => {
107                if let Err(exit_error) = jvm.monitor_exit(lock).await {
108                    tracing::error!(?exit_error, "failed to release BufferedWriter lock");
109                }
110                Err(error)
111            }
112        }
113    }
114
115    async fn flush_buffer(jvm: &Jvm, this: &mut ClassInstanceRef<Self>) -> Result<()> {
116        let out: ClassInstanceRef<Writer> = jvm.get_field(this, "out", "Ljava/io/Writer;").await?;
117        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(this, "cb", "[C").await?;
118        if out.is_null() || buffer.is_null() {
119            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
120        }
121        let next_char: i32 = jvm.get_field(this, "nextChar", "I").await?;
122        if next_char > 0 {
123            let _: () = jvm
124                .invoke_virtual(&out, "java/io/Writer", "write", "([CII)V", (buffer, 0, next_char))
125                .await?;
126            jvm.put_field(this, "nextChar", "I", 0).await?;
127        }
128        Ok(())
129    }
130
131    async fn write_char(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
132        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
133        Self::with_lock(jvm, &lock, Self::write_char_locked(jvm, this, value)).await
134    }
135
136    async fn write_char_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
137        tracing::debug!("java.io.BufferedWriter::write({this:?}, {value})");
138
139        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "out", "Ljava/io/Writer;").await?;
140        let mut buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "cb", "[C").await?;
141        if out.is_null() || buffer.is_null() {
142            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
143        }
144        let n_chars: i32 = jvm.get_field(&this, "nChars", "I").await?;
145        let mut next_char: i32 = jvm.get_field(&this, "nextChar", "I").await?;
146        if next_char >= n_chars {
147            Self::flush_buffer(jvm, &mut this).await?;
148            next_char = 0;
149            buffer = jvm.get_field(&this, "cb", "[C").await?;
150        }
151        jvm.store_array(&mut buffer, next_char as usize, [value as JavaChar]).await?;
152        jvm.put_field(&mut this, "nextChar", "I", next_char + 1).await
153    }
154
155    async fn write_chars(
156        jvm: &Jvm,
157        _: &mut RuntimeContext,
158        this: ClassInstanceRef<Self>,
159        chars: ClassInstanceRef<Array<JavaChar>>,
160        offset: i32,
161        length: i32,
162    ) -> Result<()> {
163        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
164        Self::with_lock(jvm, &lock, Self::write_chars_locked(jvm, this, chars, offset, length)).await
165    }
166
167    async fn write_chars_locked(
168        jvm: &Jvm,
169        mut this: ClassInstanceRef<Self>,
170        chars: ClassInstanceRef<Array<JavaChar>>,
171        offset: i32,
172        length: i32,
173    ) -> Result<()> {
174        tracing::debug!("java.io.BufferedWriter::write({this:?}, {chars:?}, {offset}, {length})");
175
176        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "out", "Ljava/io/Writer;").await?;
177        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "cb", "[C").await?;
178        if out.is_null() || buffer.is_null() {
179            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
180        }
181        if chars.is_null() {
182            return Err(jvm.exception("java/lang/NullPointerException", "character array is null").await);
183        }
184        let source_length = jvm.array_length(&chars).await? as i32;
185        if offset < 0 || length < 0 || offset > source_length - length {
186            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
187        }
188        if length == 0 {
189            return Ok(());
190        }
191        let n_chars: i32 = jvm.get_field(&this, "nChars", "I").await?;
192        if length >= n_chars {
193            Self::flush_buffer(jvm, &mut this).await?;
194            return jvm
195                .invoke_virtual(&out, "java/io/Writer", "write", "([CII)V", (chars, offset, length))
196                .await;
197        }
198
199        let mut source_position = offset;
200        let end = offset + length;
201        while source_position < end {
202            let mut next_char: i32 = jvm.get_field(&this, "nextChar", "I").await?;
203            let copied = (n_chars - next_char).min(end - source_position);
204            let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "cb", "[C").await?;
205            let _: () = jvm
206                .invoke_static(
207                    "java/lang/System",
208                    "arraycopy",
209                    "(Ljava/lang/Object;ILjava/lang/Object;II)V",
210                    (chars.clone(), source_position, buffer, next_char, copied),
211                )
212                .await?;
213            source_position += copied;
214            next_char += copied;
215            jvm.put_field(&mut this, "nextChar", "I", next_char).await?;
216            if next_char >= n_chars {
217                Self::flush_buffer(jvm, &mut this).await?;
218            }
219        }
220        Ok(())
221    }
222
223    async fn write_string(
224        jvm: &Jvm,
225        _: &mut RuntimeContext,
226        this: ClassInstanceRef<Self>,
227        value: ClassInstanceRef<String>,
228        offset: i32,
229        length: i32,
230    ) -> Result<()> {
231        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
232        Self::with_lock(jvm, &lock, Self::write_string_locked(jvm, this, value, offset, length)).await
233    }
234
235    async fn write_string_locked(
236        jvm: &Jvm,
237        mut this: ClassInstanceRef<Self>,
238        value: ClassInstanceRef<String>,
239        offset: i32,
240        length: i32,
241    ) -> Result<()> {
242        tracing::debug!("java.io.BufferedWriter::write({this:?}, {value:?}, {offset}, {length})");
243
244        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "out", "Ljava/io/Writer;").await?;
245        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "cb", "[C").await?;
246        if out.is_null() || buffer.is_null() {
247            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
248        }
249        if value.is_null() {
250            return Err(jvm.exception("java/lang/NullPointerException", "string is null").await);
251        }
252        let string_length: i32 = jvm.invoke_virtual(&value, "java/lang/String", "length", "()I", ()).await?;
253        if offset < 0 || length < 0 || offset > string_length - length {
254            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
255        }
256        let n_chars: i32 = jvm.get_field(&this, "nChars", "I").await?;
257        let mut source_position = offset;
258        let end = offset + length;
259        while source_position < end {
260            let mut next_char: i32 = jvm.get_field(&this, "nextChar", "I").await?;
261            let copied = (n_chars - next_char).min(end - source_position);
262            let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "cb", "[C").await?;
263            let _: () = jvm
264                .invoke_virtual(
265                    &value,
266                    "java/lang/String",
267                    "getChars",
268                    "(II[CI)V",
269                    (source_position, source_position + copied, buffer, next_char),
270                )
271                .await?;
272            source_position += copied;
273            next_char += copied;
274            jvm.put_field(&mut this, "nextChar", "I", next_char).await?;
275            if next_char >= n_chars {
276                Self::flush_buffer(jvm, &mut this).await?;
277            }
278        }
279        Ok(())
280    }
281
282    async fn new_line(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
283        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
284        Self::with_lock(jvm, &lock, Self::new_line_locked(jvm, this)).await
285    }
286
287    async fn new_line_locked(jvm: &Jvm, this: ClassInstanceRef<Self>) -> Result<()> {
288        tracing::debug!("java.io.BufferedWriter::newLine({this:?})");
289
290        let line_separator: ClassInstanceRef<String> = jvm.get_field(&this, "lineSeparator", "Ljava/lang/String;").await?;
291        let length: i32 = jvm.invoke_virtual(&line_separator, "java/lang/String", "length", "()I", ()).await?;
292        Self::write_string_locked(jvm, this, line_separator, 0, length).await
293    }
294
295    async fn flush(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
296        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
297        Self::with_lock(jvm, &lock, Self::flush_locked(jvm, this)).await
298    }
299
300    async fn flush_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>) -> Result<()> {
301        tracing::debug!("java.io.BufferedWriter::flush({this:?})");
302
303        Self::flush_buffer(jvm, &mut this).await?;
304        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "out", "Ljava/io/Writer;").await?;
305        jvm.invoke_virtual(&out, "java/io/Writer", "flush", "()V", ()).await
306    }
307
308    async fn close(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
309        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "lock", "Ljava/lang/Object;").await?;
310        Self::with_lock(jvm, &lock, Self::close_locked(jvm, this)).await
311    }
312
313    async fn close_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>) -> Result<()> {
314        tracing::debug!("java.io.BufferedWriter::close({this:?})");
315
316        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "out", "Ljava/io/Writer;").await?;
317        if out.is_null() {
318            return Ok(());
319        }
320        let flush_result = Self::flush_buffer(jvm, &mut this).await;
321        let close_result: Result<()> = jvm.invoke_virtual(&out, "java/io/Writer", "close", "()V", ()).await;
322        let null_writer: ClassInstanceRef<Writer> = None.into();
323        let null_buffer: ClassInstanceRef<Array<JavaChar>> = None.into();
324        let clear_out_result = jvm.put_field(&mut this, "out", "Ljava/io/Writer;", null_writer).await;
325        let clear_buffer_result = jvm.put_field(&mut this, "cb", "[C", null_buffer).await;
326
327        flush_result?;
328        close_result?;
329        clear_out_result?;
330        clear_buffer_result
331    }
332}