1 // Copyright (C) 2024 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use std::borrow::Borrow;
15 use std::fs::File;
16 use std::mem;
17 use std::ops::Deref;
18 use std::os::fd::{FromRawFd, IntoRawFd};
19 use std::pin::Pin;
20 
21 use cxx::UniquePtr;
22 
23 use super::error::ParcelSetError;
24 use super::wrapper::{
25     AsParcel, AsParcelMut, MessageOption, MessageParcel, NewMessageOption, NewMessageParcel,
26     Parcel, ReadBuffer, ReadInterfaceToken, ReadRemoteObject, ReadString16, ReadString16Vector,
27     WriteBuffer, WriteInterfaceToken, WriteRemoteObject, WriteString16, WriteString16Vector,
28 };
29 use super::{Deserialize, Serialize};
30 use crate::parcel::wrapper::IRemoteObjectWrapper;
31 use crate::remote::RemoteObj;
32 use crate::{IpcResult, IpcStatusCode};
33 const STRING_16_SIZE: usize = 12;
34 
35 pub(crate) enum ParcelMem {
36     Unique(UniquePtr<MessageParcel>),
37     Borrow(*mut MessageParcel),
38     Null,
39 }
40 
41 /// Ipc MsgParcel
42 pub struct MsgParcel {
43     pub(crate) inner: ParcelMem,
44 }
45 
46 unsafe impl Send for MsgParcel {}
47 unsafe impl Send for MsgOption {}
48 
49 impl MsgParcel {
50     /// Creates a new, empty MsgParcel.
51     ///
52     /// # Panics
53     /// Panics if allocate failed.
54     ///
55     /// # Examples
56     /// ```rust
57     /// use ipc::parcel::MsgParcel;
58     ///
59     /// let msg = MsgParcel::new();
60     /// ```
new() -> Self61     pub fn new() -> Self {
62         let ptr = NewMessageParcel();
63         assert!(!ptr.is_null(), "memory allocation of MessageParcel failed");
64         Self {
65             inner: ParcelMem::Unique(ptr),
66         }
67     }
68 
69     /// create MsgParcel from raw ptr
from_ptr(ptr: *mut MessageParcel) -> Self70     pub fn from_ptr(ptr: *mut MessageParcel) -> Self {
71         Self {
72             inner: ParcelMem::Borrow(ptr),
73         }
74     }
75 
76     /// into raw ptr
into_raw(self) -> *mut MessageParcel77     pub fn into_raw(self) -> *mut MessageParcel {
78         match self.inner {
79             ParcelMem::Unique(p) => p.into_raw(),
80             ParcelMem::Borrow(p) => p,
81             ParcelMem::Null => unreachable!(),
82         }
83     }
84 
85     /// Writes a [`Serialize`] value into this MsgParcel.
86     ///
87     /// [Serialize]: crate::parcel::Serialize
88     ///
89     /// # Example
90     /// ``` rust
91     /// use ipc::parcel::{MsgParcel, Serialize};
92     /// use ipc::IpcResult;
93     /// struct Foo {
94     ///     a: i32,
95     /// }
96     ///
97     /// impl Serialize for Foo {
98     ///     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
99     ///         parcel.write(&self.a)
100     ///     }
101     /// }
102     ///
103     /// let mut msg = MsgParcel::new();
104     /// msg.write(&Foo { a: 1 }).unwrap();
105     /// assert_eq!(1, msg.read::<i32>().unwrap());
106     /// ```
write<T: Serialize + ?Sized>(&mut self, value: &T) -> IpcResult<()>107     pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> IpcResult<()> {
108         value.serialize(self)
109     }
110 
111     /// Reads a [`Deserialize`] value out of this MsgParcel.
112     ///
113     /// [Deserialize]: crate::parcel::Deserialize
114     ///
115     /// # Example
116     /// ```rust
117     /// use ipc::parcel::{Deserialize, MsgParcel, Serialize};
118     /// use ipc::IpcResult;
119     ///
120     /// struct Foo {
121     ///     a: i32,
122     /// }
123     /// impl Serialize for Foo {
124     ///     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
125     ///         parcel.write(&self.a)
126     ///     }
127     /// }
128     /// impl Deserialize for Foo {
129     ///     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
130     ///         Ok(Foo { a: parcel.read()? })
131     ///     }
132     /// }
133     /// let mut msg = MsgParcel::new();
134     /// msg.write(&Foo { a: 1 }).unwrap();
135     /// let foo = msg.read::<Foo>().unwrap();
136     /// assert_eq!(foo.a, 1);
137     /// ```
read<T: Deserialize>(&mut self) -> IpcResult<T>138     pub fn read<T: Deserialize>(&mut self) -> IpcResult<T> {
139         T::deserialize(self)
140     }
141 
142     /// Writes a interface token into this MsgParcel.
143     ///
144     /// # Example
145     /// ```rust
146     /// use ipc::parcel::MsgParcel;
147     ///
148     /// let mut msg = MsgParcel::new();
149     /// msg.write_interface_token("OHOS.Download.RequestServiceInterface");
150     /// ```
write_interface_token(&mut self, name: &str) -> IpcResult<()>151     pub fn write_interface_token(&mut self, name: &str) -> IpcResult<()> {
152         self.write_process(name, WriteInterfaceToken)
153     }
154 
155     /// Reads a interface token from this MsgParcel.
156     ///
157     /// # Example
158     /// ```rust
159     /// use ipc::parcel::MsgParcel;
160     ///
161     /// let mut msg = MsgParcel::new();
162     /// msg.write_interface_token("OHOS.Download.RequestServiceInterface");
163     /// assert_eq!(
164     ///     "OHOS.Download.RequestServiceInterface",
165     ///     msg.read_interface_token().unwrap().as_str(),
166     /// );
167     /// ```
read_interface_token(&mut self) -> IpcResult<String>168     pub fn read_interface_token(&mut self) -> IpcResult<String> {
169         fn read_process(parcel: Pin<&mut MessageParcel>) -> IpcResult<String> {
170             Ok(ReadInterfaceToken(parcel))
171         }
172 
173         self.read_process(read_process)
174     }
175 
176     /// Writes a raw fd from a given file into this MsgParcel.
177     ///
178     /// ```no_run
179     /// use std::fs::File;
180     /// use std::io::{Read, Seek, Write};
181     ///
182     /// use ipc::parcel::MsgParcel;
183     ///
184     /// let mut msg = MsgParcel::new();
185     /// let mut file = std::fs::OpenOptions::new()
186     ///     .read(true)
187     ///     .write(true)
188     ///     .truncate(true)
189     ///     .open("foo")
190     ///     .unwrap();
191     /// file.write_all(b"hello world").unwrap();
192     /// msg.write_file(file).unwrap();
193     ///
194     /// let mut f = msg.read_file().unwrap();
195     /// let mut buf = String::new();
196     /// f.rewind().unwrap();
197     /// f.read_to_string(&mut buf).unwrap();
198     /// assert_eq!("hello world", buf);
199     /// ```
write_file(&mut self, file: File) -> IpcResult<()>200     pub fn write_file(&mut self, file: File) -> IpcResult<()> {
201         let fd = file.into_raw_fd();
202         match self.as_msg_parcel_mut().WriteFileDescriptor(fd) {
203             true => Ok(()),
204             false => Err(IpcStatusCode::Failed),
205         }
206     }
207 
208     /// Reads a file out of this MsgParcel, that created from the fd written
209     /// before.
210     ///
211     /// # Examples
212     /// ```no_run
213     /// use std::fs::File;
214     /// use std::io::{Read, Seek, Write};
215     ///
216     /// use ipc::parcel::MsgParcel;
217     /// let mut msg = MsgParcel::new();
218     /// let mut file = std::fs::OpenOptions::new()
219     ///     .read(true)
220     ///     .write(true)
221     ///     .truncate(true)
222     ///     .open("foo")
223     ///     .unwrap();
224     /// file.write_all(b"hello world").unwrap();
225     /// msg.write_file(file).unwrap();
226     ///
227     /// let mut f = msg.read_file().unwrap();
228     /// let mut buf = String::new();
229     /// f.rewind().unwrap();
230     /// f.read_to_string(&mut buf).unwrap();
231     /// assert_eq!("hello world", buf);
232     /// ```
read_file(&mut self) -> IpcResult<File>233     pub fn read_file(&mut self) -> IpcResult<File> {
234         let fd = self.as_msg_parcel_mut().ReadFileDescriptor();
235         unsafe { Ok(File::from_raw_fd(fd)) }
236     }
237 
238     /// Writes a data region (buffer) to this parcel
239     ///
240     /// # Example
241     /// ```rust
242     /// use crate::parcel::MsgParcel;
243     ///
244     /// let msg = MsgParcel::new();
245     /// let data = vec![];
246     /// msg.write_buffer(data.as_bytes);
247     /// ```
write_buffer(&mut self, buffer: &[u8]) -> IpcResult<()>248     pub fn write_buffer(&mut self, buffer: &[u8]) -> IpcResult<()> {
249         match WriteBuffer(self.as_msg_parcel_mut(), buffer) {
250             true => Ok(()),
251             false => Err(IpcStatusCode::Failed),
252         }
253     }
254 
255     /// Reads a block of data (buffer data) from this parcel
256     ///
257     /// # Example
258     /// ```rust
259     /// use crate::parcel::MsgParcel;
260     ///
261     /// let msg = MsgParcel::new();
262     /// let data = msg.read_buffer().unwrap();
263     /// ```
read_buffer(&mut self, len: usize) -> IpcResult<Vec<u8>>264     pub fn read_buffer(&mut self, len: usize) -> IpcResult<Vec<u8>> {
265         let pad_size = Self::get_pad_size(len);
266         let mut vec = Vec::with_capacity(len + pad_size);
267         match ReadBuffer(self.as_msg_parcel_mut(), len + pad_size, &mut vec) {
268             true => Ok({
269                 unsafe { vec.set_len(len) };
270                 vec
271             }),
272             false => Err(IpcStatusCode::Failed),
273         }
274     }
275 
write_string16(&mut self, s: &str) -> IpcResult<()>276     pub fn write_string16(&mut self, s: &str) -> IpcResult<()> {
277         match WriteString16(self.as_parcel_mut(), s) {
278             true => Ok(()),
279             false => Err(IpcStatusCode::Failed),
280         }
281     }
282 
read_string16(&mut self) -> IpcResult<String>283     pub fn read_string16(&mut self) -> IpcResult<String> {
284         Ok(ReadString16(self.as_parcel_mut()))
285     }
286 
write_string16_vec(&mut self, s: &[String]) -> IpcResult<()>287     pub fn write_string16_vec(&mut self, s: &[String]) -> IpcResult<()> {
288         match WriteString16Vector(self.as_parcel_mut(), s) {
289             true => Ok(()),
290             false => Err(IpcStatusCode::Failed),
291         }
292     }
293 
read_string16_vec(&mut self) -> IpcResult<Vec<String>>294     pub fn read_string16_vec(&mut self) -> IpcResult<Vec<String>> {
295         let mut v = vec![];
296         match ReadString16Vector(self.as_parcel_mut(), &mut v) {
297             true => Ok(v),
298             false => Err(IpcStatusCode::Failed),
299         }
300     }
301 
302     /// Writes a RemoteObj into this MsgParcel.
303     ///
304     /// # Example
305     /// ```rust
306     /// use ipc::parcel::MsgParcel;
307     /// use ipc::remote::{RemoteObj, RemoteStub};
308     ///
309     /// struct TestRemoteStub;
310     /// impl RemoteStub for TestRemoteStub {
311     ///     fn on_remote_request(&self, code: u32, data: &mut MsgParcel, reply: &mut MsgParcel) -> i32 {
312     ///         reply.write("nihao");
313     ///         println!("hello");
314     ///         0
315     ///     }
316     /// }
317     ///
318     /// let mut msg = MsgParcel::new();
319     /// msg.write_remote(RemoteObj::from_stub(TestRemoteStub).unwrap())
320     ///     .unwrap();
321     /// ```
write_remote(&mut self, remote: RemoteObj) -> IpcResult<()>322     pub fn write_remote(&mut self, remote: RemoteObj) -> IpcResult<()> {
323         self.write_process(remote.inner, WriteRemoteObject)
324     }
325 
326     /// Reads a RemoteObj from this MsgParcel.
327     ///
328     /// # Example
329     /// ```rust
330     /// use ipc::parcel::MsgParcel;
331     /// use ipc::remote::{RemoteObj, RemoteStub};
332     ///
333     /// struct TestRemoteStub;
334     /// impl RemoteStub for TestRemoteStub {
335     ///     fn on_remote_request(&self, code: u32, data: &mut MsgParcel, reply: &mut MsgParcel) -> i32 {
336     ///         reply.write("nihao");
337     ///         println!("hello");
338     ///         0
339     ///     }
340     /// }
341     ///
342     /// let mut msg = MsgParcel::new();
343     /// msg.write_remote(RemoteObj::from_stub(TestRemoteStub).unwrap())
344     ///     .unwrap();
345     /// let remote = msg.read_remote().unwrap();
346     /// ```
read_remote(&mut self) -> IpcResult<RemoteObj>347     pub fn read_remote(&mut self) -> IpcResult<RemoteObj> {
348         fn read_remote_process(
349             parcel: Pin<&mut MessageParcel>,
350         ) -> IpcResult<UniquePtr<IRemoteObjectWrapper>> {
351             let remote = ReadRemoteObject(parcel);
352             if remote.is_null() {
353                 Err(IpcStatusCode::Failed)
354             } else {
355                 Ok(remote)
356             }
357         }
358 
359         self.read_process(read_remote_process)
360             .map(|remote| unsafe { RemoteObj::new_unchecked(remote) })
361     }
362 
363     /// Returns the size that this MsgParcel has written in bytes.
364     ///
365     /// # Example
366     /// ```rust
367     /// use ipc::parcel::MsgParcel;
368     ///
369     /// let mut msg = MsgParcel::new();
370     /// msg.write(&1i32);
371     /// assert_eq!(msg.size(), 4);
372     /// ```
size(&self) -> usize373     pub fn size(&self) -> usize {
374         self.as_parcel().GetDataSize()
375     }
376 
377     /// Returns the remaining writable size in bytes before reallocating.
378     ///
379     /// # Example
380     /// ```rust
381     /// use ipc::parcel::MsgParcel;
382     ///
383     /// let mut msg = MsgParcel::new();
384     /// assert_eq!(0, msg.writable());
385     /// msg.write(&1i32);
386     /// assert_eq!(60, msg.writable());
387     /// ```
writable(&self) -> usize388     pub fn writable(&self) -> usize {
389         self.as_parcel().GetWritableBytes()
390     }
391 
392     /// Returns the remaining readable size in bytes.
393     ///
394     /// # Example
395     /// ```rust
396     /// use ipc::parcel::MsgParcel;
397     ///
398     /// let mut msg = MsgParcel::new();
399     /// msg.write(&1i32);
400     /// assert_eq!(4, msg.readable() as u32);
401     /// ```
readable(&self) -> usize402     pub fn readable(&self) -> usize {
403         self.as_parcel().GetReadableBytes()
404     }
405 
406     /// Returns the offset size in bytes.
407     ///
408     /// # Example
409     /// ```rust
410     /// use ipc::parcel::MsgParcel;
411     /// let msg = MsgParcel::new();
412     /// ```
offset(&self) -> usize413     pub fn offset(&self) -> usize {
414         self.as_parcel().GetOffsetsSize()
415     }
416 
417     /// Returns the total bytes the MsgParcel can hold without reallocating.
418     ///
419     /// # Example
420     /// ```rust
421     /// use ipc::parcel::MsgParcel;
422     ///
423     /// let mut msg = MsgParcel::new();
424     /// assert_eq!(0, msg.capacity());
425     /// msg.write(&1i32);
426     /// assert_eq!(64, msg.capacity());
427     /// ```
capacity(&self) -> usize428     pub fn capacity(&self) -> usize {
429         self.as_parcel().GetDataCapacity()
430     }
431 
432     /// Returns the maximum capacity MsgParcel can allocate.
433     ///
434     /// # Example
435     /// ```rust
436     /// use ipc::parcel::MsgParcel;
437     ///
438     /// let msg = MsgParcel::new();
439     /// assert_eq!(204800, msg.max_capacity());
440     /// ```
max_capacity(&self) -> usize441     pub fn max_capacity(&self) -> usize {
442         self.as_parcel().GetMaxCapacity()
443     }
444 
445     /// Returns the write_position of the MsgPacel in bytes.
446     ///
447     /// # Example
448     /// ```rust
449     /// use ipc::parcel::MsgParcel;
450     ///
451     /// let mut msg = MsgParcel::new();
452     /// assert_eq!(0, msg.write_position());
453     /// msg.write(&1i32).unwrap();
454     /// assert_eq!(4, msg.write_position());
455     /// ```
write_position(&mut self) -> usize456     pub fn write_position(&mut self) -> usize {
457         self.as_parcel_mut().GetWritePosition()
458     }
459 
460     /// Returns the read_position of the MsgParcel in bytes.
461     ///
462     /// # Example
463     /// ```rust
464     /// use ipc::parcel::MsgParcel;
465     ///
466     /// let mut msg = MsgParcel::new();
467     /// assert_eq!(0, msg.read_position());
468     /// msg.write(&1i32).unwrap();
469     /// assert_eq!(0, msg.read_position());
470     /// msg.read::<i32>().unwrap();
471     /// assert_eq!(4, msg.read_position());
472     /// ```
read_position(&mut self) -> usize473     pub fn read_position(&mut self) -> usize {
474         self.as_parcel_mut().GetReadPosition()
475     }
476 
477     /// Changes the size of the MsgParcel.
478     ///
479     /// # Errors
480     /// If new data size > capacity, set will fail.
481     ///
482     /// # Example
483     /// ```rust
484     /// use ipc::parcel::MsgParcel;
485     ///
486     /// let mut msg = MsgParcel::new();
487     /// msg.write(&1i32);
488     /// assert_eq!(4, msg.size());
489     /// msg.set_size(0);
490     /// assert_eq!(0, msg.size());
491     /// ```
set_size(&mut self, size: usize) -> Result<(), ParcelSetError>492     pub fn set_size(&mut self, size: usize) -> Result<(), ParcelSetError> {
493         if self.as_parcel_mut().SetDataSize(size) {
494             Ok(())
495         } else {
496             Err(ParcelSetError)
497         }
498     }
499 
500     /// Changes the capacity of the MsgParcel.
501     ///
502     /// # Errors
503     /// If data size > new capacity bytes, set will fail.
504     ///
505     /// # Example
506     /// ```rust
507     /// use ipc::parcel::MsgParcel;
508     ///
509     /// let msg = MsgParcel::new();
510     /// msg.set_capacity(64).unwrap();
511     /// assert_eq!(64, msg.capacity());
512     /// ```
set_capacity(&mut self, size: usize) -> Result<(), ParcelSetError>513     pub fn set_capacity(&mut self, size: usize) -> Result<(), ParcelSetError> {
514         if self.as_parcel_mut().SetDataCapacity(size) {
515             Ok(())
516         } else {
517             Err(ParcelSetError)
518         }
519     }
520 
521     /// Changes the capacity of the MsgParcel.
522     ///
523     /// # Errors
524     /// If new max capacity reach the limit, set will fail.
525     ///
526     /// # Example
527     /// ```rust
528     /// use ipc::parcel::MsgParcel;
529     ///
530     /// let mut msg = MsgParcel::new();
531     /// msg.set_max_capacity(64).unwrap();
532     /// ```
set_max_capacity(&mut self, size: usize) -> Result<(), ParcelSetError>533     pub fn set_max_capacity(&mut self, size: usize) -> Result<(), ParcelSetError> {
534         if self.as_parcel_mut().SetMaxCapacity(size) {
535             Ok(())
536         } else {
537             Err(ParcelSetError)
538         }
539     }
540 
541     /// Changes the read position of the MsgParcel.
542     ///
543     /// # Errors
544     /// If new position > data size, set will fail.
545     ///
546     /// # Example
547     /// ```rust
548     /// use ipc::parcel::MsgParcel;
549     ///
550     /// let mut msg = MsgParcel::new();
551     /// msg.write(&1i32).unwrap();
552     /// msg.write(&2i32).unwrap();
553     /// msg.set_read_position(4).unwrap();
554     /// assert_eq!(2, msg.read().unwrap());
555     /// ```
set_read_position(&mut self, size: usize) -> Result<(), ParcelSetError>556     pub fn set_read_position(&mut self, size: usize) -> Result<(), ParcelSetError> {
557         if self.as_parcel_mut().RewindRead(size) {
558             Ok(())
559         } else {
560             Err(ParcelSetError)
561         }
562     }
563 
564     /// Changes the write position of the MsgParcel.
565     ///
566     /// # Errors
567     /// if new position > data size, set will fail
568     ///
569     /// # Example
570     /// ```rust
571     /// use ipc::parcel::MsgParcel;
572     ///
573     /// let mut msg = MsgParcel::new();
574     /// msg.write(&1i32).unwrap();
575     /// msg.write(&2i32).unwrap();
576     /// msg.set_write_position(0);
577     /// msg.write(&2i32).unwrap();
578     /// assert_eq(2, msg.read().unwrap());
579     /// ```
set_write_position(&mut self, size: usize) -> Result<(), ParcelSetError>580     pub fn set_write_position(&mut self, size: usize) -> Result<(), ParcelSetError> {
581         if self.as_parcel_mut().RewindWrite(size) {
582             Ok(())
583         } else {
584             Err(ParcelSetError)
585         }
586     }
587 
588     /// Skip read data in bytes of the MsgParcel
589     ///
590     /// # Errors
591     /// if skip size > readable data the the read position will be the capacity.
592     ///
593     /// # Examples
594     /// ```rust
595     /// use ipc::parcel::MsgParcel;
596     ///
597     /// let mut msg = MsgParcel::new();
598     /// msg.write(&1i32).unwrap();
599     /// msg.write(&2i32).unwrap();
600     /// msg.skip_read(4);
601     /// assert_eq!(2, msg.read().unwrap());
602     /// ```
skip_read(&mut self, size: usize)603     pub fn skip_read(&mut self, size: usize) {
604         self.as_parcel_mut().SkipBytes(size)
605     }
606 
as_msg_parcel_mut(&mut self) -> Pin<&mut MessageParcel>607     fn as_msg_parcel_mut(&mut self) -> Pin<&mut MessageParcel> {
608         match &mut self.inner {
609             ParcelMem::Unique(p) => p.pin_mut(),
610             ParcelMem::Borrow(p) => unsafe { Pin::new_unchecked(&mut **p) },
611             _ => unreachable!(),
612         }
613     }
614 
as_parcel(&self) -> &Parcel615     fn as_parcel(&self) -> &Parcel {
616         match &self.inner {
617             ParcelMem::Unique(p) => unsafe {
618                 let parcel = AsParcel(p.as_ref().unwrap());
619                 &*parcel
620             },
621             ParcelMem::Borrow(p) => unsafe {
622                 let parcel = AsParcel(&**p);
623                 &*parcel
624             },
625             _ => unreachable!(),
626         }
627     }
628 
as_parcel_mut(&mut self) -> Pin<&mut Parcel>629     pub(crate) fn as_parcel_mut(&mut self) -> Pin<&mut Parcel> {
630         match &mut self.inner {
631             ParcelMem::Unique(p) => unsafe {
632                 let parcel = AsParcelMut(p.pin_mut());
633                 Pin::new_unchecked(&mut *parcel)
634             },
635             ParcelMem::Borrow(p) => unsafe {
636                 let parcel = AsParcelMut(Pin::new_unchecked(&mut **p));
637                 Pin::new_unchecked(&mut *parcel)
638             },
639             _ => unreachable!(),
640         }
641     }
642 
write_process<T>( &mut self, value: T, f: fn(parcel: Pin<&mut MessageParcel>, value: T) -> bool, ) -> IpcResult<()>643     pub(crate) fn write_process<T>(
644         &mut self,
645         value: T,
646         f: fn(parcel: Pin<&mut MessageParcel>, value: T) -> bool,
647     ) -> IpcResult<()> {
648         match mem::replace(&mut self.inner, ParcelMem::Null) {
649             ParcelMem::Unique(mut p) => {
650                 let res = f(p.pin_mut(), value);
651                 self.inner = ParcelMem::Unique(p);
652                 match res {
653                     true => Ok(()),
654                     false => Err(IpcStatusCode::Failed),
655                 }
656             }
657             ParcelMem::Borrow(p) => {
658                 let w = unsafe { Pin::new_unchecked(&mut *p) };
659                 let res = f(w, value);
660                 self.inner = ParcelMem::Borrow(p);
661                 match res {
662                     true => Ok(()),
663                     false => Err(IpcStatusCode::Failed),
664                 }
665             }
666             ParcelMem::Null => IpcResult::Err(IpcStatusCode::Failed),
667         }
668     }
669 
read_process<T>( &mut self, f: fn(parcel: Pin<&mut MessageParcel>) -> IpcResult<T>, ) -> IpcResult<T>670     pub(crate) fn read_process<T>(
671         &mut self,
672         f: fn(parcel: Pin<&mut MessageParcel>) -> IpcResult<T>,
673     ) -> IpcResult<T> {
674         match mem::replace(&mut self.inner, ParcelMem::Null) {
675             ParcelMem::Unique(mut p) => {
676                 let res = f(p.pin_mut());
677                 self.inner = ParcelMem::Unique(p);
678                 res
679             }
680             ParcelMem::Borrow(p) => {
681                 let w = unsafe { Pin::new_unchecked(&mut *p) };
682                 let res = f(w);
683                 self.inner = ParcelMem::Borrow(p);
684                 res
685             }
686             ParcelMem::Null => IpcResult::Err(IpcStatusCode::Failed),
687         }
688     }
689 
pin_mut(&mut self) -> Option<Pin<&mut MessageParcel>>690     pub fn pin_mut(&mut self) -> Option<Pin<&mut MessageParcel>> {
691         match &mut self.inner {
692             ParcelMem::Unique(p) => Some(p.pin_mut()),
693             _ => None,
694         }
695     }
696 
get_pad_size(size: usize) -> usize697     fn get_pad_size(size: usize) -> usize {
698         const SIZE_OFFSET: usize = 3;
699         ((size + SIZE_OFFSET) & (!SIZE_OFFSET)) - size
700     }
701 }
702 
703 /// Ipc MsgOption used when send request, including some settings.
704 pub struct MsgOption {
705     pub(crate) inner: UniquePtr<MessageOption>,
706 }
707 
708 impl MsgOption {
709     const TF_SYNC: i32 = 0x00;
710     const TF_ASYNC: i32 = 0x01;
711 
712     /// Creates a new, empty MsgOption.
713 
714     /// # Panics
715     /// Panics if allocate failed.
716     ///
717     /// # Examples
718     /// ```rust
719     /// use ipc::parcel::MsgOption;
720     ///
721     /// let msg = MsgOption::new();
722     /// ```
new() -> Self723     pub fn new() -> Self {
724         let ptr = NewMessageOption();
725         assert!(!ptr.is_null(), "memory allocation of MessageOption failed");
726 
727         Self {
728             inner: NewMessageOption(),
729         }
730     }
731 
732     /// Set send to be async.
set_async(&mut self)733     pub fn set_async(&mut self) {
734         self.inner.pin_mut().SetFlags(Self::TF_ASYNC);
735     }
736 
737     /// Sets send to be sync.
set_sync(&mut self)738     pub fn set_sync(&mut self) {
739         self.inner.pin_mut().SetFlags(Self::TF_SYNC);
740     }
741 
742     /// Return true if has set to async.
is_async(&self) -> bool743     pub fn is_async(&self) -> bool {
744         self.inner.GetFlags() == Self::TF_ASYNC
745     }
746 }
747 
748 impl Default for MsgParcel {
default() -> Self749     fn default() -> Self {
750         Self::new()
751     }
752 }
753 
754 impl Default for MsgOption {
default() -> Self755     fn default() -> Self {
756         Self::new()
757     }
758 }
759 
760 #[cfg(test)]
761 mod test {
762     use std::mem;
763 
764     use super::MsgParcel;
765 
766     /// UT test cases for `GetDataSize`
767     ///
768     /// # Brief
769     /// 1. Creates a MsgParcel
770     /// 2. Writes a value to the MsgParcel and then check its data size.
771     #[test]
parcel_size()772     fn parcel_size() {
773         let mut msg = MsgParcel::new();
774         let mut size = 0;
775 
776         msg.write(&1i8).unwrap();
777         size += mem::size_of::<i32>();
778         assert_eq!(size, msg.size());
779 
780         msg.write(&1i16).unwrap();
781         size += mem::size_of::<i32>();
782         assert_eq!(size, msg.size());
783 
784         msg.write(&1i32).unwrap();
785         size += mem::size_of::<i32>();
786         assert_eq!(size, msg.size());
787 
788         msg.write(&1i64).unwrap();
789         size += mem::size_of::<i64>();
790         assert_eq!(size, msg.size());
791 
792         msg.write(&1u8).unwrap();
793         size += mem::size_of::<u32>();
794         assert_eq!(size, msg.size());
795 
796         msg.write(&1u16).unwrap();
797         size += mem::size_of::<u32>();
798         assert_eq!(size, msg.size());
799 
800         msg.write(&1u32).unwrap();
801         size += mem::size_of::<u32>();
802         assert_eq!(size, msg.size());
803 
804         msg.write(&1u64).unwrap();
805         size += mem::size_of::<u64>();
806         assert_eq!(size, msg.size());
807 
808         msg.write(&true).unwrap();
809         size += mem::size_of::<i32>();
810         assert_eq!(size, msg.size());
811     }
812 
813     /// UT test cases for read_to_end
814     ///
815     /// # Brief
816     /// 1. Creates a new MsgParcel.
817     /// 3. Write a bool and read it out.
818     /// 2. write a vector into this MsgParcel, and read_to_end check the
819     ///    correctness.
820     #[test]
read_to_end()821     fn read_to_end() {
822         let mut msg = MsgParcel::new();
823         msg.write(&true).unwrap();
824         msg.read::<bool>().unwrap();
825 
826         msg.write(&vec![1, 2, 3]).unwrap();
827         assert_eq!(
828             vec![3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0],
829             msg.read_buffer(msg.readable()).unwrap()
830         );
831     }
832 }
833