Skip to main content

rustjava_runtime/classes/java/io/
buffered_output_stream.rs

1use alloc::vec;
2
3use jvm::{Array, ClassInstanceRef, Jvm, Result};
4use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
5use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
6
7use crate::{RuntimeClassProto, RuntimeContext, classes::java::io::OutputStream};
8
9const DEFAULT_BUFFER_SIZE: i32 = 8192;
10
11// class java.io.BufferedOutputStream
12pub struct BufferedOutputStream;
13
14impl BufferedOutputStream {
15    pub fn as_proto() -> RuntimeClassProto {
16        RuntimeClassProto {
17            name: "java/io/BufferedOutputStream",
18            parent_class: Some("java/io/FilterOutputStream"),
19            interfaces: vec![],
20            methods: vec![
21                JavaMethodProto::new("<init>", "(Ljava/io/OutputStream;)V", Self::init, MethodAccessFlags::PUBLIC),
22                JavaMethodProto::new("<init>", "(Ljava/io/OutputStream;I)V", Self::init_with_size, MethodAccessFlags::PUBLIC),
23                JavaMethodProto::new("write", "(I)V", Self::write, MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED),
24                JavaMethodProto::new(
25                    "write",
26                    "([BII)V",
27                    Self::write_bytes,
28                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
29                ),
30                JavaMethodProto::new("flush", "()V", Self::flush, MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED),
31            ],
32            fields: vec![
33                JavaFieldProto::new("buf", "[B", FieldAccessFlags::PROTECTED),
34                JavaFieldProto::new("count", "I", FieldAccessFlags::PROTECTED),
35            ],
36            access_flags: ClassAccessFlags::PUBLIC,
37        }
38    }
39
40    async fn init(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, out: ClassInstanceRef<OutputStream>) -> Result<()> {
41        tracing::debug!("java.io.BufferedOutputStream::<init>({this:?}, {out:?})");
42        jvm.invoke_special(
43            &this,
44            "java/io/BufferedOutputStream",
45            "<init>",
46            "(Ljava/io/OutputStream;I)V",
47            (out, DEFAULT_BUFFER_SIZE),
48        )
49        .await
50    }
51
52    async fn init_with_size(
53        jvm: &Jvm,
54        _: &mut RuntimeContext,
55        mut this: ClassInstanceRef<Self>,
56        out: ClassInstanceRef<OutputStream>,
57        size: i32,
58    ) -> Result<()> {
59        tracing::debug!("java.io.BufferedOutputStream::<init>({this:?}, {out:?}, {size})");
60
61        if out.is_null() {
62            return Err(jvm.exception("java/lang/NullPointerException", "output is null").await);
63        }
64        if size <= 0 {
65            return Err(jvm.exception("java/lang/IllegalArgumentException", "Buffer size <= 0").await);
66        }
67
68        let _: () = jvm
69            .invoke_special(&this, "java/io/FilterOutputStream", "<init>", "(Ljava/io/OutputStream;)V", (out,))
70            .await?;
71        let buffer = jvm.instantiate_array("B", size as usize).await?;
72        jvm.put_field(&mut this, "buf", "[B", buffer).await?;
73        jvm.put_field(&mut this, "count", "I", 0).await
74    }
75
76    async fn flush_buffer(jvm: &Jvm, this: &mut ClassInstanceRef<Self>) -> Result<()> {
77        let out: ClassInstanceRef<OutputStream> = jvm.get_field(this, "out", "Ljava/io/OutputStream;").await?;
78        let buffer: ClassInstanceRef<Array<i8>> = jvm.get_field(this, "buf", "[B").await?;
79        if out.is_null() || buffer.is_null() {
80            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
81        }
82        let count: i32 = jvm.get_field(this, "count", "I").await?;
83        if count > 0 {
84            let _: () = jvm
85                .invoke_virtual(&out, "java/io/OutputStream", "write", "([BII)V", (buffer, 0, count))
86                .await?;
87            jvm.put_field(this, "count", "I", 0).await?;
88        }
89        Ok(())
90    }
91
92    async fn write(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, value: i32) -> Result<()> {
93        tracing::debug!("java.io.BufferedOutputStream::write({this:?}, {value})");
94
95        let out: ClassInstanceRef<OutputStream> = jvm.get_field(&this, "out", "Ljava/io/OutputStream;").await?;
96        let mut buffer: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
97        if out.is_null() || buffer.is_null() {
98            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
99        }
100        let mut count: i32 = jvm.get_field(&this, "count", "I").await?;
101        if count >= jvm.array_length(&buffer).await? as i32 {
102            Self::flush_buffer(jvm, &mut this).await?;
103            count = 0;
104            buffer = jvm.get_field(&this, "buf", "[B").await?;
105        }
106        jvm.store_array(&mut buffer, count as usize, [value as i8]).await?;
107        jvm.put_field(&mut this, "count", "I", count + 1).await
108    }
109
110    async fn write_bytes(
111        jvm: &Jvm,
112        _: &mut RuntimeContext,
113        mut this: ClassInstanceRef<Self>,
114        bytes: ClassInstanceRef<Array<i8>>,
115        offset: i32,
116        length: i32,
117    ) -> Result<()> {
118        tracing::debug!("java.io.BufferedOutputStream::write({this:?}, {bytes:?}, {offset}, {length})");
119
120        let source_length = jvm.array_length(&bytes).await? as i32;
121        if offset < 0 || length < 0 || offset > source_length - length {
122            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
123        }
124        let out: ClassInstanceRef<OutputStream> = jvm.get_field(&this, "out", "Ljava/io/OutputStream;").await?;
125        let mut buffer: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
126        if out.is_null() || buffer.is_null() {
127            return Err(jvm.exception("java/io/IOException", "Stream closed").await);
128        }
129        if length == 0 {
130            return Ok(());
131        }
132
133        let buffer_length = jvm.array_length(&buffer).await? as i32;
134        if length >= buffer_length {
135            Self::flush_buffer(jvm, &mut this).await?;
136            return jvm
137                .invoke_virtual(&out, "java/io/OutputStream", "write", "([BII)V", (bytes, offset, length))
138                .await;
139        }
140
141        let mut count: i32 = jvm.get_field(&this, "count", "I").await?;
142        if length > buffer_length - count {
143            Self::flush_buffer(jvm, &mut this).await?;
144            count = 0;
145            buffer = jvm.get_field(&this, "buf", "[B").await?;
146        }
147        let _: () = jvm
148            .invoke_static(
149                "java/lang/System",
150                "arraycopy",
151                "(Ljava/lang/Object;ILjava/lang/Object;II)V",
152                (bytes, offset, buffer, count, length),
153            )
154            .await?;
155        jvm.put_field(&mut this, "count", "I", count + length).await
156    }
157
158    async fn flush(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>) -> Result<()> {
159        tracing::debug!("java.io.BufferedOutputStream::flush({this:?})");
160
161        Self::flush_buffer(jvm, &mut this).await?;
162        let out: ClassInstanceRef<OutputStream> = jvm.get_field(&this, "out", "Ljava/io/OutputStream;").await?;
163        jvm.invoke_virtual(&out, "java/io/OutputStream", "flush", "()V", ()).await
164    }
165}