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, "java/io/BufferedWriter", "out", "Ljava/io/Writer;", out).await?;
90        jvm.put_field(&mut this, "java/io/BufferedWriter", "cb", "[C", buffer).await?;
91        jvm.put_field(&mut this, "java/io/BufferedWriter", "nChars", "I", size).await?;
92        jvm.put_field(&mut this, "java/io/BufferedWriter", "nextChar", "I", 0).await?;
93        jvm.put_field(&mut this, "java/io/BufferedWriter", "lineSeparator", "Ljava/lang/String;", line_separator)
94            .await
95    }
96
97    async fn with_lock<T, F>(jvm: &Jvm, lock: &ClassInstanceRef<Object>, operation: F) -> Result<T>
98    where
99        F: Future<Output = Result<T>>,
100    {
101        jvm.monitor_enter(lock).await?;
102        match operation.await {
103            Ok(value) => {
104                jvm.monitor_exit(lock).await?;
105                Ok(value)
106            }
107            Err(error) => {
108                if let Err(exit_error) = jvm.monitor_exit(lock).await {
109                    tracing::error!(?exit_error, "failed to release BufferedWriter lock");
110                }
111                Err(error)
112            }
113        }
114    }
115
116    async fn flush_buffer(jvm: &Jvm, this: &mut ClassInstanceRef<Self>) -> Result<()> {
117        let out: ClassInstanceRef<Writer> = jvm.get_field(this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
118        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(this, "java/io/BufferedWriter", "cb", "[C").await?;
119        if out.is_null() || buffer.is_null() {
120            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
121        }
122        let next_char: i32 = jvm.get_field(this, "java/io/BufferedWriter", "nextChar", "I").await?;
123        if next_char > 0 {
124            let _: () = jvm
125                .invoke_virtual(&out, "java/io/Writer", "write", "([CII)V", (buffer, 0, next_char))
126                .await?;
127            jvm.put_field(this, "java/io/BufferedWriter", "nextChar", "I", 0).await?;
128        }
129        Ok(())
130    }
131
132    async fn write_char(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
133        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
134        Self::with_lock(jvm, &lock, Self::write_char_locked(jvm, this, value)).await
135    }
136
137    async fn write_char_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
138        tracing::debug!("java.io.BufferedWriter::write({this:?}, {value})");
139
140        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
141        let mut buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
142        if out.is_null() || buffer.is_null() {
143            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
144        }
145        let n_chars: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nChars", "I").await?;
146        let mut next_char: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nextChar", "I").await?;
147        if next_char >= n_chars {
148            Self::flush_buffer(jvm, &mut this).await?;
149            next_char = 0;
150            buffer = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
151        }
152        jvm.store_array(&mut buffer, next_char as usize, [value as JavaChar]).await?;
153        jvm.put_field(&mut this, "java/io/BufferedWriter", "nextChar", "I", next_char + 1).await
154    }
155
156    async fn write_chars(
157        jvm: &Jvm,
158        _: &mut RuntimeContext,
159        this: ClassInstanceRef<Self>,
160        chars: ClassInstanceRef<Array<JavaChar>>,
161        offset: i32,
162        length: i32,
163    ) -> Result<()> {
164        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
165        Self::with_lock(jvm, &lock, Self::write_chars_locked(jvm, this, chars, offset, length)).await
166    }
167
168    async fn write_chars_locked(
169        jvm: &Jvm,
170        mut this: ClassInstanceRef<Self>,
171        chars: ClassInstanceRef<Array<JavaChar>>,
172        offset: i32,
173        length: i32,
174    ) -> Result<()> {
175        tracing::debug!("java.io.BufferedWriter::write({this:?}, {chars:?}, {offset}, {length})");
176
177        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
178        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
179        if out.is_null() || buffer.is_null() {
180            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
181        }
182        if chars.is_null() {
183            return Err(jvm.exception("java/lang/NullPointerException", "character array is null").await);
184        }
185        let source_length = jvm.array_length(&chars).await? as i32;
186        if offset < 0 || length < 0 || offset > source_length - length {
187            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
188        }
189        if length == 0 {
190            return Ok(());
191        }
192        let n_chars: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nChars", "I").await?;
193        if length >= n_chars {
194            Self::flush_buffer(jvm, &mut this).await?;
195            return jvm
196                .invoke_virtual(&out, "java/io/Writer", "write", "([CII)V", (chars, offset, length))
197                .await;
198        }
199
200        let mut source_position = offset;
201        let end = offset + length;
202        while source_position < end {
203            let mut next_char: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nextChar", "I").await?;
204            let copied = (n_chars - next_char).min(end - source_position);
205            let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
206            let _: () = jvm
207                .invoke_static(
208                    "java/lang/System",
209                    "arraycopy",
210                    "(Ljava/lang/Object;ILjava/lang/Object;II)V",
211                    (chars.clone(), source_position, buffer, next_char, copied),
212                )
213                .await?;
214            source_position += copied;
215            next_char += copied;
216            jvm.put_field(&mut this, "java/io/BufferedWriter", "nextChar", "I", next_char).await?;
217            if next_char >= n_chars {
218                Self::flush_buffer(jvm, &mut this).await?;
219            }
220        }
221        Ok(())
222    }
223
224    async fn write_string(
225        jvm: &Jvm,
226        _: &mut RuntimeContext,
227        this: ClassInstanceRef<Self>,
228        value: ClassInstanceRef<String>,
229        offset: i32,
230        length: i32,
231    ) -> Result<()> {
232        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
233        Self::with_lock(jvm, &lock, Self::write_string_locked(jvm, this, value, offset, length)).await
234    }
235
236    async fn write_string_locked(
237        jvm: &Jvm,
238        mut this: ClassInstanceRef<Self>,
239        value: ClassInstanceRef<String>,
240        offset: i32,
241        length: i32,
242    ) -> Result<()> {
243        tracing::debug!("java.io.BufferedWriter::write({this:?}, {value:?}, {offset}, {length})");
244
245        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
246        let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
247        if out.is_null() || buffer.is_null() {
248            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
249        }
250        if value.is_null() {
251            return Err(jvm.exception("java/lang/NullPointerException", "string is null").await);
252        }
253        let string_length: i32 = jvm.invoke_virtual(&value, "java/lang/String", "length", "()I", ()).await?;
254        if offset < 0 || length < 0 || offset > string_length - length {
255            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
256        }
257        let n_chars: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nChars", "I").await?;
258        let mut source_position = offset;
259        let end = offset + length;
260        while source_position < end {
261            let mut next_char: i32 = jvm.get_field(&this, "java/io/BufferedWriter", "nextChar", "I").await?;
262            let copied = (n_chars - next_char).min(end - source_position);
263            let buffer: ClassInstanceRef<Array<JavaChar>> = jvm.get_field(&this, "java/io/BufferedWriter", "cb", "[C").await?;
264            let _: () = jvm
265                .invoke_virtual(
266                    &value,
267                    "java/lang/String",
268                    "getChars",
269                    "(II[CI)V",
270                    (source_position, source_position + copied, buffer, next_char),
271                )
272                .await?;
273            source_position += copied;
274            next_char += copied;
275            jvm.put_field(&mut this, "java/io/BufferedWriter", "nextChar", "I", next_char).await?;
276            if next_char >= n_chars {
277                Self::flush_buffer(jvm, &mut this).await?;
278            }
279        }
280        Ok(())
281    }
282
283    async fn new_line(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
284        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
285        Self::with_lock(jvm, &lock, Self::new_line_locked(jvm, this)).await
286    }
287
288    async fn new_line_locked(jvm: &Jvm, this: ClassInstanceRef<Self>) -> Result<()> {
289        tracing::debug!("java.io.BufferedWriter::newLine({this:?})");
290
291        let line_separator: ClassInstanceRef<String> = jvm
292            .get_field(&this, "java/io/BufferedWriter", "lineSeparator", "Ljava/lang/String;")
293            .await?;
294        let length: i32 = jvm.invoke_virtual(&line_separator, "java/lang/String", "length", "()I", ()).await?;
295        Self::write_string_locked(jvm, this, line_separator, 0, length).await
296    }
297
298    async fn flush(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
299        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
300        Self::with_lock(jvm, &lock, Self::flush_locked(jvm, this)).await
301    }
302
303    async fn flush_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>) -> Result<()> {
304        tracing::debug!("java.io.BufferedWriter::flush({this:?})");
305
306        Self::flush_buffer(jvm, &mut this).await?;
307        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
308        jvm.invoke_virtual(&out, "java/io/Writer", "flush", "()V", ()).await
309    }
310
311    async fn close(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
312        let lock: ClassInstanceRef<Object> = jvm.get_field(&this, "java/io/BufferedWriter", "lock", "Ljava/lang/Object;").await?;
313        Self::with_lock(jvm, &lock, Self::close_locked(jvm, this)).await
314    }
315
316    async fn close_locked(jvm: &Jvm, mut this: ClassInstanceRef<Self>) -> Result<()> {
317        tracing::debug!("java.io.BufferedWriter::close({this:?})");
318
319        let out: ClassInstanceRef<Writer> = jvm.get_field(&this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;").await?;
320        if out.is_null() {
321            return Ok(());
322        }
323        let flush_result = Self::flush_buffer(jvm, &mut this).await;
324        let close_result: Result<()> = jvm.invoke_virtual(&out, "java/io/Writer", "close", "()V", ()).await;
325        let null_writer: ClassInstanceRef<Writer> = None.into();
326        let null_buffer: ClassInstanceRef<Array<JavaChar>> = None.into();
327        let clear_out_result = jvm
328            .put_field(&mut this, "java/io/BufferedWriter", "out", "Ljava/io/Writer;", null_writer)
329            .await;
330        let clear_buffer_result = jvm.put_field(&mut this, "java/io/BufferedWriter", "cb", "[C", null_buffer).await;
331
332        flush_result?;
333        close_result?;
334        clear_out_result?;
335        clear_buffer_result
336    }
337}