ohos_web_binding/protocol/
http_body_stream.rs1use std::{ffi::c_void, mem::ManuallyDrop, ptr::NonNull};
2
3use ohos_web_sys::{
4 ArkWeb_HttpBodyStream, OH_ArkWebHttpBodyStream_GetSize, OH_ArkWebHttpBodyStream_GetUserData,
5 OH_ArkWebHttpBodyStream_Init, OH_ArkWebHttpBodyStream_IsChunked, OH_ArkWebHttpBodyStream_IsEof,
6 OH_ArkWebHttpBodyStream_IsInMemory, OH_ArkWebHttpBodyStream_Read,
7 OH_ArkWebHttpBodyStream_SetReadCallback, OH_ArkWebHttpBodyStream_SetUserData,
8};
9
10pub struct HttpBodyStream {
11 raw: NonNull<ArkWeb_HttpBodyStream>,
12}
13
14struct ReadCallbackContext {
15 callback: Box<dyn FnMut(Vec<u8>)>,
16}
17
18impl HttpBodyStream {
19 pub fn new(raw: *mut ArkWeb_HttpBodyStream) -> Self {
20 unsafe {
21 OH_ArkWebHttpBodyStream_Init(raw, None);
22 Self {
23 raw: NonNull::new_unchecked(raw),
24 }
25 }
26 }
27
28 pub fn is_chunked(&self) -> bool {
29 unsafe { OH_ArkWebHttpBodyStream_IsChunked(self.raw.as_ptr()) }
30 }
31
32 pub fn is_eof(&self) -> bool {
33 unsafe { OH_ArkWebHttpBodyStream_IsEof(self.raw.as_ptr()) }
34 }
35
36 pub fn is_in_memory(&self) -> bool {
37 unsafe { OH_ArkWebHttpBodyStream_IsInMemory(self.raw.as_ptr()) }
38 }
39
40 pub fn read<F>(&self, size: usize, mut callback: F)
41 where
42 F: FnMut(Vec<u8>),
43 {
44 let mut buf: Vec<u8> = Vec::with_capacity(size);
45 let buf_ptr = buf.as_mut_ptr();
46
47 let static_callback = unsafe {
48 std::mem::transmute::<Box<dyn FnMut(Vec<u8>)>, Box<dyn FnMut(Vec<u8>) + 'static>>(
49 Box::new(move |buf| {
50 callback(buf);
51 }),
52 )
53 };
54
55 let ctx = ReadCallbackContext {
56 callback: static_callback,
57 };
58 let ctx_ptr = Box::into_raw(Box::new(ctx)) as *mut c_void;
59
60 unsafe {
61 OH_ArkWebHttpBodyStream_SetUserData(self.raw.as_ptr(), ctx_ptr);
62 OH_ArkWebHttpBodyStream_SetReadCallback(self.raw.as_ptr(), Some(read_callback));
63 OH_ArkWebHttpBodyStream_Read(self.raw.as_ptr(), buf_ptr, size as _);
64 };
65 }
66
67 pub fn size(&self) -> u64 {
68 unsafe { OH_ArkWebHttpBodyStream_GetSize(self.raw.as_ptr()) }
69 }
70}
71
72extern "C" fn read_callback(
73 http_body_stream: *const ArkWeb_HttpBodyStream,
74 buffer: *mut u8,
75 bytes_read: i32,
76) {
77 unsafe {
78 let user_data_ptr = OH_ArkWebHttpBodyStream_GetUserData(http_body_stream);
79 let mut ctx = ManuallyDrop::new(Box::from_raw(user_data_ptr as *mut ReadCallbackContext));
80 let data = std::slice::from_raw_parts(buffer, bytes_read as usize).to_vec();
81 (ctx.callback)(data);
82 }
83}