1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 use std::collections::HashMap;
17 use std::sync::{RwLock, RwLockReadGuard};
18 
19 use ipc::parcel::{Deserialize, MsgParcel, Serialize};
20 use ipc::remote::RemoteObj;
21 use ipc::{IpcResult, IpcStatusCode};
22 
23 use crate::ipc_conn::asset::{CloudAsset, CloudAssets};
24 use crate::ipc_conn::error::{Error, Errors};
25 use crate::ipc_conn::ffi::ConnectService;
26 use crate::ipc_conn::function::CloudServiceFunc::{
27     GetAppBriefInfo, GetAppSchema, GetServiceInfo, Subscribe, Unsubscribe,
28 };
29 use crate::ipc_conn::{
30     string_hash_map_raw_read, string_hash_map_raw_write, vec_raw_read, vec_raw_write,
31 };
32 
33 /// ************ All AppSchema struct-related structures and methods
34 /// *************
35 
36 #[derive(Default, Debug, PartialEq, Clone)]
37 pub(crate) struct Response {
38     pub(crate) time: u64,
39     pub(crate) device_name: String,
40     pub(crate) app_id: String,
41 }
42 
43 impl Serialize for Response {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>44     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
45         parcel.write(&self.time)?;
46         parcel.write_string16(&self.device_name)?;
47         parcel.write_string16(&self.app_id)?;
48         Ok(())
49     }
50 }
51 
52 impl Deserialize for Response {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>53     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
54         let time = parcel.read::<u64>()?;
55         let device_name = parcel.read_string16()?;
56         let app_id = parcel.read_string16()?;
57 
58         let result = Response {
59             time,
60             device_name,
61             app_id,
62         };
63         Ok(result)
64     }
65 }
66 
67 /// Struct that mark status of an Asset.
68 #[repr(C)]
69 #[derive(Eq, Clone, Debug, PartialEq)]
70 pub enum AssetStatus {
71     /// Normal. Everything works fine for the asset.
72     Normal,
73     /// The asset is about to be inserted.
74     Insert,
75     /// The asset is about to be updated.
76     Update,
77     /// The asset is about to be deleted.
78     Delete,
79     /// The asset is abnormal and something is wrong with it.
80     Abnormal,
81     /// The asset is being downloading.
82     Downloading,
83 }
84 
85 impl Default for AssetStatus {
default() -> Self86     fn default() -> Self {
87         Self::Normal
88     }
89 }
90 
91 impl Serialize for AssetStatus {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>92     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
93         match self {
94             AssetStatus::Normal => parcel.write(&0_i32),
95             AssetStatus::Insert => parcel.write(&1_i32),
96             AssetStatus::Update => parcel.write(&2_i32),
97             AssetStatus::Delete => parcel.write(&3_i32),
98             AssetStatus::Abnormal => parcel.write(&4_i32),
99             AssetStatus::Downloading => parcel.write(&5_i32),
100         }
101     }
102 }
103 
104 impl Deserialize for AssetStatus {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>105     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
106         let index = parcel.read::<i32>()?;
107         match index {
108             0 => Ok(AssetStatus::Normal),
109             1 => Ok(AssetStatus::Insert),
110             2 => Ok(AssetStatus::Update),
111             3 => Ok(AssetStatus::Delete),
112             4 => Ok(AssetStatus::Abnormal),
113             5 => Ok(AssetStatus::Downloading),
114             _ => Err(IpcStatusCode::Failed),
115         }
116     }
117 }
118 
119 #[derive(Debug, PartialEq)]
120 pub(crate) enum SwitchStatus {
121     Close,
122     Open,
123     NotEnable,
124 }
125 
126 impl Default for SwitchStatus {
default() -> Self127     fn default() -> Self {
128         Self::Close
129     }
130 }
131 
132 impl Serialize for SwitchStatus {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>133     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
134         match self {
135             SwitchStatus::Close => parcel.write(&0_u32),
136             SwitchStatus::Open => parcel.write(&1_u32),
137             SwitchStatus::NotEnable => parcel.write(&2_u32),
138         }
139     }
140 }
141 
142 impl Deserialize for SwitchStatus {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>143     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
144         let index = parcel.read::<u32>()?;
145         match index {
146             0 => Ok(SwitchStatus::Close),
147             1 => Ok(SwitchStatus::Open),
148             2 => Ok(SwitchStatus::NotEnable),
149             _ => Err(IpcStatusCode::Failed),
150         }
151     }
152 }
153 
154 #[derive(Debug, Clone)]
155 pub enum FieldRaw {
156     Null,
157     Number(i64),
158     Real(f64),
159     Text(String),
160     Bool(bool),
161     Blob(Vec<u8>),
162     Asset(CloudAsset),
163     Assets(CloudAssets),
164 }
165 
166 impl From<FieldRaw> for u8 {
from(value: FieldRaw) -> Self167     fn from(value: FieldRaw) -> Self {
168         match value {
169             FieldRaw::Null => 0,
170             FieldRaw::Number(_) => 1,
171             FieldRaw::Real(_) => 2,
172             FieldRaw::Text(_) => 3,
173             FieldRaw::Bool(_) => 4,
174             FieldRaw::Blob(_) => 5,
175             FieldRaw::Asset(_) => 6,
176             FieldRaw::Assets(_) => 7,
177         }
178     }
179 }
180 
181 impl Serialize for FieldRaw {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>182     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
183         match self {
184             FieldRaw::Null => parcel.write(&0_u32),
185             FieldRaw::Number(number) => {
186                 parcel.write(&1_u32)?;
187                 parcel.write(number)
188             }
189             FieldRaw::Real(real) => {
190                 parcel.write(&2_u32)?;
191                 parcel.write(real)
192             }
193             FieldRaw::Text(text) => {
194                 parcel.write(&3_u32)?;
195                 parcel.write_string16(text)
196             }
197             FieldRaw::Bool(boolean) => {
198                 parcel.write(&4_u32)?;
199                 parcel.write(boolean)
200             }
201             FieldRaw::Blob(blob) => {
202                 parcel.write(&5_u32)?;
203                 parcel.write(blob)
204             }
205             FieldRaw::Asset(asset) => {
206                 parcel.write(&6_u32)?;
207                 parcel.write(asset)
208             }
209             FieldRaw::Assets(assets) => {
210                 parcel.write(&7_u32)?;
211                 parcel.write(assets)
212             }
213         }
214     }
215 }
216 
217 impl Deserialize for FieldRaw {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>218     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
219         let index = parcel.read::<u32>()?;
220         match index {
221             0 => Ok(FieldRaw::Null),
222             1 => {
223                 let number = parcel.read::<i64>()?;
224                 Ok(FieldRaw::Number(number))
225             }
226             2 => {
227                 let real = parcel.read::<f64>()?;
228                 Ok(FieldRaw::Real(real))
229             }
230             3 => {
231                 let text = parcel.read_string16()?;
232                 Ok(FieldRaw::Text(text))
233             }
234             4 => {
235                 let boolean = parcel.read::<bool>()?;
236                 Ok(FieldRaw::Bool(boolean))
237             }
238             5 => {
239                 let blob = parcel.read::<Vec<u8>>()?;
240                 Ok(FieldRaw::Blob(blob))
241             }
242             6 => {
243                 let asset = parcel.read::<CloudAsset>()?;
244                 Ok(FieldRaw::Asset(asset))
245             }
246             7 => {
247                 let assets = parcel.read::<CloudAssets>()?;
248                 Ok(FieldRaw::Assets(assets))
249             }
250             _ => Err(IpcStatusCode::Failed),
251         }
252     }
253 }
254 
255 /// Struct ValueBucket.
256 #[derive(Default, Debug, Clone)]
257 pub struct ValueBucket(pub HashMap<String, FieldRaw>);
258 
259 impl Serialize for ValueBucket {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>260     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
261         string_hash_map_raw_write(parcel, &self.0)
262     }
263 }
264 
265 impl Deserialize for ValueBucket {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>266     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
267         let result = string_hash_map_raw_read::<FieldRaw>(parcel)?;
268         Ok(ValueBucket(result))
269     }
270 }
271 
272 #[derive(Default, Debug)]
273 pub(crate) struct ValueBuckets(pub(crate) Vec<ValueBucket>);
274 
275 impl Serialize for ValueBuckets {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>276     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
277         vec_raw_write(parcel, &self.0)
278     }
279 }
280 
281 impl Deserialize for ValueBuckets {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>282     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
283         let result = ValueBuckets(vec_raw_read::<ValueBucket>(parcel)?);
284         Ok(result)
285     }
286 }
287 
288 #[derive(Default, Debug)]
289 pub(crate) struct CloudData {
290     pub(crate) next_cursor: String,
291     pub(crate) has_more: bool,
292     pub(crate) values: ValueBuckets,
293 }
294 
295 impl Deserialize for CloudData {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>296     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
297         let next_cursor = parcel.read_string16()?;
298         let has_more = parcel.read::<bool>()?;
299         let values = parcel.read::<ValueBuckets>()?;
300 
301         let cloud_data = CloudData {
302             next_cursor,
303             has_more,
304             values,
305         };
306         Ok(cloud_data)
307     }
308 }
309 
310 #[derive(Default)]
311 pub(crate) struct Database {
312     pub(crate) alias: String,
313     pub(crate) name: String,
314     pub(crate) tables: SchemaOrderTables,
315 }
316 
317 impl Serialize for Database {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>318     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
319         parcel.write_string16(&self.alias)?;
320         parcel.write_string16(&self.name)?;
321         parcel.write(&self.tables)?;
322         Ok(())
323     }
324 }
325 
326 impl Deserialize for Database {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>327     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
328         let alias = parcel.read_string16()?;
329         let name = parcel.read_string16()?;
330         let tables = parcel.read::<SchemaOrderTables>()?;
331 
332         let result = Database {
333             name,
334             alias,
335             tables,
336         };
337         Ok(result)
338     }
339 }
340 
341 #[derive(Default, Debug, PartialEq)]
342 pub(crate) enum FieldType {
343     #[default]
344     Null,
345     Number,
346     Real,
347     Text,
348     Bool,
349     Blob,
350     Asset,
351     Assets,
352 }
353 
354 impl From<&FieldType> for u8 {
from(value: &FieldType) -> Self355     fn from(value: &FieldType) -> Self {
356         match value {
357             FieldType::Null => 0,
358             FieldType::Number => 1,
359             FieldType::Real => 2,
360             FieldType::Text => 3,
361             FieldType::Bool => 4,
362             FieldType::Blob => 5,
363             FieldType::Asset => 6,
364             FieldType::Assets => 7,
365         }
366     }
367 }
368 
369 impl TryFrom<u8> for FieldType {
370     type Error = Error;
371 
try_from(value: u8) -> Result<Self, Self::Error>372     fn try_from(value: u8) -> Result<Self, Self::Error> {
373         let typ = match value {
374             0 => FieldType::Null,
375             1 => FieldType::Number,
376             2 => FieldType::Real,
377             3 => FieldType::Text,
378             4 => FieldType::Bool,
379             5 => FieldType::Blob,
380             6 => FieldType::Asset,
381             7 => FieldType::Assets,
382             _ => return Err(Error::InvalidFieldType),
383         };
384         Ok(typ)
385     }
386 }
387 
388 impl Serialize for FieldType {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>389     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
390         let code = u8::from(self) as u32;
391         parcel.write(&code)
392     }
393 }
394 
395 impl Deserialize for FieldType {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>396     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
397         let index = parcel.read::<i32>()?;
398         match index {
399             0 => Ok(FieldType::Null),
400             1 => Ok(FieldType::Number),
401             2 => Ok(FieldType::Real),
402             3 => Ok(FieldType::Text),
403             4 => Ok(FieldType::Bool),
404             5 => Ok(FieldType::Blob),
405             6 => Ok(FieldType::Asset),
406             7 => Ok(FieldType::Assets),
407             _ => Err(IpcStatusCode::Failed),
408         }
409     }
410 }
411 
412 #[derive(Default, Debug, PartialEq)]
413 pub(crate) struct Field {
414     pub(crate) col_name: String,
415     pub(crate) alias: String,
416     pub(crate) typ: FieldType,
417     pub(crate) primary: bool,
418     pub(crate) nullable: bool,
419 }
420 
421 impl Serialize for Field {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>422     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
423         parcel.write_string16(&self.alias)?;
424         parcel.write_string16(&self.col_name)?;
425         parcel.write(&self.typ)?;
426         parcel.write(&self.primary)?;
427         parcel.write(&self.nullable)?;
428         Ok(())
429     }
430 }
431 
432 impl Deserialize for Field {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>433     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
434         let col_name = parcel.read_string16()?;
435         let cloud_name = parcel.read_string16()?;
436         let typ = parcel.read::<FieldType>()?;
437         let primary = parcel.read::<bool>()?;
438         let nullable = parcel.read::<bool>()?;
439 
440         let result = Field {
441             col_name,
442             alias: cloud_name,
443             typ,
444             primary,
445             nullable,
446         };
447         Ok(result)
448     }
449 }
450 
451 #[derive(Default, Debug, PartialEq)]
452 pub(crate) struct Fields(pub(crate) Vec<Field>);
453 
454 impl Serialize for Fields {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>455     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
456         vec_raw_write(parcel, &self.0)
457     }
458 }
459 
460 impl Deserialize for Fields {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>461     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
462         let result = Fields(vec_raw_read::<Field>(parcel)?);
463         Ok(result)
464     }
465 }
466 
467 #[derive(Default, Debug, PartialEq)]
468 pub(crate) struct OrderTable {
469     pub(crate) alias: String,
470     pub(crate) table_name: String,
471     pub(crate) fields: Fields,
472 }
473 
474 impl Serialize for OrderTable {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>475     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
476         parcel.write_string16(&self.alias)?;
477         parcel.write_string16(&self.table_name)?;
478         parcel.write(&self.fields)?;
479         Ok(())
480     }
481 }
482 
483 impl Deserialize for OrderTable {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>484     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
485         let result = OrderTable {
486             alias: parcel.read_string16()?,
487             table_name: parcel.read_string16()?,
488             fields: parcel.read::<Fields>()?,
489         };
490         Ok(result)
491     }
492 }
493 
494 #[derive(Default, Debug, PartialEq)]
495 pub(crate) struct SchemaOrderTables(pub(crate) Vec<OrderTable>);
496 
497 impl Serialize for SchemaOrderTables {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>498     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
499         vec_raw_write(parcel, &self.0)
500     }
501 }
502 
503 impl Deserialize for SchemaOrderTables {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>504     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
505         let result = SchemaOrderTables(vec_raw_read::<OrderTable>(parcel)?);
506         Ok(result)
507     }
508 }
509 
510 #[derive(Default)]
511 pub(crate) struct Databases(pub(crate) Vec<Database>);
512 
513 impl Serialize for Databases {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>514     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
515         vec_raw_write(parcel, &self.0)
516     }
517 }
518 
519 impl Deserialize for Databases {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>520     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
521         let databases = Databases(vec_raw_read(parcel)?);
522         Ok(databases)
523     }
524 }
525 
526 #[derive(Default)]
527 pub(crate) struct Schema {
528     pub(crate) version: i32,
529     pub(crate) bundle_name: String,
530     pub(crate) databases: Databases,
531 }
532 
533 impl Schema {
read(&mut self, msg_parcel: &mut MsgParcel) -> Result<(), Error>534     fn read(&mut self, msg_parcel: &mut MsgParcel) -> Result<(), Error> {
535         if msg_parcel
536             .read::<i32>()
537             .map_err(|_| Error::ReadMsgParcelFailed)?
538             == 0
539         {
540             self.version = msg_parcel
541                 .read::<i32>()
542                 .map_err(|_| Error::ReadMsgParcelFailed)?;
543             self.bundle_name = msg_parcel
544                 .read_string16()
545                 .map_err(|_| Error::ReadMsgParcelFailed)?;
546             self.databases = msg_parcel
547                 .read::<Databases>()
548                 .map_err(|_| Error::ReadMsgParcelFailed)?;
549             Ok(())
550         } else {
551             Err(Error::ReadMsgParcelFailed)
552         }
553     }
554 }
555 
556 impl Deserialize for Schema {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>557     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
558         let version = parcel.read::<i32>()?;
559         let bundle_name = parcel.read_string16()?;
560         let databases = parcel.read::<Databases>()?;
561 
562         let result = Schema {
563             version,
564             bundle_name,
565             databases,
566         };
567         Ok(result)
568     }
569 }
570 
571 /// ************ All AppInfo struct-related structures and methods *************
572 
573 #[derive(Default, Debug, PartialEq)]
574 pub(crate) struct AppInfo {
575     pub(crate) app_id: String,
576     pub(crate) bundle_name: String,
577     pub(crate) cloud_switch: bool,
578     pub(crate) instance_id: i32,
579 }
580 
581 impl Deserialize for AppInfo {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>582     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
583         let app_id = parcel.read_string16()?;
584         let bundle_name = parcel.read_string16()?;
585         let cloud_switch = parcel.read::<i32>()? != 0;
586         let instance_id = parcel.read::<i32>()?;
587 
588         let result = Self {
589             app_id,
590             bundle_name,
591             cloud_switch,
592             instance_id,
593         };
594         Ok(result)
595     }
596 }
597 
598 /// ************ All ServiceInfo struct-related structures and methods
599 /// *************
600 #[derive(Default)]
601 pub(crate) struct ServiceInfo {
602     // Whether cloud is enabled.
603     pub(crate) enable_cloud: bool,
604 
605     // ID of the cloud account generated by using SHA-256.
606     pub(crate) account_id: String,
607 
608     // Total space (in KB) of the account on the server.
609     pub(crate) total_space: u64,
610 
611     // Available space (in KB) of the account on the server.
612     pub(crate) remain_space: u64,
613 
614     // Current user of the device.
615     pub(crate) user: i32,
616 }
617 
618 impl ServiceInfo {
read(&mut self, msg_parcel: &mut MsgParcel) -> Result<(), Error>619     fn read(&mut self, msg_parcel: &mut MsgParcel) -> Result<(), Error> {
620         self.enable_cloud = msg_parcel
621             .read::<bool>()
622             .map_err(|_| Error::ReadMsgParcelFailed)?;
623         self.account_id = msg_parcel
624             .read_string16()
625             .map_err(|_| Error::ReadMsgParcelFailed)?;
626         self.total_space = msg_parcel
627             .read::<u64>()
628             .map_err(|_| Error::ReadMsgParcelFailed)?;
629         self.remain_space = msg_parcel
630             .read::<u64>()
631             .map_err(|_| Error::ReadMsgParcelFailed)?;
632         self.user = msg_parcel
633             .read::<i32>()
634             .map_err(|_| Error::ReadMsgParcelFailed)?;
635         Ok(())
636     }
637 }
638 
639 /// ************ All Subscribe struct-related structures and methods
640 /// *************
641 
642 #[derive(Default)]
643 #[non_exhaustive]
644 pub(crate) struct Subscription;
645 
646 #[derive(Default, Debug, PartialEq)]
647 pub(crate) struct SubscriptionResultValue(pub(crate) Vec<(String, String)>);
648 
649 impl Deserialize for SubscriptionResultValue {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>650     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
651         let length = parcel.read::<i32>()? as usize;
652         let mut vector = Vec::with_capacity(length);
653         for _ in 0..length {
654             let alias = parcel.read_string16()?;
655             let subscription_id = parcel.read_string16()?;
656             vector.push((alias, subscription_id));
657         }
658         Ok(SubscriptionResultValue(vector))
659     }
660 }
661 
662 #[derive(Default, Debug)]
663 pub(crate) struct SubscriptionResult(pub(crate) (i64, HashMap<String, SubscriptionResultValue>));
664 
665 impl Deserialize for SubscriptionResult {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>666     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
667         let interval = parcel.read::<i64>()?;
668         let result = string_hash_map_raw_read::<SubscriptionResultValue>(parcel)?;
669         Ok(SubscriptionResult((interval, result)))
670     }
671 }
672 
673 #[derive(Default)]
674 pub(crate) struct UnsubscriptionInfo(pub(crate) HashMap<String, Vec<String>>);
675 
676 impl Serialize for UnsubscriptionInfo {
serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()>677     fn serialize(&self, parcel: &mut MsgParcel) -> IpcResult<()> {
678         string_hash_map_raw_write(parcel, &self.0)
679     }
680 }
681 
682 impl Subscription {
683     // For subsequent extensibility, use `&self` here.
subscribe( &self, remote: &Option<RemoteObj>, expiration: i64, bundle_name: &str, databases: &Databases, ) -> Result<SubscriptionResult, Errors>684     pub(crate) fn subscribe(
685         &self,
686         remote: &Option<RemoteObj>,
687         expiration: i64,
688         bundle_name: &str,
689         databases: &Databases,
690     ) -> Result<SubscriptionResult, Errors> {
691         let mut msg_parcel = MsgParcel::new();
692 
693         msg_parcel
694             .write(&expiration)
695             .map_err(|_| Errors(vec![Error::WriteMsgParcelFailed]))?;
696         msg_parcel
697             .write_string16(bundle_name)
698             .map_err(|_| Errors(vec![Error::WriteMsgParcelFailed]))?;
699         msg_parcel
700             .write(databases)
701             .map_err(|_| Errors(vec![Error::WriteMsgParcelFailed]))?;
702 
703         let function_number = Subscribe as u32;
704         let remote_obj = remote
705             .as_ref()
706             .ok_or(Errors(vec![Error::CreateMsgParcelFailed]))?;
707         let mut receive = remote_obj
708             .send_request(function_number, &mut msg_parcel)
709             .map_err(|_| Errors(vec![Error::SendRequestFailed]))?;
710 
711         let mut errs = Errors::default();
712         errs.0.push(Error::ReadMsgParcelFailed);
713         if receive.read::<i32>().map_err(|_| errs)? == 0 {
714             if let Ok(cloud_subscription_info) = receive.read::<SubscriptionResult>() {
715                 return Ok(cloud_subscription_info);
716             }
717         }
718 
719         let mut errs = Errors::default();
720         errs.0.push(Error::ReadMsgParcelFailed);
721         Err(errs)
722     }
723 
unsubscribe( &self, remote: &Option<RemoteObj>, info: &UnsubscriptionInfo, ) -> Result<(), Errors>724     pub(crate) fn unsubscribe(
725         &self,
726         remote: &Option<RemoteObj>,
727         info: &UnsubscriptionInfo,
728     ) -> Result<(), Errors> {
729         let mut msg_parcel = MsgParcel::new();
730 
731         msg_parcel
732             .write(info)
733             .map_err(|_| Errors(vec![Error::WriteMsgParcelFailed]))?;
734 
735         let function_number = Unsubscribe as u32;
736         let remote_obj = remote
737             .as_ref()
738             .ok_or(Errors(vec![Error::CreateMsgParcelFailed]))?;
739         let mut receive = remote_obj
740             .send_request(function_number, &mut msg_parcel)
741             .map_err(|_| Errors(vec![Error::SendRequestFailed]))?;
742 
743         if let Ok(errs) = receive.read::<Errors>() {
744             return Err(errs);
745         }
746 
747         Ok(())
748     }
749 }
750 
751 /// ************ All Connect struct-related structures and methods *************
752 
753 pub(crate) type ConnectResult<T> = Result<T, Error>;
754 
755 pub(crate) struct Connect {
756     pub(crate) remote_obj: Option<RemoteObj>,
757     infos: HashMap<i32, Infos>,
758 }
759 
760 impl Connect {
761     // Creates a structure `Connect` for connecting to the cloud and getting various
762     // information about the cloud.
new(user_id: i32) -> ConnectResult<Self>763     pub(crate) fn new(user_id: i32) -> ConnectResult<Self> {
764         let remote_obj = unsafe { RemoteObj::from_ciremote(ConnectService(user_id)) }
765             .ok_or(Error::GetProxyObjectFailed)?;
766         Ok(Self {
767             remote_obj: Some(remote_obj),
768             infos: HashMap::default(),
769         })
770     }
771 
772     // Sends `MsgParcel` to the cloud,
773     // wait for the return value from the cloud,
774     // get the required app infos from the cloud.
get_app_brief_info( &mut self, user_id: i32, ) -> ConnectResult<RwLockReadGuard<AppInfos>>775     pub(crate) fn get_app_brief_info(
776         &mut self,
777         user_id: i32,
778     ) -> ConnectResult<RwLockReadGuard<AppInfos>> {
779         self.infos.entry(user_id).or_default();
780         let infos = self.infos.get_mut(&user_id).unwrap();
781 
782         let mut lock = infos.app_infos.write().unwrap();
783 
784         let mut msg_parcel = MsgParcel::new();
785 
786         let function_number = GetAppBriefInfo as u32;
787         let remote_obj = self
788             .remote_obj
789             .as_ref()
790             .ok_or(Error::GetProxyObjectFailed)?;
791         let mut receive = remote_obj
792             .send_request(function_number, &mut msg_parcel)
793             .map_err(|_| Error::SendRequestFailed)?;
794 
795         lock.0 = receive
796             .read::<AppInfos>()
797             .map_err(|_| Error::ReadMsgParcelFailed)?
798             .0;
799 
800         drop(lock);
801 
802         Ok(infos.app_infos.read().unwrap())
803     }
804 
805     // Sends `MsgParcel` to the cloud,
806     // wait for the return value from the cloud,
807     // get the required user info from the cloud.
get_service_info( &mut self, user_id: i32, ) -> ConnectResult<RwLockReadGuard<ServiceInfo>>808     pub(crate) fn get_service_info(
809         &mut self,
810         user_id: i32,
811     ) -> ConnectResult<RwLockReadGuard<ServiceInfo>> {
812         self.infos.entry(user_id).or_default();
813         let infos = self.infos.get_mut(&user_id).unwrap();
814 
815         let mut lock = infos.service_info.write().unwrap();
816 
817         let mut msg_parcel = MsgParcel::new();
818 
819         let function_number = GetServiceInfo as u32;
820         let remote_obj = self
821             .remote_obj
822             .clone()
823             .ok_or(Error::CreateMsgParcelFailed)?;
824         let mut receive = remote_obj
825             .send_request(function_number, &mut msg_parcel)
826             .map_err(|_| Error::SendRequestFailed)?;
827 
828         lock.read(&mut receive)?;
829 
830         drop(lock);
831 
832         Ok(infos.service_info.read().unwrap())
833     }
834 
get_app_schema( &mut self, user_id: i32, bundle_name: &str, ) -> ConnectResult<RwLockReadGuard<Schema>>835     pub(crate) fn get_app_schema(
836         &mut self,
837         user_id: i32,
838         bundle_name: &str,
839     ) -> ConnectResult<RwLockReadGuard<Schema>> {
840         self.infos.entry(user_id).or_default();
841         let infos = self.infos.get_mut(&user_id).unwrap();
842 
843         let mut lock = infos.app_schema.write().unwrap();
844 
845         let mut msg_parcel = MsgParcel::new();
846 
847         msg_parcel
848             .write_string16(bundle_name)
849             .map_err(|_| Error::WriteMsgParcelFailed)?;
850 
851         let function_number = GetAppSchema as u32;
852         let remote_obj = self
853             .remote_obj
854             .clone()
855             .ok_or(Error::CreateMsgParcelFailed)?;
856         let mut receive = remote_obj
857             .send_request(function_number, &mut msg_parcel)
858             .map_err(|_| Error::SendRequestFailed)?;
859 
860         lock.read(&mut receive)?;
861 
862         drop(lock);
863 
864         Ok(infos.app_schema.read().unwrap())
865     }
866 
subscribe( &self, expiration: i64, bundle_name: &str, databases: &Databases, ) -> Result<SubscriptionResult, Errors>867     pub(crate) fn subscribe(
868         &self,
869         expiration: i64,
870         bundle_name: &str,
871         databases: &Databases,
872     ) -> Result<SubscriptionResult, Errors> {
873         let subscription = Subscription::default();
874         subscription.subscribe(&self.remote_obj, expiration, bundle_name, databases)
875     }
876 
unsubscribe(&self, info: &UnsubscriptionInfo) -> Result<(), Errors>877     pub(crate) fn unsubscribe(&self, info: &UnsubscriptionInfo) -> Result<(), Errors> {
878         let subscription = Subscription::default();
879         subscription.unsubscribe(&self.remote_obj, info)
880     }
881 }
882 
883 #[derive(Default)]
884 pub(crate) struct AppInfos(pub(crate) HashMap<String, AppInfo>);
885 
886 impl Deserialize for AppInfos {
deserialize(parcel: &mut MsgParcel) -> IpcResult<Self>887     fn deserialize(parcel: &mut MsgParcel) -> IpcResult<Self> {
888         let result = AppInfos(string_hash_map_raw_read::<AppInfo>(parcel)?);
889         Ok(result)
890     }
891 }
892 
893 #[derive(Default)]
894 pub(crate) struct Infos {
895     app_infos: RwLock<AppInfos>,
896     service_info: RwLock<ServiceInfo>,
897     app_schema: RwLock<Schema>,
898 }
899 
900 #[cfg(test)]
901 mod connect_test {
902     use ipc::parcel::MsgParcel;
903 
904     use crate::ipc_conn::connect::{Response, SubscriptionResultValue, SwitchStatus};
905     use crate::ipc_conn::{
906         AppInfo, AssetStatus, CloudAsset, CloudAssets, CloudData, Database, Databases, FieldRaw,
907         OrderTable, Schema, SchemaOrderTables, ValueBucket, ValueBuckets,
908     };
909 
910     /// UT test for response_serialize.
911     ///
912     /// # Title
913     /// ut_response_serialize
914     ///
915     /// # Brief
916     /// 1. Create a `Response` struct.
917     /// 2. Serialize the struct.
918     /// 3. Check if it is correct.
919     #[test]
ut_response_serialize()920     fn ut_response_serialize() {
921         let response = Response::default();
922 
923         let mut msg_parcel = MsgParcel::new();
924         msg_parcel.write(&response).unwrap();
925 
926         assert_eq!(msg_parcel.read::<i64>().unwrap(), 0);
927         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
928         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
929     }
930 
931     /// UT test for response_deserialize.
932     ///
933     /// # Title
934     /// ut_response_deserialize
935     ///
936     /// # Brief
937     /// 1. Create a `Response` struct.
938     /// 2. Serialize the struct.
939     /// 3. Read the data in `MsgParcel`.
940     /// 4. Deserialize the data to `Response`.
941     /// 5. Check if it is correct.
942     #[test]
ut_response_deserialize()943     fn ut_response_deserialize() {
944         let response = Response::default();
945 
946         let mut msg_parcel = MsgParcel::new();
947         msg_parcel.write(&response).unwrap();
948 
949         assert_eq!(msg_parcel.read::<Response>().unwrap(), response);
950     }
951 
952     /// UT test for operation_type_serialize.
953     ///
954     /// # Title
955     /// ut_operation_type_serialize
956     ///
957     /// # Brief
958     /// 1. Create a `OperationType` enum.
959     /// 2. Serialize the enum.
960     /// 3. Check if it is correct.
961     #[test]
ut_operation_type_serialize()962     fn ut_operation_type_serialize() {
963         let normal = AssetStatus::Normal;
964         let insert = AssetStatus::Insert;
965         let update = AssetStatus::Update;
966         let delete = AssetStatus::Delete;
967         let abnormal = AssetStatus::Abnormal;
968         let downloading = AssetStatus::Downloading;
969 
970         let mut msg_parcel = MsgParcel::new();
971         msg_parcel.write(&normal).unwrap();
972         msg_parcel.write(&insert).unwrap();
973         msg_parcel.write(&update).unwrap();
974         msg_parcel.write(&delete).unwrap();
975         msg_parcel.write(&abnormal).unwrap();
976         msg_parcel.write(&downloading).unwrap();
977 
978         assert_eq!(msg_parcel.read::<u32>().unwrap(), 0_u32);
979         assert_eq!(msg_parcel.read::<u32>().unwrap(), 1_u32);
980         assert_eq!(msg_parcel.read::<u32>().unwrap(), 2_u32);
981         assert_eq!(msg_parcel.read::<u32>().unwrap(), 3_u32);
982         assert_eq!(msg_parcel.read::<u32>().unwrap(), 4_u32);
983         assert_eq!(msg_parcel.read::<u32>().unwrap(), 5_u32);
984     }
985 
986     /// UT test for operation_type_deserialize.
987     ///
988     /// # Title
989     /// ut_operation_type_deserialize
990     ///
991     /// # Brief
992     /// 1. Create a `OperationType` enum.
993     /// 2. Serialize the enum.
994     /// 3. Read the data in `MsgParcel`.
995     /// 4. Deserialize the data to `OperationType`.
996     /// 5. Check if it is correct.
997     #[test]
ut_operation_type_deserialize()998     fn ut_operation_type_deserialize() {
999         let normal = AssetStatus::Normal;
1000         let insert = AssetStatus::Insert;
1001         let update = AssetStatus::Update;
1002         let delete = AssetStatus::Delete;
1003         let abnormal = AssetStatus::Abnormal;
1004         let downloading = AssetStatus::Downloading;
1005 
1006         let mut msg_parcel = MsgParcel::new();
1007         msg_parcel.write(&normal).unwrap();
1008         msg_parcel.write(&insert).unwrap();
1009         msg_parcel.write(&update).unwrap();
1010         msg_parcel.write(&delete).unwrap();
1011         msg_parcel.write(&abnormal).unwrap();
1012         msg_parcel.write(&downloading).unwrap();
1013 
1014         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), normal);
1015         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), insert);
1016         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), update);
1017         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), delete);
1018         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), abnormal);
1019         assert_eq!(msg_parcel.read::<AssetStatus>().unwrap(), downloading);
1020     }
1021 
1022     /// UT test for switch_status_serialize.
1023     ///
1024     /// # Title
1025     /// ut_switch_status_serialize
1026     ///
1027     /// # Brief
1028     /// 1. Create a `SwitchStatus` enum.
1029     /// 2. Serialize the enum.
1030     /// 3. Check if it is correct.
1031     #[test]
ut_switch_status_serialize()1032     fn ut_switch_status_serialize() {
1033         let close = SwitchStatus::Close;
1034         let open = SwitchStatus::Open;
1035         let not_enable = SwitchStatus::NotEnable;
1036 
1037         let mut msg_parcel = MsgParcel::new();
1038         msg_parcel.write(&close).unwrap();
1039         msg_parcel.write(&open).unwrap();
1040         msg_parcel.write(&not_enable).unwrap();
1041 
1042         assert_eq!(msg_parcel.read::<u32>().unwrap(), 0_u32);
1043         assert_eq!(msg_parcel.read::<u32>().unwrap(), 1_u32);
1044         assert_eq!(msg_parcel.read::<u32>().unwrap(), 2_u32);
1045     }
1046 
1047     /// UT test for switch_status_deserialize.
1048     ///
1049     /// # Title
1050     /// ut_switch_status_deserialize
1051     ///
1052     /// # Brief
1053     /// 1. Create a `SwitchStatus` enum.
1054     /// 2. Serialize the enum.
1055     /// 3. Read the data in `MsgParcel`.
1056     /// 4. Deserialize the data to `SwitchStatus`.
1057     /// 5. Check if it is correct.
1058     #[test]
ut_switch_status_deserialize()1059     fn ut_switch_status_deserialize() {
1060         let close = SwitchStatus::Close;
1061         let open = SwitchStatus::Open;
1062         let not_enable = SwitchStatus::NotEnable;
1063 
1064         let mut msg_parcel = MsgParcel::new();
1065         msg_parcel.write(&close).unwrap();
1066         msg_parcel.write(&open).unwrap();
1067         msg_parcel.write(&not_enable).unwrap();
1068 
1069         assert_eq!(msg_parcel.read::<SwitchStatus>().unwrap(), close);
1070         assert_eq!(msg_parcel.read::<SwitchStatus>().unwrap(), open);
1071         assert_eq!(msg_parcel.read::<SwitchStatus>().unwrap(), not_enable);
1072     }
1073 
1074     /// UT test for asset_serialize.
1075     ///
1076     /// # Title
1077     /// ut_asset_serialize
1078     ///
1079     /// # Brief
1080     /// 1. Create a `CloudAsset` struct.
1081     /// 2. Serialize the struct.
1082     /// 3. Check if it is correct.
1083     #[test]
ut_asset_serialize()1084     fn ut_asset_serialize() {
1085         let asset = CloudAsset::default();
1086 
1087         let mut msg_parcel = MsgParcel::new();
1088         msg_parcel.write(&asset).unwrap();
1089 
1090         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1091         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1092         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1093         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1094         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1095         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1096         assert_eq!(
1097             msg_parcel.read::<AssetStatus>().unwrap(),
1098             AssetStatus::Normal
1099         );
1100         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1101         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1102     }
1103 
1104     /// UT test for asset_deserialize.
1105     ///
1106     /// # Title
1107     /// ut_asset_deserialize
1108     ///
1109     /// # Brief
1110     /// 1. Create a `CloudAsset` struct.
1111     /// 2. Serialize the struct.
1112     /// 3. Read the data in `MsgParcel`.
1113     /// 4. Deserialize the data to `CloudAsset`.
1114     /// 5. Check if it is correct.
1115     #[test]
ut_asset_deserialize()1116     fn ut_asset_deserialize() {
1117         let asset = CloudAsset::default();
1118 
1119         let mut msg_parcel = MsgParcel::new();
1120         msg_parcel.write(&asset).unwrap();
1121 
1122         let result = msg_parcel.read::<CloudAsset>().unwrap();
1123         assert_eq!(result.uri, asset.uri);
1124         assert_eq!(result.asset_name, asset.asset_name);
1125         assert_eq!(result.status, asset.status);
1126         assert_eq!(result.create_time, asset.create_time);
1127         assert_eq!(result.modify_time, asset.modify_time);
1128         assert_eq!(result.size, asset.size);
1129         assert_eq!(result.sub_path, asset.sub_path);
1130         assert_eq!(result.hash, asset.hash);
1131         assert_eq!(result.asset_id, asset.asset_id);
1132     }
1133 
1134     /// UT test for assets_serialize.
1135     ///
1136     /// # Title
1137     /// ut_assets_serialize
1138     ///
1139     /// # Brief
1140     /// 1. Create a `CloudAssets` struct.
1141     /// 2. Serialize the struct.
1142     /// 3. Check if it is correct.
1143     #[test]
ut_assets_serialize()1144     fn ut_assets_serialize() {
1145         let mut assets = CloudAssets::default();
1146         let asset_one = CloudAsset::default();
1147         let asset_two = CloudAsset::default();
1148         assets.0.push(asset_one);
1149         assets.0.push(asset_two);
1150 
1151         let mut msg_parcel = MsgParcel::new();
1152         msg_parcel.write(&assets).unwrap();
1153 
1154         assert_eq!(msg_parcel.read::<u32>().unwrap(), 2);
1155 
1156         let default_one = CloudAsset::default();
1157         let result_one = msg_parcel.read::<CloudAsset>().unwrap();
1158         assert_eq!(result_one.uri, default_one.uri);
1159         assert_eq!(result_one.asset_name, default_one.asset_name);
1160         assert_eq!(result_one.status, default_one.status);
1161         assert_eq!(result_one.create_time, default_one.create_time);
1162         assert_eq!(result_one.modify_time, default_one.modify_time);
1163         assert_eq!(result_one.size, default_one.size);
1164         assert_eq!(result_one.sub_path, default_one.sub_path);
1165         assert_eq!(result_one.hash, default_one.hash);
1166         assert_eq!(result_one.asset_id, default_one.asset_id);
1167 
1168         let default_two = CloudAsset::default();
1169         let result_two = msg_parcel.read::<CloudAsset>().unwrap();
1170         assert_eq!(result_two.uri, default_two.uri);
1171         assert_eq!(result_two.asset_name, default_two.asset_name);
1172         assert_eq!(result_two.status, default_two.status);
1173         assert_eq!(result_two.create_time, default_two.create_time);
1174         assert_eq!(result_two.modify_time, default_two.modify_time);
1175         assert_eq!(result_two.size, default_two.size);
1176         assert_eq!(result_two.sub_path, default_two.sub_path);
1177         assert_eq!(result_two.hash, default_two.hash);
1178         assert_eq!(result_two.asset_id, default_two.asset_id);
1179     }
1180 
1181     /// UT test for assets_deserialize.
1182     ///
1183     /// # Title
1184     /// ut_assets_deserialize
1185     ///
1186     /// # Brief
1187     /// 1. Create a `CloudAssets` struct.
1188     /// 2. Serialize the struct.
1189     /// 3. Read the data in `MsgParcel`.
1190     /// 4. Deserialize the data to `CloudAssets`.
1191     /// 5. Check if it is correct.
1192     #[test]
ut_assets_deserialize()1193     fn ut_assets_deserialize() {
1194         let mut assets = CloudAssets::default();
1195         let asset_one = CloudAsset::default();
1196         let asset_two = CloudAsset::default();
1197         assets.0.push(asset_one);
1198         assets.0.push(asset_two);
1199 
1200         let mut msg_parcel = MsgParcel::new();
1201         msg_parcel.write(&assets).unwrap();
1202 
1203         assert!(msg_parcel.read::<CloudAssets>().is_ok());
1204     }
1205 
1206     /// UT test for field_serialize.
1207     ///
1208     /// # Title
1209     /// ut_field_serialize
1210     ///
1211     /// # Brief
1212     /// 1. Create a `Field` enum.
1213     /// 2. Serialize the enum.
1214     /// 3. Check if it is correct.
1215     #[test]
ut_field_serialize()1216     fn ut_field_serialize() {
1217         let null = FieldRaw::Null;
1218         let number = FieldRaw::Number(1);
1219         let real = FieldRaw::Real(2.0);
1220         let text = FieldRaw::Text(String::from("text"));
1221         let boolean = FieldRaw::Bool(true);
1222         let blob = FieldRaw::Blob(vec![0]);
1223         let asset = FieldRaw::Asset(CloudAsset::default());
1224         let assets = FieldRaw::Assets(CloudAssets::default());
1225 
1226         let mut msg_parcel = MsgParcel::new();
1227         msg_parcel.write(&null).unwrap();
1228         msg_parcel.write(&number).unwrap();
1229         msg_parcel.write(&real).unwrap();
1230         msg_parcel.write(&text).unwrap();
1231         msg_parcel.write(&boolean).unwrap();
1232         msg_parcel.write(&blob).unwrap();
1233         msg_parcel.write(&asset).unwrap();
1234         msg_parcel.write(&assets).unwrap();
1235 
1236         assert_eq!(msg_parcel.read::<u32>().unwrap(), 0);
1237 
1238         assert_eq!(msg_parcel.read::<u32>().unwrap(), 1);
1239         assert_eq!(msg_parcel.read::<i64>().unwrap(), 1);
1240 
1241         assert_eq!(msg_parcel.read::<u32>().unwrap(), 2);
1242         assert_eq!(msg_parcel.read::<f64>().unwrap(), 2.0);
1243 
1244         assert_eq!(msg_parcel.read::<u32>().unwrap(), 3);
1245         assert_eq!(msg_parcel.read_string16().unwrap(), String::from("text"));
1246 
1247         assert_eq!(msg_parcel.read::<u32>().unwrap(), 4);
1248         assert!(msg_parcel.read::<bool>().unwrap());
1249 
1250         assert_eq!(msg_parcel.read::<u32>().unwrap(), 5);
1251         assert_eq!(msg_parcel.read::<Vec<u8>>().unwrap(), vec![0]);
1252 
1253         assert_eq!(msg_parcel.read::<u32>().unwrap(), 6);
1254         assert!(msg_parcel.read::<CloudAsset>().is_ok());
1255 
1256         assert_eq!(msg_parcel.read::<u32>().unwrap(), 7);
1257         assert!(msg_parcel.read::<CloudAssets>().is_ok());
1258     }
1259 
1260     /// UT test for field_deserialize.
1261     ///
1262     /// # Title
1263     /// ut_field_deserialize
1264     ///
1265     /// # Brief
1266     /// 1. Create a `Field` enum.
1267     /// 2. Serialize the enum.
1268     /// 3. Read the data in `MsgParcel`.
1269     /// 4. Deserialize the data to `Field`.
1270     /// 5. Check if it is correct.
1271     #[test]
ut_field_deserialize()1272     fn ut_field_deserialize() {
1273         let null = FieldRaw::Null;
1274         let number = FieldRaw::Number(1);
1275         let text = FieldRaw::Text(String::from("text"));
1276         let boolean = FieldRaw::Bool(true);
1277         let blob = FieldRaw::Blob(vec![0]);
1278         let asset = FieldRaw::Asset(CloudAsset::default());
1279         let assets = FieldRaw::Assets(CloudAssets::default());
1280 
1281         let mut msg_parcel = MsgParcel::new();
1282         msg_parcel.write(&null).unwrap();
1283         msg_parcel.write(&number).unwrap();
1284         msg_parcel.write(&text).unwrap();
1285         msg_parcel.write(&boolean).unwrap();
1286         msg_parcel.write(&blob).unwrap();
1287         msg_parcel.write(&asset).unwrap();
1288         msg_parcel.write(&assets).unwrap();
1289 
1290         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1291         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1292         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1293         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1294         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1295         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1296         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1297     }
1298 
1299     /// UT test for value_bucket_data_serialize.
1300     ///
1301     /// # Title
1302     /// ut_value_bucket_data_serialize
1303     ///
1304     /// # Brief
1305     /// 1. Create a `ValueBucketData` struct.
1306     /// 2. Serialize the struct.
1307     /// 3. Check if it is correct.
1308     #[test]
ut_value_bucket_data_serialize()1309     fn ut_value_bucket_data_serialize() {
1310         let mut value_bucket_data = ValueBucket::default();
1311         value_bucket_data
1312             .0
1313             .insert(String::from("key1"), FieldRaw::Null);
1314         value_bucket_data
1315             .0
1316             .insert(String::from("key2"), FieldRaw::Number(1));
1317 
1318         let mut msg_parcel = MsgParcel::new();
1319         msg_parcel.write(&value_bucket_data).unwrap();
1320 
1321         assert_eq!(msg_parcel.read::<i32>().unwrap(), 2);
1322         assert_eq!(msg_parcel.read_string16().unwrap(), String::from("key1"));
1323         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1324         assert_eq!(msg_parcel.read_string16().unwrap(), String::from("key2"));
1325         assert!(msg_parcel.read::<FieldRaw>().is_ok());
1326     }
1327 
1328     /// UT test for value_bucket_data_deserialize.
1329     ///
1330     /// # Title
1331     /// ut_value_bucket_data_deserialize
1332     ///
1333     /// # Brief
1334     /// 1. Create a `ValueBucketData` struct.
1335     /// 2. Serialize the struct.
1336     /// 3. Read the data in `MsgParcel`.
1337     /// 4. Deserialize the data to `ValueBucketData`.
1338     /// 5. Check if it is correct.
1339     #[test]
ut_value_bucket_data_deserialize()1340     fn ut_value_bucket_data_deserialize() {
1341         let mut value_bucket_data = ValueBucket::default();
1342         value_bucket_data
1343             .0
1344             .insert(String::from("key1"), FieldRaw::Null);
1345         value_bucket_data
1346             .0
1347             .insert(String::from("key2"), FieldRaw::Number(1));
1348 
1349         let mut msg_parcel = MsgParcel::new();
1350         msg_parcel.write(&value_bucket_data).unwrap();
1351 
1352         assert!(msg_parcel.read::<ValueBucket>().is_ok());
1353     }
1354 
1355     /// UT test for value_bucket_serialize.
1356     ///
1357     /// # Title
1358     /// ut_value_bucket_serialize
1359     ///
1360     /// # Brief
1361     /// 1. Create a `ValueBucket` struct.
1362     /// 2. Serialize the struct.
1363     /// 3. Check if it is correct.
1364     #[test]
ut_value_bucket_serialize()1365     fn ut_value_bucket_serialize() {
1366         let value_bucket = ValueBucket::default();
1367 
1368         let mut msg_parcel = MsgParcel::new();
1369         msg_parcel.write(&value_bucket).unwrap();
1370 
1371         assert_eq!(msg_parcel.read::<i32>().unwrap(), 0);
1372     }
1373 
1374     /// UT test for value_bucket_deserialize.
1375     ///
1376     /// # Title
1377     /// ut_value_bucket_deserialize
1378     ///
1379     /// # Brief
1380     /// 1. Create a `ValueBucket` struct.
1381     /// 2. Serialize the struct.
1382     /// 3. Read the data in `MsgParcel`.
1383     /// 4. Deserialize the data to `ValueBucket`.
1384     /// 5. Check if it is correct.
1385     #[test]
ut_value_bucket_deserialize()1386     fn ut_value_bucket_deserialize() {
1387         let value_bucket = ValueBucket::default();
1388 
1389         let mut msg_parcel = MsgParcel::new();
1390         msg_parcel.write(&value_bucket).unwrap();
1391 
1392         assert!(msg_parcel.read::<ValueBucket>().is_ok());
1393     }
1394 
1395     /// UT test for value_buckets_serialize.
1396     ///
1397     /// # Title
1398     /// ut_value_buckets_serialize
1399     ///
1400     /// # Brief
1401     /// 1. Create a `ValueBuckets` struct.
1402     /// 2. Serialize the struct.
1403     /// 3. Check if it is correct.
1404     #[test]
ut_value_buckets_serialize()1405     fn ut_value_buckets_serialize() {
1406         let mut value_buckets = ValueBuckets::default();
1407         let value_bucket_one = ValueBucket::default();
1408         let value_bucket_two = ValueBucket::default();
1409         value_buckets.0.push(value_bucket_one);
1410         value_buckets.0.push(value_bucket_two);
1411 
1412         let mut msg_parcel = MsgParcel::new();
1413         msg_parcel.write(&value_buckets).unwrap();
1414 
1415         assert_eq!(msg_parcel.read::<u32>().unwrap(), 2);
1416         for _ in 0..2 {
1417             assert!(msg_parcel.read::<ValueBucket>().is_ok());
1418         }
1419     }
1420 
1421     /// UT test for value_buckets_deserialize.
1422     ///
1423     /// # Title
1424     /// ut_value_buckets_deserialize
1425     ///
1426     /// # Brief
1427     /// 1. Create a `ValueBuckets` struct.
1428     /// 2. Serialize the struct.
1429     /// 3. Read the data in `MsgParcel`.
1430     /// 4. Deserialize the data to `ValueBuckets`.
1431     /// 5. Check if it is correct.
1432     #[test]
ut_value_buckets_deserialize()1433     fn ut_value_buckets_deserialize() {
1434         let mut value_buckets = ValueBuckets::default();
1435         let value_bucket_one = ValueBucket::default();
1436         let value_bucket_two = ValueBucket::default();
1437         value_buckets.0.push(value_bucket_one);
1438         value_buckets.0.push(value_bucket_two);
1439 
1440         let mut msg_parcel = MsgParcel::new();
1441         msg_parcel.write(&value_buckets).unwrap();
1442 
1443         assert!(msg_parcel.read::<ValueBuckets>().is_ok());
1444     }
1445 
1446     /// UT test for cloud_data_deserialize.
1447     ///
1448     /// # Title
1449     /// ut_cloud_data_deserialize
1450     ///
1451     /// # Brief
1452     /// 1. Create a `CloudData` struct.
1453     /// 2. Serialize the struct.
1454     /// 3. Read the data in `MsgParcel`.
1455     /// 4. Deserialize the data to `CloudData`.
1456     /// 5. Check if it is correct.
1457     #[test]
ut_cloud_data_deserialize()1458     fn ut_cloud_data_deserialize() {
1459         let next_cursor = String::from("");
1460         let has_more = false;
1461         let values = ValueBuckets::default();
1462 
1463         let mut msg_parcel = MsgParcel::new();
1464         msg_parcel.write_string16(&next_cursor).unwrap();
1465         msg_parcel.write(&has_more).unwrap();
1466         msg_parcel.write(&values).unwrap();
1467 
1468         assert!(msg_parcel.read::<CloudData>().is_ok());
1469     }
1470 
1471     /// UT test for database_serialize.
1472     ///
1473     /// # Title
1474     /// ut_database_serialize
1475     ///
1476     /// # Brief
1477     /// 1. Create a `Database` struct.
1478     /// 2. Serialize the struct.
1479     /// 3. Check if it is correct.
1480     #[test]
ut_database_serialize()1481     fn ut_database_serialize() {
1482         let database = Database::default();
1483 
1484         let mut msg_parcel = MsgParcel::new();
1485         msg_parcel.write(&database).unwrap();
1486 
1487         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1488         assert_eq!(msg_parcel.read_string16().unwrap(), String::from(""));
1489         assert_eq!(
1490             msg_parcel.read::<SchemaOrderTables>().unwrap(),
1491             SchemaOrderTables::default()
1492         );
1493     }
1494 
1495     /// UT test for database_deserialize.
1496     ///
1497     /// # Title
1498     /// ut_database_deserialize
1499     ///
1500     /// # Brief
1501     /// 1. Create a `Database` struct.
1502     /// 2. Serialize the struct.
1503     /// 3. Read the data in `MsgParcel`.
1504     /// 4. Deserialize the data to `Database`.
1505     /// 5. Check if it is correct.
1506     #[test]
ut_database_deserialize()1507     fn ut_database_deserialize() {
1508         let database = Database::default();
1509 
1510         let mut msg_parcel = MsgParcel::new();
1511         msg_parcel.write(&database).unwrap();
1512 
1513         assert!(msg_parcel.read::<Database>().is_ok());
1514     }
1515 
1516     /// UT test for order_table_serialize.
1517     ///
1518     /// # Title
1519     /// ut_order_table_serialize
1520     ///
1521     /// # Brief
1522     /// 1. Create a `OrderTable` struct.
1523     /// 2. Serialize the struct.
1524     /// 3. Check if it is correct.
1525     #[test]
ut_order_table_serialize()1526     fn ut_order_table_serialize() {
1527         let order_table = OrderTable::default();
1528 
1529         let mut msg_parcel = MsgParcel::new();
1530         msg_parcel.write(&order_table).unwrap();
1531 
1532         assert_eq!(msg_parcel.read_string16().unwrap(), String::default());
1533         assert_eq!(msg_parcel.read_string16().unwrap(), String::default());
1534     }
1535 
1536     /// UT test for order_table_deserialize.
1537     ///
1538     /// # Title
1539     /// ut_order_table_deserialize
1540     ///
1541     /// # Brief
1542     /// 1. Create a `OrderTable` struct.
1543     /// 2. Serialize the struct.
1544     /// 3. Read the data in `MsgParcel`.
1545     /// 4. Deserialize the data to `OrderTable`.
1546     /// 5. Check if it is correct.
1547     #[test]
ut_order_table_deserialize()1548     fn ut_order_table_deserialize() {
1549         let order_table = OrderTable::default();
1550 
1551         let mut msg_parcel = MsgParcel::new();
1552         msg_parcel.write(&order_table).unwrap();
1553 
1554         assert_eq!(msg_parcel.read::<OrderTable>().unwrap(), order_table);
1555     }
1556 
1557     /// UT test for schema_order_tables_serialize.
1558     ///
1559     /// # Title
1560     /// ut_schema_order_tables_serialize
1561     ///
1562     /// # Brief
1563     /// 1. Create a `SchemaOrderTables` struct.
1564     /// 2. Serialize the struct.
1565     /// 3. Check if it is correct.
1566     #[test]
ut_schema_order_tables_serialize()1567     fn ut_schema_order_tables_serialize() {
1568         let mut schema_order_tables = SchemaOrderTables::default();
1569         let order_table_one = OrderTable::default();
1570         let order_table_two = OrderTable::default();
1571         schema_order_tables.0.push(order_table_one);
1572         schema_order_tables.0.push(order_table_two);
1573 
1574         let mut msg_parcel = MsgParcel::new();
1575         msg_parcel.write(&schema_order_tables).unwrap();
1576 
1577         assert_eq!(msg_parcel.read::<i32>().unwrap(), 2);
1578         assert_eq!(
1579             msg_parcel.read::<OrderTable>().unwrap(),
1580             OrderTable::default()
1581         );
1582         assert_eq!(
1583             msg_parcel.read::<OrderTable>().unwrap(),
1584             OrderTable::default()
1585         );
1586     }
1587 
1588     /// UT test for schema_order_tables_deserialize.
1589     ///
1590     /// # Title
1591     /// ut_schema_order_tables_deserialize
1592     ///
1593     /// # Brief
1594     /// 1. Create a `SchemaOrderTables` struct.
1595     /// 2. Serialize the struct.
1596     /// 3. Read the data in `MsgParcel`.
1597     /// 4. Deserialize the data to `SchemaOrderTables`.
1598     /// 5. Check if it is correct.
1599     #[test]
ut_schema_order_tables_deserialize()1600     fn ut_schema_order_tables_deserialize() {
1601         let mut schema_order_tables = SchemaOrderTables::default();
1602         let order_table_one = OrderTable::default();
1603         let order_table_two = OrderTable::default();
1604         schema_order_tables.0.push(order_table_one);
1605         schema_order_tables.0.push(order_table_two);
1606 
1607         let mut msg_parcel = MsgParcel::new();
1608         msg_parcel.write(&schema_order_tables).unwrap();
1609 
1610         assert_eq!(
1611             msg_parcel.read::<SchemaOrderTables>().unwrap(),
1612             schema_order_tables
1613         );
1614     }
1615 
1616     /// UT test for databases_serialize.
1617     ///
1618     /// # Title
1619     /// ut_databases_serialize
1620     ///
1621     /// # Brief
1622     /// 1. Create a `Databases` struct.
1623     /// 2. Serialize the struct.
1624     /// 3. Check if it is correct.
1625     #[test]
ut_databases_serialize()1626     fn ut_databases_serialize() {
1627         let mut databases = Databases::default();
1628         let database_one = Database::default();
1629         let database_two = Database::default();
1630         databases.0.push(database_one);
1631         databases.0.push(database_two);
1632 
1633         let mut msg_parcel = MsgParcel::new();
1634         msg_parcel.write(&databases).unwrap();
1635 
1636         assert_eq!(msg_parcel.read::<i32>().unwrap(), 2);
1637         assert!(msg_parcel.read::<Database>().is_ok());
1638         assert!(msg_parcel.read::<Database>().is_ok());
1639     }
1640 
1641     /// UT test for databases_deserialize.
1642     ///
1643     /// # Title
1644     /// ut_databases_deserialize
1645     ///
1646     /// # Brief
1647     /// 1. Create a `Databases` struct.
1648     /// 2. Serialize the struct.
1649     /// 3. Read the data in `MsgParcel`.
1650     /// 4. Deserialize the data to `Databases`.
1651     /// 5. Check if it is correct.
1652     #[test]
ut_databases_deserialize()1653     fn ut_databases_deserialize() {
1654         let mut databases = Databases::default();
1655         let database_one = Database::default();
1656         let database_two = Database::default();
1657         databases.0.push(database_one);
1658         databases.0.push(database_two);
1659 
1660         let mut msg_parcel = MsgParcel::new();
1661         msg_parcel.write(&databases).unwrap();
1662 
1663         assert!(msg_parcel.read::<Databases>().is_ok());
1664     }
1665 
1666     /// UT test for schema_deserialize.
1667     ///
1668     /// # Title
1669     /// ut_schema_deserialize
1670     ///
1671     /// # Brief
1672     /// 1. Create a `Schema` struct.
1673     /// 2. Serialize the struct.
1674     /// 3. Read the data in `MsgParcel`.
1675     /// 4. Deserialize the data to `Schema`.
1676     /// 5. Check if it is correct.
1677     #[test]
ut_schema_deserialize()1678     fn ut_schema_deserialize() {
1679         let mut msg_parcel = MsgParcel::new();
1680         msg_parcel.write(&0_i32).unwrap();
1681         msg_parcel.write_string16("").unwrap();
1682         msg_parcel.write(&Databases::default()).unwrap();
1683 
1684         assert!(msg_parcel.read::<Schema>().is_ok());
1685     }
1686 
1687     /// UT test for app_info_deserialize.
1688     ///
1689     /// # Title
1690     /// ut_app_info_deserialize
1691     ///
1692     /// # Brief
1693     /// 1. Create a `AppInfo` struct.
1694     /// 2. Serialize the struct.
1695     /// 3. Read the data in `MsgParcel`.
1696     /// 4. Deserialize the data to `AppInfo`.
1697     /// 5. Check if it is correct.
1698     #[test]
ut_app_info_deserialize()1699     fn ut_app_info_deserialize() {
1700         let app_info = AppInfo::default();
1701 
1702         let mut msg_parcel = MsgParcel::new();
1703         msg_parcel.write_string16("").unwrap();
1704         msg_parcel.write_string16("").unwrap();
1705         msg_parcel.write(&bool::default()).unwrap();
1706         msg_parcel.write(&0_i32).unwrap();
1707         msg_parcel.write(&0_i32).unwrap();
1708 
1709         assert_eq!(msg_parcel.read::<AppInfo>().unwrap(), app_info);
1710     }
1711 
1712     /// UT test for subscription_result_value_deserialize.
1713     ///
1714     /// # Title
1715     /// ut_subscription_result_value_deserialize
1716     ///
1717     /// # Brief
1718     /// 1. Create a `SubscriptionResultValue` struct.
1719     /// 2. Serialize the struct.
1720     /// 3. Read the data in `MsgParcel`.
1721     /// 4. Deserialize the data to `SubscriptionResultValue`.
1722     /// 5. Check if it is correct.
1723     #[test]
ut_subscription_result_value_deserialize()1724     fn ut_subscription_result_value_deserialize() {
1725         let mut subscription = SubscriptionResultValue::default();
1726         subscription
1727             .0
1728             .push((String::from("test1"), String::from("2")));
1729 
1730         let mut msg_parcel = MsgParcel::new();
1731         msg_parcel.write(&1_i32).unwrap();
1732         msg_parcel.write_string16(&String::from("test1")).unwrap();
1733         msg_parcel.write_string16(&String::from("2")).unwrap();
1734 
1735         assert_eq!(
1736             msg_parcel.read::<SubscriptionResultValue>().unwrap(),
1737             subscription
1738         );
1739     }
1740 }
1741