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, RawFd}; 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 /// ``` 233 #[deprecated(note = "This method is unsafe; use `read_raw_fd()` instead")] read_file(&mut self) -> IpcResult<File>234 pub fn read_file(&mut self) -> IpcResult<File> { 235 let fd = self.as_msg_parcel_mut().ReadFileDescriptor(); 236 unsafe { Ok(File::from_raw_fd(fd)) } 237 } 238 239 /// Reads a raw file descriptor (fd) previously written to the `MsgParcel`. 240 /// 241 /// # Safety 242 /// This function is `unsafe` because it returns a raw file descriptor (`RawFd`). 243 /// The caller must ensure: 244 /// - The returned `RawFd` is valid (i.e., ≥0) and owned by the caller. 245 /// - The descriptor is properly closed (e.g., via `File::from_raw_fd` + `drop`) 246 /// to avoid resource leaks. 247 /// 248 /// # Examples 249 /// ```no_run 250 /// use std::fs::File; 251 /// use std::io::{Read, Seek, Write}; 252 /// use std::os::fd::FromRawFd; 253 /// 254 /// use ipc::parcel::MsgParcel; 255 /// let mut msg = MsgParcel::new(); 256 /// let mut file = std::fs::OpenOptions::new() 257 /// .read(true) 258 /// .write(true) 259 /// .truncate(true) 260 /// .open("foo") 261 /// .unwrap(); 262 /// file.write_all(b"hello world").unwrap(); 263 /// msg.write_file(file).unwrap(); 264 /// 265 /// let raw_fd = unsafe { msg.read_raw_fd() }; 266 /// assert!(raw_fd >= 0, "Invalid fd: {}", raw_fd); 267 /// let mut f = unsafe { File::from_raw_fd(raw_fd) }; 268 /// let mut buf = String::new(); 269 /// f.rewind().unwrap(); 270 /// f.read_to_string(&mut buf).unwrap(); 271 /// assert_eq!("hello world", buf); 272 /// drop(f); 273 /// ``` read_raw_fd(&mut self) -> RawFd274 pub unsafe fn read_raw_fd(&mut self) -> RawFd { 275 self.as_msg_parcel_mut().ReadFileDescriptor() 276 } 277 278 /// Writes a data region (buffer) to this parcel 279 /// 280 /// # Example 281 /// ```rust 282 /// use crate::parcel::MsgParcel; 283 /// 284 /// let msg = MsgParcel::new(); 285 /// let data = vec![]; 286 /// msg.write_buffer(data.as_bytes); 287 /// ``` write_buffer(&mut self, buffer: &[u8]) -> IpcResult<()>288 pub fn write_buffer(&mut self, buffer: &[u8]) -> IpcResult<()> { 289 match WriteBuffer(self.as_msg_parcel_mut(), buffer) { 290 true => Ok(()), 291 false => Err(IpcStatusCode::Failed), 292 } 293 } 294 295 /// Reads a block of data (buffer data) from this parcel 296 /// 297 /// # Example 298 /// ```rust 299 /// use crate::parcel::MsgParcel; 300 /// 301 /// let msg = MsgParcel::new(); 302 /// let data = msg.read_buffer().unwrap(); 303 /// ``` read_buffer(&mut self, len: usize) -> IpcResult<Vec<u8>>304 pub fn read_buffer(&mut self, len: usize) -> IpcResult<Vec<u8>> { 305 let pad_size = Self::get_pad_size(len); 306 let mut vec = Vec::with_capacity(len + pad_size); 307 match ReadBuffer(self.as_msg_parcel_mut(), len + pad_size, &mut vec) { 308 true => Ok({ 309 unsafe { vec.set_len(len) }; 310 vec 311 }), 312 false => Err(IpcStatusCode::Failed), 313 } 314 } 315 write_string16(&mut self, s: &str) -> IpcResult<()>316 pub fn write_string16(&mut self, s: &str) -> IpcResult<()> { 317 match WriteString16(self.as_parcel_mut(), s) { 318 true => Ok(()), 319 false => Err(IpcStatusCode::Failed), 320 } 321 } 322 read_string16(&mut self) -> IpcResult<String>323 pub fn read_string16(&mut self) -> IpcResult<String> { 324 Ok(ReadString16(self.as_parcel_mut())) 325 } 326 write_string16_vec(&mut self, s: &[String]) -> IpcResult<()>327 pub fn write_string16_vec(&mut self, s: &[String]) -> IpcResult<()> { 328 match WriteString16Vector(self.as_parcel_mut(), s) { 329 true => Ok(()), 330 false => Err(IpcStatusCode::Failed), 331 } 332 } 333 read_string16_vec(&mut self) -> IpcResult<Vec<String>>334 pub fn read_string16_vec(&mut self) -> IpcResult<Vec<String>> { 335 let mut v = vec![]; 336 match ReadString16Vector(self.as_parcel_mut(), &mut v) { 337 true => Ok(v), 338 false => Err(IpcStatusCode::Failed), 339 } 340 } 341 342 /// Writes a RemoteObj into this MsgParcel. 343 /// 344 /// # Example 345 /// ```rust 346 /// use ipc::parcel::MsgParcel; 347 /// use ipc::remote::{RemoteObj, RemoteStub}; 348 /// 349 /// struct TestRemoteStub; 350 /// impl RemoteStub for TestRemoteStub { 351 /// fn on_remote_request(&self, code: u32, data: &mut MsgParcel, reply: &mut MsgParcel) -> i32 { 352 /// reply.write("nihao"); 353 /// println!("hello"); 354 /// 0 355 /// } 356 /// } 357 /// 358 /// let mut msg = MsgParcel::new(); 359 /// msg.write_remote(RemoteObj::from_stub(TestRemoteStub).unwrap()) 360 /// .unwrap(); 361 /// ``` write_remote(&mut self, remote: RemoteObj) -> IpcResult<()>362 pub fn write_remote(&mut self, remote: RemoteObj) -> IpcResult<()> { 363 self.write_process(remote.inner, WriteRemoteObject) 364 } 365 366 /// Reads a RemoteObj from this MsgParcel. 367 /// 368 /// # Example 369 /// ```rust 370 /// use ipc::parcel::MsgParcel; 371 /// use ipc::remote::{RemoteObj, RemoteStub}; 372 /// 373 /// struct TestRemoteStub; 374 /// impl RemoteStub for TestRemoteStub { 375 /// fn on_remote_request(&self, code: u32, data: &mut MsgParcel, reply: &mut MsgParcel) -> i32 { 376 /// reply.write("nihao"); 377 /// println!("hello"); 378 /// 0 379 /// } 380 /// } 381 /// 382 /// let mut msg = MsgParcel::new(); 383 /// msg.write_remote(RemoteObj::from_stub(TestRemoteStub).unwrap()) 384 /// .unwrap(); 385 /// let remote = msg.read_remote().unwrap(); 386 /// ``` read_remote(&mut self) -> IpcResult<RemoteObj>387 pub fn read_remote(&mut self) -> IpcResult<RemoteObj> { 388 fn read_remote_process( 389 parcel: Pin<&mut MessageParcel>, 390 ) -> IpcResult<UniquePtr<IRemoteObjectWrapper>> { 391 let remote = ReadRemoteObject(parcel); 392 if remote.is_null() { 393 Err(IpcStatusCode::Failed) 394 } else { 395 Ok(remote) 396 } 397 } 398 399 self.read_process(read_remote_process) 400 .map(|remote| unsafe { RemoteObj::new_unchecked(remote) }) 401 } 402 403 /// Returns the size that this MsgParcel has written in bytes. 404 /// 405 /// # Example 406 /// ```rust 407 /// use ipc::parcel::MsgParcel; 408 /// 409 /// let mut msg = MsgParcel::new(); 410 /// msg.write(&1i32); 411 /// assert_eq!(msg.size(), 4); 412 /// ``` size(&self) -> usize413 pub fn size(&self) -> usize { 414 self.as_parcel().GetDataSize() 415 } 416 417 /// Returns the remaining writable size in bytes before reallocating. 418 /// 419 /// # Example 420 /// ```rust 421 /// use ipc::parcel::MsgParcel; 422 /// 423 /// let mut msg = MsgParcel::new(); 424 /// assert_eq!(0, msg.writable()); 425 /// msg.write(&1i32); 426 /// assert_eq!(60, msg.writable()); 427 /// ``` writable(&self) -> usize428 pub fn writable(&self) -> usize { 429 self.as_parcel().GetWritableBytes() 430 } 431 432 /// Returns the remaining readable size in bytes. 433 /// 434 /// # Example 435 /// ```rust 436 /// use ipc::parcel::MsgParcel; 437 /// 438 /// let mut msg = MsgParcel::new(); 439 /// msg.write(&1i32); 440 /// assert_eq!(4, msg.readable() as u32); 441 /// ``` readable(&self) -> usize442 pub fn readable(&self) -> usize { 443 self.as_parcel().GetReadableBytes() 444 } 445 446 /// Returns the offset size in bytes. 447 /// 448 /// # Example 449 /// ```rust 450 /// use ipc::parcel::MsgParcel; 451 /// let msg = MsgParcel::new(); 452 /// ``` offset(&self) -> usize453 pub fn offset(&self) -> usize { 454 self.as_parcel().GetOffsetsSize() 455 } 456 457 /// Returns the total bytes the MsgParcel can hold without reallocating. 458 /// 459 /// # Example 460 /// ```rust 461 /// use ipc::parcel::MsgParcel; 462 /// 463 /// let mut msg = MsgParcel::new(); 464 /// assert_eq!(0, msg.capacity()); 465 /// msg.write(&1i32); 466 /// assert_eq!(64, msg.capacity()); 467 /// ``` capacity(&self) -> usize468 pub fn capacity(&self) -> usize { 469 self.as_parcel().GetDataCapacity() 470 } 471 472 /// Returns the maximum capacity MsgParcel can allocate. 473 /// 474 /// # Example 475 /// ```rust 476 /// use ipc::parcel::MsgParcel; 477 /// 478 /// let msg = MsgParcel::new(); 479 /// assert_eq!(204800, msg.max_capacity()); 480 /// ``` max_capacity(&self) -> usize481 pub fn max_capacity(&self) -> usize { 482 self.as_parcel().GetMaxCapacity() 483 } 484 485 /// Returns the write_position of the MsgPacel in bytes. 486 /// 487 /// # Example 488 /// ```rust 489 /// use ipc::parcel::MsgParcel; 490 /// 491 /// let mut msg = MsgParcel::new(); 492 /// assert_eq!(0, msg.write_position()); 493 /// msg.write(&1i32).unwrap(); 494 /// assert_eq!(4, msg.write_position()); 495 /// ``` write_position(&mut self) -> usize496 pub fn write_position(&mut self) -> usize { 497 self.as_parcel_mut().GetWritePosition() 498 } 499 500 /// Returns the read_position of the MsgParcel in bytes. 501 /// 502 /// # Example 503 /// ```rust 504 /// use ipc::parcel::MsgParcel; 505 /// 506 /// let mut msg = MsgParcel::new(); 507 /// assert_eq!(0, msg.read_position()); 508 /// msg.write(&1i32).unwrap(); 509 /// assert_eq!(0, msg.read_position()); 510 /// msg.read::<i32>().unwrap(); 511 /// assert_eq!(4, msg.read_position()); 512 /// ``` read_position(&mut self) -> usize513 pub fn read_position(&mut self) -> usize { 514 self.as_parcel_mut().GetReadPosition() 515 } 516 517 /// Changes the size of the MsgParcel. 518 /// 519 /// # Errors 520 /// If new data size > capacity, set will fail. 521 /// 522 /// # Example 523 /// ```rust 524 /// use ipc::parcel::MsgParcel; 525 /// 526 /// let mut msg = MsgParcel::new(); 527 /// msg.write(&1i32); 528 /// assert_eq!(4, msg.size()); 529 /// msg.set_size(0); 530 /// assert_eq!(0, msg.size()); 531 /// ``` set_size(&mut self, size: usize) -> Result<(), ParcelSetError>532 pub fn set_size(&mut self, size: usize) -> Result<(), ParcelSetError> { 533 if self.as_parcel_mut().SetDataSize(size) { 534 Ok(()) 535 } else { 536 Err(ParcelSetError) 537 } 538 } 539 540 /// Changes the capacity of the MsgParcel. 541 /// 542 /// # Errors 543 /// If data size > new capacity bytes, set will fail. 544 /// 545 /// # Example 546 /// ```rust 547 /// use ipc::parcel::MsgParcel; 548 /// 549 /// let msg = MsgParcel::new(); 550 /// msg.set_capacity(64).unwrap(); 551 /// assert_eq!(64, msg.capacity()); 552 /// ``` set_capacity(&mut self, size: usize) -> Result<(), ParcelSetError>553 pub fn set_capacity(&mut self, size: usize) -> Result<(), ParcelSetError> { 554 if self.as_parcel_mut().SetDataCapacity(size) { 555 Ok(()) 556 } else { 557 Err(ParcelSetError) 558 } 559 } 560 561 /// Changes the capacity of the MsgParcel. 562 /// 563 /// # Errors 564 /// If new max capacity reach the limit, set will fail. 565 /// 566 /// # Example 567 /// ```rust 568 /// use ipc::parcel::MsgParcel; 569 /// 570 /// let mut msg = MsgParcel::new(); 571 /// msg.set_max_capacity(64).unwrap(); 572 /// ``` set_max_capacity(&mut self, size: usize) -> Result<(), ParcelSetError>573 pub fn set_max_capacity(&mut self, size: usize) -> Result<(), ParcelSetError> { 574 if self.as_parcel_mut().SetMaxCapacity(size) { 575 Ok(()) 576 } else { 577 Err(ParcelSetError) 578 } 579 } 580 581 /// Changes the read position of the MsgParcel. 582 /// 583 /// # Errors 584 /// If new position > data size, set will fail. 585 /// 586 /// # Example 587 /// ```rust 588 /// use ipc::parcel::MsgParcel; 589 /// 590 /// let mut msg = MsgParcel::new(); 591 /// msg.write(&1i32).unwrap(); 592 /// msg.write(&2i32).unwrap(); 593 /// msg.set_read_position(4).unwrap(); 594 /// assert_eq!(2, msg.read().unwrap()); 595 /// ``` set_read_position(&mut self, size: usize) -> Result<(), ParcelSetError>596 pub fn set_read_position(&mut self, size: usize) -> Result<(), ParcelSetError> { 597 if self.as_parcel_mut().RewindRead(size) { 598 Ok(()) 599 } else { 600 Err(ParcelSetError) 601 } 602 } 603 604 /// Changes the write position of the MsgParcel. 605 /// 606 /// # Errors 607 /// if new position > data size, set will fail 608 /// 609 /// # Example 610 /// ```rust 611 /// use ipc::parcel::MsgParcel; 612 /// 613 /// let mut msg = MsgParcel::new(); 614 /// msg.write(&1i32).unwrap(); 615 /// msg.write(&2i32).unwrap(); 616 /// msg.set_write_position(0); 617 /// msg.write(&2i32).unwrap(); 618 /// assert_eq(2, msg.read().unwrap()); 619 /// ``` set_write_position(&mut self, size: usize) -> Result<(), ParcelSetError>620 pub fn set_write_position(&mut self, size: usize) -> Result<(), ParcelSetError> { 621 if self.as_parcel_mut().RewindWrite(size) { 622 Ok(()) 623 } else { 624 Err(ParcelSetError) 625 } 626 } 627 628 /// Skip read data in bytes of the MsgParcel 629 /// 630 /// # Errors 631 /// if skip size > readable data the the read position will be the capacity. 632 /// 633 /// # Examples 634 /// ```rust 635 /// use ipc::parcel::MsgParcel; 636 /// 637 /// let mut msg = MsgParcel::new(); 638 /// msg.write(&1i32).unwrap(); 639 /// msg.write(&2i32).unwrap(); 640 /// msg.skip_read(4); 641 /// assert_eq!(2, msg.read().unwrap()); 642 /// ``` skip_read(&mut self, size: usize)643 pub fn skip_read(&mut self, size: usize) { 644 self.as_parcel_mut().SkipBytes(size) 645 } 646 as_msg_parcel_mut(&mut self) -> Pin<&mut MessageParcel>647 fn as_msg_parcel_mut(&mut self) -> Pin<&mut MessageParcel> { 648 match &mut self.inner { 649 ParcelMem::Unique(p) => p.pin_mut(), 650 ParcelMem::Borrow(p) => unsafe { Pin::new_unchecked(&mut **p) }, 651 _ => unreachable!(), 652 } 653 } 654 as_parcel(&self) -> &Parcel655 fn as_parcel(&self) -> &Parcel { 656 match &self.inner { 657 ParcelMem::Unique(p) => unsafe { 658 let parcel = AsParcel(p.as_ref().unwrap()); 659 &*parcel 660 }, 661 ParcelMem::Borrow(p) => unsafe { 662 let parcel = AsParcel(&**p); 663 &*parcel 664 }, 665 _ => unreachable!(), 666 } 667 } 668 as_parcel_mut(&mut self) -> Pin<&mut Parcel>669 pub(crate) fn as_parcel_mut(&mut self) -> Pin<&mut Parcel> { 670 match &mut self.inner { 671 ParcelMem::Unique(p) => unsafe { 672 let parcel = AsParcelMut(p.pin_mut()); 673 Pin::new_unchecked(&mut *parcel) 674 }, 675 ParcelMem::Borrow(p) => unsafe { 676 let parcel = AsParcelMut(Pin::new_unchecked(&mut **p)); 677 Pin::new_unchecked(&mut *parcel) 678 }, 679 _ => unreachable!(), 680 } 681 } 682 write_process<T>( &mut self, value: T, f: fn(parcel: Pin<&mut MessageParcel>, value: T) -> bool, ) -> IpcResult<()>683 pub(crate) fn write_process<T>( 684 &mut self, 685 value: T, 686 f: fn(parcel: Pin<&mut MessageParcel>, value: T) -> bool, 687 ) -> IpcResult<()> { 688 match mem::replace(&mut self.inner, ParcelMem::Null) { 689 ParcelMem::Unique(mut p) => { 690 let res = f(p.pin_mut(), value); 691 self.inner = ParcelMem::Unique(p); 692 match res { 693 true => Ok(()), 694 false => Err(IpcStatusCode::Failed), 695 } 696 } 697 ParcelMem::Borrow(p) => { 698 let w = unsafe { Pin::new_unchecked(&mut *p) }; 699 let res = f(w, value); 700 self.inner = ParcelMem::Borrow(p); 701 match res { 702 true => Ok(()), 703 false => Err(IpcStatusCode::Failed), 704 } 705 } 706 ParcelMem::Null => IpcResult::Err(IpcStatusCode::Failed), 707 } 708 } 709 read_process<T>( &mut self, f: fn(parcel: Pin<&mut MessageParcel>) -> IpcResult<T>, ) -> IpcResult<T>710 pub(crate) fn read_process<T>( 711 &mut self, 712 f: fn(parcel: Pin<&mut MessageParcel>) -> IpcResult<T>, 713 ) -> IpcResult<T> { 714 match mem::replace(&mut self.inner, ParcelMem::Null) { 715 ParcelMem::Unique(mut p) => { 716 let res = f(p.pin_mut()); 717 self.inner = ParcelMem::Unique(p); 718 res 719 } 720 ParcelMem::Borrow(p) => { 721 let w = unsafe { Pin::new_unchecked(&mut *p) }; 722 let res = f(w); 723 self.inner = ParcelMem::Borrow(p); 724 res 725 } 726 ParcelMem::Null => IpcResult::Err(IpcStatusCode::Failed), 727 } 728 } 729 pin_mut(&mut self) -> Option<Pin<&mut MessageParcel>>730 pub fn pin_mut(&mut self) -> Option<Pin<&mut MessageParcel>> { 731 match &mut self.inner { 732 ParcelMem::Unique(p) => Some(p.pin_mut()), 733 _ => None, 734 } 735 } 736 get_pad_size(size: usize) -> usize737 fn get_pad_size(size: usize) -> usize { 738 const SIZE_OFFSET: usize = 3; 739 ((size + SIZE_OFFSET) & (!SIZE_OFFSET)) - size 740 } 741 } 742 743 /// Ipc MsgOption used when send request, including some settings. 744 pub struct MsgOption { 745 pub(crate) inner: UniquePtr<MessageOption>, 746 } 747 748 impl MsgOption { 749 const TF_SYNC: i32 = 0x00; 750 const TF_ASYNC: i32 = 0x01; 751 752 /// Creates a new, empty MsgOption. 753 754 /// # Panics 755 /// Panics if allocate failed. 756 /// 757 /// # Examples 758 /// ```rust 759 /// use ipc::parcel::MsgOption; 760 /// 761 /// let msg = MsgOption::new(); 762 /// ``` new() -> Self763 pub fn new() -> Self { 764 let ptr = NewMessageOption(); 765 assert!(!ptr.is_null(), "memory allocation of MessageOption failed"); 766 767 Self { 768 inner: NewMessageOption(), 769 } 770 } 771 772 /// Set send to be async. set_async(&mut self)773 pub fn set_async(&mut self) { 774 self.inner.pin_mut().SetFlags(Self::TF_ASYNC); 775 } 776 777 /// Sets send to be sync. set_sync(&mut self)778 pub fn set_sync(&mut self) { 779 self.inner.pin_mut().SetFlags(Self::TF_SYNC); 780 } 781 782 /// Return true if has set to async. is_async(&self) -> bool783 pub fn is_async(&self) -> bool { 784 self.inner.GetFlags() == Self::TF_ASYNC 785 } 786 } 787 788 impl Default for MsgParcel { default() -> Self789 fn default() -> Self { 790 Self::new() 791 } 792 } 793 794 impl Default for MsgOption { default() -> Self795 fn default() -> Self { 796 Self::new() 797 } 798 } 799 800 #[cfg(test)] 801 mod test { 802 use std::mem; 803 804 use super::MsgParcel; 805 806 /// UT test cases for `GetDataSize` 807 /// 808 /// # Brief 809 /// 1. Creates a MsgParcel 810 /// 2. Writes a value to the MsgParcel and then check its data size. 811 #[test] parcel_size()812 fn parcel_size() { 813 let mut msg = MsgParcel::new(); 814 let mut size = 0; 815 816 msg.write(&1i8).unwrap(); 817 size += mem::size_of::<i32>(); 818 assert_eq!(size, msg.size()); 819 820 msg.write(&1i16).unwrap(); 821 size += mem::size_of::<i32>(); 822 assert_eq!(size, msg.size()); 823 824 msg.write(&1i32).unwrap(); 825 size += mem::size_of::<i32>(); 826 assert_eq!(size, msg.size()); 827 828 msg.write(&1i64).unwrap(); 829 size += mem::size_of::<i64>(); 830 assert_eq!(size, msg.size()); 831 832 msg.write(&1u8).unwrap(); 833 size += mem::size_of::<u32>(); 834 assert_eq!(size, msg.size()); 835 836 msg.write(&1u16).unwrap(); 837 size += mem::size_of::<u32>(); 838 assert_eq!(size, msg.size()); 839 840 msg.write(&1u32).unwrap(); 841 size += mem::size_of::<u32>(); 842 assert_eq!(size, msg.size()); 843 844 msg.write(&1u64).unwrap(); 845 size += mem::size_of::<u64>(); 846 assert_eq!(size, msg.size()); 847 848 msg.write(&true).unwrap(); 849 size += mem::size_of::<i32>(); 850 assert_eq!(size, msg.size()); 851 } 852 853 /// UT test cases for read_to_end 854 /// 855 /// # Brief 856 /// 1. Creates a new MsgParcel. 857 /// 3. Write a bool and read it out. 858 /// 2. write a vector into this MsgParcel, and read_to_end check the 859 /// correctness. 860 #[test] read_to_end()861 fn read_to_end() { 862 let mut msg = MsgParcel::new(); 863 msg.write(&true).unwrap(); 864 msg.read::<bool>().unwrap(); 865 866 msg.write(&vec![1, 2, 3]).unwrap(); 867 assert_eq!( 868 vec![3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0], 869 msg.read_buffer(msg.readable()).unwrap() 870 ); 871 } 872 } 873