Skip to main content

rustjava_runtime/classes/java/io/
byte_array_output_stream.rs

1use alloc::{vec, vec::Vec};
2
3use jvm::{Array, ClassInstanceRef, Jvm, Result};
4use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
5use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
6
7use crate::{
8    RuntimeClassProto, RuntimeContext,
9    classes::java::{io::OutputStream, lang::String},
10};
11
12// class java.io.ByteArrayOutputStream
13pub struct ByteArrayOutputStream;
14
15impl ByteArrayOutputStream {
16    pub fn as_proto() -> RuntimeClassProto {
17        RuntimeClassProto {
18            name: "java/io/ByteArrayOutputStream",
19            parent_class: Some("java/io/OutputStream"),
20            interfaces: vec![],
21            methods: vec![
22                JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
23                JavaMethodProto::new("<init>", "(I)V", Self::init_with_size, MethodAccessFlags::PUBLIC),
24                JavaMethodProto::new("write", "(I)V", Self::write, MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED),
25                JavaMethodProto::new(
26                    "write",
27                    "([BII)V",
28                    Self::write_bytes,
29                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
30                ),
31                JavaMethodProto::new(
32                    "writeTo",
33                    "(Ljava/io/OutputStream;)V",
34                    Self::write_to,
35                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
36                ),
37                JavaMethodProto::new(
38                    "toByteArray",
39                    "()[B",
40                    Self::to_byte_array,
41                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
42                ),
43                JavaMethodProto::new(
44                    "toString",
45                    "()Ljava/lang/String;",
46                    Self::to_string,
47                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
48                ),
49                JavaMethodProto::new(
50                    "toString",
51                    "(Ljava/lang/String;)Ljava/lang/String;",
52                    Self::to_string_with_encoding,
53                    MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED,
54                ),
55                JavaMethodProto::new("size", "()I", Self::size, MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED),
56                JavaMethodProto::new("reset", "()V", Self::reset, MethodAccessFlags::PUBLIC | MethodAccessFlags::SYNCHRONIZED),
57                JavaMethodProto::new("close", "()V", Self::close, MethodAccessFlags::PUBLIC),
58            ],
59            fields: vec![
60                JavaFieldProto::new("buf", "[B", FieldAccessFlags::PROTECTED),
61                JavaFieldProto::new("count", "I", FieldAccessFlags::PROTECTED),
62            ],
63            access_flags: ClassAccessFlags::PUBLIC,
64        }
65    }
66
67    async fn init(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
68        tracing::debug!("java.io.ByteArrayOutputStream::<init>({this:?})");
69
70        let _: () = jvm
71            .invoke_special(&this, "java/io/ByteArrayOutputStream", "<init>", "(I)V", (32,))
72            .await?;
73
74        Ok(())
75    }
76
77    async fn init_with_size(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, size: i32) -> Result<()> {
78        tracing::debug!("java.io.ByteArrayOutputStream::<init>({this:?}, {size:?})");
79
80        if size < 0 {
81            return Err(jvm.exception("java/lang/IllegalArgumentException", "Negative initial size").await);
82        }
83
84        let _: () = jvm.invoke_special(&this, "java/io/OutputStream", "<init>", "()V", ()).await?;
85
86        let array = jvm.instantiate_array("B", size as usize).await?;
87
88        jvm.put_field(&mut this, "buf", "[B", array).await?;
89        jvm.put_field(&mut this, "count", "I", 0).await?;
90
91        Ok(())
92    }
93
94    async fn write_bytes(
95        jvm: &Jvm,
96        _: &mut RuntimeContext,
97        mut this: ClassInstanceRef<Self>,
98        bytes: ClassInstanceRef<Array<i8>>,
99        off: i32,
100        len: i32,
101    ) -> Result<()> {
102        tracing::debug!("java.io.ByteArrayOutputStream::write({this:?}, {bytes:?}, {off}, {len})");
103
104        if bytes.is_null() {
105            return Err(jvm.exception("java/lang/NullPointerException", "buffer is null").await);
106        }
107        let length = jvm.array_length(&bytes).await? as i32;
108        if off < 0 || len < 0 || off > length - len {
109            return Err(jvm.exception("java/lang/IndexOutOfBoundsException", "Invalid offset or length").await);
110        }
111
112        let count: i32 = jvm.get_field(&this, "count", "I").await?;
113        Self::ensure_capacity(jvm, &mut this, (count + len) as usize).await?;
114        let mut buf = jvm.get_field(&this, "buf", "[B").await?;
115        let values: Vec<i8> = jvm.load_array(&bytes, off as usize, len as usize).await?;
116        jvm.store_array(&mut buf, count as usize, values).await?;
117        jvm.put_field(&mut this, "count", "I", count + len).await
118    }
119
120    async fn write(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, b: i32) -> Result<()> {
121        tracing::debug!("java.io.ByteArrayOutputStream::write({this:?}, {b:?})");
122
123        let count: i32 = jvm.get_field(&this, "count", "I").await?;
124        Self::ensure_capacity(jvm, &mut this, (count + 1) as _).await?;
125
126        let mut buf = jvm.get_field(&this, "buf", "[B").await?;
127        jvm.store_array(&mut buf, count as _, vec![b as i8]).await?;
128
129        jvm.put_field(&mut this, "count", "I", count + 1).await?;
130
131        Ok(())
132    }
133
134    async fn write_to(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, out: ClassInstanceRef<OutputStream>) -> Result<()> {
135        tracing::debug!("java.io.ByteArrayOutputStream::writeTo({this:?}, {out:?})");
136
137        if out.is_null() {
138            return Err(jvm.exception("java/lang/NullPointerException", "output is null").await);
139        }
140
141        let buf: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
142        let count: i32 = jvm.get_field(&this, "count", "I").await?;
143        jvm.invoke_virtual(&out, "java/io/OutputStream", "write", "([BII)V", (buf, 0, count))
144            .await
145    }
146
147    async fn to_byte_array(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<Array<i8>>> {
148        tracing::debug!("java.io.ByteArrayOutputStream::to_byte_array({this:?})");
149
150        let buf: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
151        let count: i32 = jvm.get_field(&this, "count", "I").await?;
152
153        let dest = jvm.instantiate_array("B", count as _).await?;
154        let _: () = jvm
155            .invoke_static(
156                "java/lang/System",
157                "arraycopy",
158                "(Ljava/lang/Object;ILjava/lang/Object;II)V",
159                (buf.clone(), 0, dest.clone(), 0, count),
160            )
161            .await?;
162
163        Ok(dest.into())
164    }
165
166    async fn size(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<i32> {
167        tracing::debug!("java.io.ByteArrayOutputStream::size({this:?})");
168
169        let count: i32 = jvm.get_field(&this, "count", "I").await?;
170
171        Ok(count)
172    }
173
174    async fn to_string(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<String>> {
175        tracing::debug!("java.io.ByteArrayOutputStream::toString({this:?})");
176        let buf: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
177        let count: i32 = jvm.get_field(&this, "count", "I").await?;
178        let bytes = jvm.instantiate_array("B", count as usize).await?;
179        let _: () = jvm
180            .invoke_static(
181                "java/lang/System",
182                "arraycopy",
183                "(Ljava/lang/Object;ILjava/lang/Object;II)V",
184                (buf, 0, bytes.clone(), 0, count),
185            )
186            .await?;
187        Ok(jvm.new_class("java/lang/String", "([B)V", (bytes,)).await?.into())
188    }
189
190    async fn to_string_with_encoding(
191        jvm: &Jvm,
192        _: &mut RuntimeContext,
193        this: ClassInstanceRef<Self>,
194        encoding: ClassInstanceRef<String>,
195    ) -> Result<ClassInstanceRef<String>> {
196        tracing::debug!("java.io.ByteArrayOutputStream::toString({this:?}, {encoding:?})");
197
198        if encoding.is_null() {
199            return Err(jvm.exception("java/lang/NullPointerException", "encoding is null").await);
200        }
201
202        let buf: ClassInstanceRef<Array<i8>> = jvm.get_field(&this, "buf", "[B").await?;
203        let count: i32 = jvm.get_field(&this, "count", "I").await?;
204        Ok(jvm
205            .new_class("java/lang/String", "([BIILjava/lang/String;)V", (buf, 0, count, encoding))
206            .await?
207            .into())
208    }
209
210    async fn reset(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>) -> Result<()> {
211        tracing::debug!("java.io.ByteArrayOutputStream::reset({this:?})");
212
213        jvm.put_field(&mut this, "count", "I", 0).await?;
214
215        Ok(())
216    }
217
218    async fn close(_jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
219        tracing::debug!("java.io.ByteArrayOutputStream::close({this:?})");
220
221        Ok(())
222    }
223
224    async fn ensure_capacity(jvm: &Jvm, this: &mut ClassInstanceRef<Self>, capacity: usize) -> Result<()> {
225        let old_buf = jvm.get_field(this, "buf", "[B").await?;
226        let current_capacity = jvm.array_length(&old_buf).await?;
227
228        if current_capacity < capacity {
229            let new_capacity = current_capacity.saturating_mul(2).max(capacity);
230            let new_buf = jvm.instantiate_array("B", new_capacity).await?;
231            let count: i32 = jvm.get_field(this, "count", "I").await?;
232
233            let _: () = jvm
234                .invoke_static(
235                    "java/lang/System",
236                    "arraycopy",
237                    "(Ljava/lang/Object;ILjava/lang/Object;II)V",
238                    (old_buf.clone(), 0, new_buf.clone(), 0, count),
239                )
240                .await?;
241
242            jvm.put_field(this, "buf", "[B", new_buf.clone()).await?;
243        }
244
245        Ok(())
246    }
247}