aliyun-oss-client 0.12.7

an aliyun oss client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
//! # Object 相关功能
//! `ObjectList` 对应文件列表,`Object` 对应的是单个文件对象
//!
//! `ObjectList` 也可以支持自定义的类型存储单个文件对象,例如 [issue 12](https://github.com/tu6ge/oss-rs/issues/12) 提到的,有些时候,
//! Oss 接口不仅返回文件路径,还会返回目录路径,可以使用如下例子进行适配
//!
//! ```rust,no_run
//! use aliyun_oss_client::{
//!     decode::RefineObject,
//!     object::Objects,
//!     types::object::{InvalidObjectDir, ObjectDir, ObjectPath},
//!     BucketName, Client,
//! };
//! use dotenv::dotenv;
//!
//! #[derive(Debug)]
//! enum MyObject {
//!     File(ObjectPath),
//!     Dir(ObjectDir<'static>),
//! }
//!
//! impl RefineObject<MyError> for MyObject {
//!     fn set_key(&mut self, key: &str) -> Result<(), MyError> {
//!         let res = key.parse::<ObjectPath>();
//!
//!         *self = match res {
//!             Ok(file) => MyObject::File(file),
//!             _ => {
//!                 let re = key.parse::<ObjectDir>();
//!                 MyObject::Dir(re.unwrap())
//!             }
//!         };
//!
//!         Ok(())
//!     }
//! }
//!
//! #[derive(Debug)]
//! struct MyError(String);
//!
//! use std::fmt::{self, Display};
//!
//! impl Display for MyError {
//!     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//!         f.write_fmt(format_args!("{}", self.0))
//!     }
//! }
//! impl std::error::Error for MyError {}
//!
//! impl From<InvalidObjectDir> for MyError {
//!     fn from(value: InvalidObjectDir) -> Self {
//!         Self(value.to_string())
//!     }
//! }
//!
//! type MyList = Objects<MyObject, MyError>;
//!
//! #[tokio::main]
//! async fn main() {
//!     dotenv().ok();
//!
//!     let client = Client::from_env().unwrap();
//!
//!     let mut list = MyList::default();
//!
//!     let init_object = || MyObject::File(ObjectPath::default());
//!
//!     let _ = client
//!         .base_object_list(
//!             "xxxxxx".parse::<BucketName>().unwrap(),
//!             [],
//!             &mut list,
//!             init_object,
//!         )
//!         .await;
//!
//!     println!("list: {:?}", list.to_vec());
//! }
//! ```

use crate::bucket::Bucket;
#[cfg(feature = "blocking")]
use crate::builder::RcPointer;
use crate::builder::{ArcPointer, BuilderError, PointerFamily};
use crate::client::ClientArc;
#[cfg(feature = "blocking")]
use crate::client::ClientRc;
use crate::config::{get_url_resource_with_bucket, BucketBase};
use crate::decode::{InnerListError, ListError, RefineObject, RefineObjectList};
#[cfg(feature = "blocking")]
use crate::file::blocking::AlignBuilder as BlockingAlignBuilder;
use crate::file::AlignBuilder;
use crate::types::object::ObjectPathInner;
use crate::types::{
    core::SetOssQuery,
    object::{
        CommonPrefixes, InvalidObjectDir, InvalidObjectPath, ObjectBase, ObjectDir, ObjectPath,
    },
    CanonicalizedResource, Query, QueryKey, QueryValue, CONTINUATION_TOKEN,
};
use crate::{BucketName, Client, EndPoint, KeyId, KeySecret};
use async_stream::try_stream;
use chrono::{DateTime, NaiveDateTime, Utc};
use futures_core::stream::Stream;
use http::Method;
use oss_derive::oss_gen_rc;
use url::Url;

#[cfg(feature = "blocking")]
use std::rc::Rc;
use std::{
    error::Error,
    fmt::{self, Display},
    marker::PhantomData,
    num::ParseIntError,
    slice::{Iter, IterMut},
    sync::Arc,
    vec::IntoIter,
};

#[cfg(test)]
mod test;

/// # 存放对象列表的结构体
/// before name is `ObjectList`
/// TODO impl core::ops::Index
#[derive(Clone)]
#[non_exhaustive]
pub struct ObjectList<
    P: PointerFamily = ArcPointer,
    Item: RefineObject<E> = Object<P>,
    E: Error + 'static = BuildInItemError,
> {
    pub(crate) bucket: BucketBase,
    prefix: Option<ObjectDir<'static>>,
    max_keys: u32,
    key_count: u64,
    /// 存放单个文件对象的 Vec 集合
    object_list: Vec<Item>,
    next_continuation_token: String,
    common_prefixes: CommonPrefixes,
    client: P::PointerType,
    search_query: Query,
    ph_err: PhantomData<E>,
}

/// sync ObjectList alias
pub type Objects<Item = Object<ArcPointer>, Error = BuildInItemError> =
    ObjectList<ArcPointer, Item, Error>;
/// blocking ObjectList alias
#[cfg(feature = "blocking")]
pub type ObjectsBlocking<Item = Object<RcPointer>, Error = BuildInItemError> =
    ObjectList<RcPointer, Item, Error>;

/// 存放单个对象的结构体
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Object<PointerSel: PointerFamily = ArcPointer> {
    pub(crate) base: ObjectBase<PointerSel>,
    last_modified: DateTime<Utc>,
    etag: String,
    _type: String,
    size: u64,
    storage_class: StorageClass,
}

/// 异步的 Object struct
pub type ObjectArc = Object<ArcPointer>;

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> fmt::Debug for ObjectList<T, Item, E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ObjectList")
            .field("bucket", &self.bucket)
            .field("prefix", &self.prefix)
            .field("max_keys", &self.max_keys)
            .field("key_count", &self.key_count)
            .field("next_continuation_token", &self.next_continuation_token)
            .field("common_prefixes", &self.common_prefixes)
            .field("search_query", &self.search_query)
            .finish()
    }
}

#[oss_gen_rc]
impl<Item: RefineObject<E>, E: Error> Default for ObjectList<ArcPointer, Item, E> {
    fn default() -> Self {
        Self {
            bucket: BucketBase::default(),
            prefix: Option::default(),
            max_keys: u32::default(),
            key_count: u64::default(),
            object_list: Vec::new(),
            next_continuation_token: String::default(),
            common_prefixes: CommonPrefixes::default(),
            client: Arc::new(ClientArc::default()),
            search_query: Query::default(),
            ph_err: PhantomData,
        }
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> AsMut<Query> for ObjectList<T, Item, E> {
    fn as_mut(&mut self) -> &mut Query {
        &mut self.search_query
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> AsRef<BucketBase>
    for ObjectList<T, Item, E>
{
    fn as_ref(&self) -> &BucketBase {
        &self.bucket
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> AsRef<BucketName>
    for ObjectList<T, Item, E>
{
    fn as_ref(&self) -> &BucketName {
        self.bucket.as_ref()
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> AsRef<EndPoint> for ObjectList<T, Item, E> {
    fn as_ref(&self) -> &EndPoint {
        self.bucket.as_ref()
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error> ObjectList<T, Item, E> {
    /// 文件列表的初始化方法
    #[allow(clippy::too_many_arguments)]
    pub fn new<Q: IntoIterator<Item = (QueryKey, QueryValue)>>(
        bucket: BucketBase,
        prefix: Option<ObjectDir<'static>>,
        max_keys: u32,
        key_count: u64,
        object_list: Vec<Item>,
        next_continuation_token: Option<String>,
        client: T::PointerType,
        search_query: Q,
    ) -> Self {
        Self {
            bucket,
            prefix,
            max_keys,
            key_count,
            object_list,
            next_continuation_token: next_continuation_token.unwrap_or_default(),
            common_prefixes: CommonPrefixes::default(),
            client,
            search_query: Query::from_iter(search_query),
            ph_err: PhantomData,
        }
    }

    /// 返回 bucket 元信息的引用
    pub fn bucket(&self) -> &BucketBase {
        &self.bucket
    }

    /// 返回 prefix 的引用
    pub fn prefix(&self) -> &Option<ObjectDir<'static>> {
        &self.prefix
    }

    /// 获取文件夹下的子文件夹名,子文件夹下递归的所有文件和文件夹不包含在这里。
    pub fn common_prefixes(&self) -> &CommonPrefixes {
        &self.common_prefixes
    }

    /// 设置 common_prefixes 信息
    pub fn set_common_prefixes<P: IntoIterator<Item = ObjectDir<'static>>>(&mut self, prefixes: P) {
        self.common_prefixes = CommonPrefixes::from_iter(prefixes);
    }

    /// 返回 max_keys
    pub fn max_keys(&self) -> &u32 {
        &self.max_keys
    }

    /// 返回 key_count
    pub fn key_count(&self) -> &u64 {
        &self.key_count
    }

    /// # 返回下一个 continuation_token
    /// 用于翻页使用
    pub fn next_continuation_token_str(&self) -> &String {
        &self.next_continuation_token
    }

    /// 返回查询条件
    pub fn search_query(&self) -> &Query {
        &self.search_query
    }

    /// # 下一页的查询条件
    ///
    /// 如果有下一页,返回 Some(Query)
    /// 如果没有下一页,则返回 None
    pub fn next_query(&self) -> Option<Query> {
        if !self.next_continuation_token.is_empty() {
            let mut search_query = self.search_query.clone();
            search_query.insert(CONTINUATION_TOKEN, self.next_continuation_token.to_owned());
            Some(search_query)
        } else {
            None
        }
    }

    /// 将 object 列表转化实现了 `IntoIter` Trait的外部类型
    pub fn object_iter(self) -> IntoIter<Item> {
        self.object_list.into_iter()
    }

    /// 将 object 列表转化实现了 `IntoIter` Trait的外部类型
    pub fn object_into_iter(self) -> IntoIter<Item> {
        self.object_list.into_iter()
    }

    /// 返回 object 列表迭代器
    pub fn object_iter2(&self) -> Iter<Item> {
        self.object_list.iter()
    }

    /// 将 object 列表转化为迭代器的可变引用
    pub fn object_iter_mut(&mut self) -> IterMut<Item> {
        self.object_list.iter_mut()
    }
}

#[oss_gen_rc]
impl<Item: RefineObject<E>, E: Error> ObjectList<ArcPointer, Item, E> {
    /// 设置 Client
    pub(crate) fn set_client(&mut self, client: Arc<ClientArc>) {
        self.client = client;
    }

    pub(crate) fn from_bucket(
        bucket: &Bucket<ArcPointer>,
        capacity: usize,
    ) -> ObjectList<ArcPointer> {
        ObjectList::<ArcPointer> {
            bucket: bucket.base.clone(),
            client: Arc::clone(&bucket.client),
            object_list: Vec::with_capacity(capacity),
            ..Default::default()
        }
    }

    /// 获取 Client 引用
    pub(crate) fn client(&self) -> Arc<ClientArc> {
        Arc::clone(&self.client)
    }
}

impl ObjectList<ArcPointer> {
    /// 异步获取下一页的数据
    pub async fn get_next_list(&self) -> Result<ObjectList<ArcPointer>, ExtractListError> {
        match self.next_query() {
            None => Err(ExtractListError {
                kind: ExtractListErrorKind::NoMoreFile,
            }),
            Some(query) => {
                let mut url = self.bucket.to_url();
                url.set_oss_query(&query);

                let canonicalized = CanonicalizedResource::from_bucket_query(&self.bucket, &query);

                let response = self
                    .builder(Method::GET, url, canonicalized)?
                    .send_adjust_error()
                    .await?;

                let mut list = ObjectList::<ArcPointer> {
                    client: self.client(),
                    bucket: self.bucket.clone(),
                    object_list: Vec::with_capacity(query.get_max_keys()),
                    ..Default::default()
                };

                list.decode(&response.text().await?, || {
                    Object::from_bucket(Arc::new(self.bucket.clone()))
                })?;

                list.set_search_query(query);
                Ok(list)
            }
        }
    }

    /// # 将 object_list 转化为 stream, 返回第二页,第三页... 的内容
    ///
    /// *不够完善,最后一次迭代返回的是 `Some(Err(OssError::WithoutMore))`,而不是 `None`*
    ///
    /// ## 用法
    ///
    /// 1. 添加依赖
    /// ```toml
    /// [dependencies]
    /// futures="0.3"
    /// ```
    /// 2. 将返回结果 pin 住
    /// ```no_run
    /// # use dotenv::dotenv;
    /// # use aliyun_oss_client::Client;
    /// # #[tokio::main]
    /// # async fn main() {
    /// # dotenv().ok();
    /// use futures::{pin_mut, StreamExt};
    /// # let client = Client::from_env().unwrap();
    /// # let query = [("max-keys".into(), 100u8.into())];
    /// # let object_list = client.get_object_list(query).await.unwrap();
    /// let stream = object_list.into_stream();
    /// pin_mut!(stream);
    ///
    /// let second_list = stream.next().await;
    /// let third_list = stream.next().await;
    /// println!("second_list: {:?}", second_list);
    /// println!("third_list: {:?}", third_list);
    /// # }
    /// ```
    pub fn into_stream(self) -> impl Stream<Item = Result<Self, ExtractListError>> {
        try_stream! {
            let result = self.get_next_list().await?;
            yield result;
        }
    }
}

impl<Item: RefineObject<E>, E: Error + 'static> ObjectList<ArcPointer, Item, E> {
    /// 自定义 Item 时,获取下一页数据
    pub async fn get_next_base<F>(&self, init_object: F) -> Result<Self, ExtractListError>
    where
        F: FnMut() -> Item,
    {
        match self.next_query() {
            None => Err(ExtractListError {
                kind: ExtractListErrorKind::NoMoreFile,
            }),
            Some(query) => {
                let mut list = Self::default();
                let name = self.bucket.get_name().clone();
                self.client()
                    .base_object_list(name, query, &mut list, init_object)
                    .await?;

                Ok(list)
            }
        }
    }
}

#[cfg(feature = "blocking")]
impl ObjectList<RcPointer> {
    fn clone_base(&self) -> Self {
        Self {
            client: Rc::clone(&self.client),
            bucket: self.bucket.clone(),
            search_query: self.search_query.clone(),
            max_keys: self.max_keys,
            object_list: Vec::with_capacity(self.max_keys as usize),
            ..Default::default()
        }
    }
    /// 从 OSS 获取 object 列表信息
    pub fn get_object_list(&mut self) -> Result<Self, ExtractListError> {
        let name = self.bucket.get_name();

        let client = self.client();

        let mut list = ObjectList::<RcPointer>::clone_base(self);

        let init_object = || Object::<RcPointer>::from_bucket(Rc::new(self.bucket.clone()));

        client
            .base_object_list(
                name.to_owned(),
                self.search_query.clone(),
                &mut list,
                init_object,
            )
            .map_err(ExtractListError::from)?;

        Ok(list)
    }
}

impl<T: PointerFamily, Item: RefineObject<E>, E: Error + 'static> ObjectList<T, Item, E> {
    /// 设置查询条件
    #[inline]
    pub fn set_search_query(&mut self, search_query: Query) {
        self.search_query = search_query;
    }

    /// 设置 bucket 元信息
    pub fn set_bucket(&mut self, bucket: BucketBase) {
        self.bucket = bucket;
    }

    /// 获取 bucket 名称
    pub fn bucket_name(&self) -> &str {
        self.bucket.name()
    }

    /// 返回 object 的 Vec 集合
    pub fn to_vec(self) -> Vec<Item> {
        self.object_list
    }

    /// 返回文件数量
    pub fn len(&self) -> usize {
        self.object_list.len()
    }

    /// 返回是否存在文件
    pub fn is_empty(&self) -> bool {
        self.object_list.is_empty()
    }
}

impl<T: PointerFamily> Default for Object<T> {
    fn default() -> Self {
        Object {
            base: ObjectBase::<T>::default(),
            last_modified: DateTime::<Utc>::from_utc(
                #[allow(clippy::unwrap_used)]
                NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
                Utc,
            ),
            etag: String::default(),
            _type: String::default(),
            size: 0,
            storage_class: StorageClass::default(),
        }
    }
}

impl<T: PointerFamily> AsRef<ObjectPath> for Object<T> {
    fn as_ref(&self) -> &ObjectPath {
        self.base.as_ref()
    }
}

impl<T: PointerFamily> AsRef<DateTime<Utc>> for Object<T> {
    fn as_ref(&self) -> &DateTime<Utc> {
        &self.last_modified
    }
}

impl<T: PointerFamily> AsRef<StorageClass> for Object<T> {
    fn as_ref(&self) -> &StorageClass {
        &self.storage_class
    }
}

impl<T: PointerFamily> Object<T> {
    /// 初始化 Object 结构体
    pub fn new(
        bucket: T::Bucket,
        path: ObjectPath,
        last_modified: DateTime<Utc>,
        etag: String,
        _type: String,
        size: u64,
        storage_class: StorageClass,
    ) -> Self {
        let base = ObjectBase::<T>::new2(bucket, path);
        Self {
            base,
            last_modified,
            etag,
            _type,
            size,
            storage_class,
        }
    }

    pub(crate) fn from_bucket(bucket: T::Bucket) -> Self {
        Self {
            base: ObjectBase::<T>::init_with_bucket(bucket),
            ..Default::default()
        }
    }

    /// 读取 Object 元信息
    #[inline]
    pub fn base(&self) -> &ObjectBase<T> {
        &self.base
    }

    /// 设置 Object 元信息
    #[inline]
    pub fn set_base(&mut self, base: ObjectBase<T>) {
        self.base = base;
    }

    /// 读取最后修改时间
    #[inline]
    pub fn last_modified(&self) -> &DateTime<Utc> {
        &self.last_modified
    }

    /// 设置最后修改时间
    #[inline]
    pub fn set_last_modified(&mut self, last_modified: DateTime<Utc>) {
        self.last_modified = last_modified;
    }

    /// 读取 etag 信息
    #[inline]
    pub fn etag(&self) -> &String {
        &self.etag
    }

    /// 设置 etag
    #[inline]
    pub fn set_etag(&mut self, etag: String) {
        self.etag = etag
    }

    /// 读取 type
    #[inline]
    pub fn get_type_string(&self) -> &String {
        &self._type
    }

    /// 设置 type
    #[inline]
    pub fn set_type_string(&mut self, _type: String) {
        self._type = _type;
    }

    /// 读取文件 size
    #[inline]
    pub fn size(&self) -> u64 {
        self.size
    }

    /// 设置文件 size
    #[inline]
    pub fn set_size(&mut self, size: u64) {
        self.size = size;
    }

    /// 读取 storage_class
    #[inline]
    pub fn storage_class(&self) -> &StorageClass {
        &self.storage_class
    }

    /// 设置 storage_class
    #[inline]
    pub fn set_storage_class(&mut self, storage_class: StorageClass) {
        self.storage_class = storage_class;
    }

    /// 获取一部分数据
    pub fn pieces(
        self,
    ) -> (
        ObjectBase<T>,
        DateTime<Utc>,
        String,
        String,
        u64,
        StorageClass,
    ) {
        (
            self.base,
            self.last_modified,
            self.etag,
            self._type,
            self.size,
            self.storage_class,
        )
    }

    /// 读取 文件路径
    pub fn path(&self) -> ObjectPath {
        self.base.path()
    }

    #[doc(hidden)]
    pub fn path_string(&self) -> String {
        self.base.path().to_string()
    }
}

impl Object<ArcPointer> {
    #[cfg(test)]
    pub fn test_path(path: &'static str) -> Self {
        let mut object = Self::default();
        object.set_base(ObjectBase::<ArcPointer>::new2(
            Arc::new(BucketBase::default()),
            path.try_into().unwrap(),
        ));
        object
    }
}

impl<T: PointerFamily> From<Object<T>> for ObjectPathInner<'static> {
    #[inline]
    fn from(obj: Object<T>) -> Self {
        obj.base.path
    }
}

#[oss_gen_rc]
impl Object<ArcPointer> {
    /// # Object 构建器
    /// 用例
    /// ```
    /// # use aliyun_oss_client::{config::BucketBase, ObjectPath, object::{ObjectArc, StorageClass},EndPoint};
    /// # use chrono::{DateTime, NaiveDateTime, Utc};
    /// let bucket = BucketBase::new(
    ///     "bucket-name".parse().unwrap(),
    ///     EndPoint::CN_QINGDAO,
    /// );
    /// let mut builder = ObjectArc::builder("abc".parse::<ObjectPath>().unwrap());
    ///
    /// builder
    ///     .bucket_base(bucket)
    ///     .last_modified(DateTime::<Utc>::from_utc(
    ///         NaiveDateTime::from_timestamp_opt(123000, 0).unwrap(),
    ///         Utc,
    ///     ))
    ///     .etag("foo1".to_owned())
    ///     .set_type("foo2".to_owned())
    ///     .size(123)
    ///     .storage_class(StorageClass::IA);
    ///
    /// let object = builder.build();
    /// ```
    pub fn builder(path: ObjectPath) -> ObjectBuilder<ArcPointer> {
        ObjectBuilder::<ArcPointer>::new(Arc::default(), path)
    }

    /// 带签名的 Url 链接
    pub fn to_sign_url(&self, key: &KeyId, secret: &KeySecret, expires: i64) -> Url {
        self.base.to_sign_url(key, secret, expires)
    }
}

/// Object 结构体的构建器
pub struct ObjectBuilder<T: PointerFamily = ArcPointer> {
    object: Object<T>,
}

impl<T: PointerFamily> ObjectBuilder<T> {
    /// 初始化 Object 构建器
    pub fn new(bucket: T::Bucket, path: ObjectPath) -> Self {
        let base = ObjectBase::<T>::new2(bucket, path);
        Self {
            object: Object {
                base,
                last_modified: DateTime::<Utc>::from_utc(
                    #[allow(clippy::unwrap_used)]
                    NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
                    Utc,
                ),
                etag: String::default(),
                _type: String::default(),
                size: 0,
                storage_class: StorageClass::default(),
            },
        }
    }

    /// 设置元信息
    pub fn bucket(&mut self, bucket: T::Bucket) -> &mut Self {
        self.object.base.set_bucket(bucket);
        self
    }

    /// 设置 last_modified
    pub fn last_modified(&mut self, date: DateTime<Utc>) -> &mut Self {
        self.object.last_modified = date;
        self
    }

    /// 设置 etag
    pub fn etag(&mut self, etag: String) -> &mut Self {
        self.object.etag = etag;
        self
    }

    /// 设置 type
    pub fn set_type(&mut self, _type: String) -> &mut Self {
        self.object._type = _type;
        self
    }

    /// 设置 size
    pub fn size(&mut self, size: u64) -> &mut Self {
        self.object.size = size;
        self
    }

    /// 设置 storage_class
    pub fn storage_class(&mut self, storage_class: StorageClass) -> &mut Self {
        self.object.storage_class = storage_class;
        self
    }

    /// 返回 object
    pub fn build(self) -> Object<T> {
        self.object
    }
}

#[oss_gen_rc]
impl ObjectBuilder<ArcPointer> {
    /// 设置元信息
    pub fn bucket_base(&mut self, base: BucketBase) -> &mut Self {
        self.object.base.set_bucket(Arc::new(base));
        self
    }
}

impl<T: PointerFamily + Sized> RefineObject<BuildInItemError> for Object<T> {
    #[inline]
    fn set_key(&mut self, key: &str) -> Result<(), BuildInItemError> {
        self.base
            .set_path(key.to_owned())
            .map_err(|e| BuildInItemError {
                source: key.to_string(),
                kind: BuildInItemErrorKind::BasePath(e),
            })
    }

    #[inline]
    fn set_last_modified(&mut self, value: &str) -> Result<(), BuildInItemError> {
        self.last_modified = value.parse().map_err(|e| BuildInItemError {
            source: value.to_string(),
            kind: BuildInItemErrorKind::LastModified(e),
        })?;
        Ok(())
    }

    #[inline]
    fn set_etag(&mut self, value: &str) -> Result<(), BuildInItemError> {
        self.etag = value.to_string();
        Ok(())
    }

    #[inline]
    fn set_type(&mut self, value: &str) -> Result<(), BuildInItemError> {
        self._type = value.to_string();
        Ok(())
    }

    #[inline]
    fn set_size(&mut self, size: &str) -> Result<(), BuildInItemError> {
        self.size = size.parse().map_err(|e| BuildInItemError {
            source: size.to_string(),
            kind: BuildInItemErrorKind::Size(e),
        })?;
        Ok(())
    }

    #[inline]
    fn set_storage_class(&mut self, storage_class: &str) -> Result<(), BuildInItemError> {
        self.storage_class = StorageClass::new(storage_class).ok_or(BuildInItemError {
            source: storage_class.to_string(),
            kind: BuildInItemErrorKind::InvalidStorageClass,
        })?;
        Ok(())
    }
}

/// Xml 转化为内置 Object 时的错误集合
#[derive(Debug)]
#[non_exhaustive]
pub struct BuildInItemError {
    source: String,
    kind: BuildInItemErrorKind,
}

impl BuildInItemError {
    #[cfg(test)]
    pub(crate) fn test_new() -> Self {
        Self {
            source: "foo".to_string(),
            kind: BuildInItemErrorKind::InvalidStorageClass,
        }
    }
}

impl Display for BuildInItemError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use BuildInItemErrorKind::*;
        let kind = match &self.kind {
            Size(_) => "size",
            BasePath(_) => "base-path",
            LastModified(_) => "last-modified",
            InvalidStorageClass => "storage-class",
        };
        write!(f, "parse {kind} failed, gived str: {}", self.source)
    }
}

impl Error for BuildInItemError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use BuildInItemErrorKind::*;
        match &self.kind {
            Size(e) => Some(e),
            BasePath(e) => Some(e),
            LastModified(e) => Some(e),
            InvalidStorageClass => None,
        }
    }
}

/// Xml 转化为内置 Object 时的错误集合
#[derive(Debug)]
#[non_exhaustive]
enum BuildInItemErrorKind {
    /// 转换数字类型的错误
    Size(ParseIntError),

    /// 转换为 ObjectPath 时的错误
    BasePath(InvalidObjectPath),

    /// 转换日期格式的错误
    LastModified(chrono::ParseError),

    // /// 接收 Xml 转换时的错误
    // Xml(quick_xml::Error),
    /// 非法的 StorageClass
    InvalidStorageClass,
}

impl<P: PointerFamily, Item: RefineObject<E>, E: Error + 'static>
    RefineObjectList<Item, ObjectListError, E> for ObjectList<P, Item, E>
{
    #[inline]
    fn set_key_count(&mut self, key_count: &str) -> Result<(), ObjectListError> {
        self.key_count = key_count.parse().map_err(|e| ObjectListError {
            source: key_count.to_owned(),
            kind: ObjectListErrorKind::KeyCount(e),
        })?;
        Ok(())
    }

    #[inline]
    fn set_prefix(&mut self, prefix: &str) -> Result<(), ObjectListError> {
        if prefix.is_empty() {
            self.prefix = None;
        } else {
            let mut string = String::from(prefix);
            string += "/";
            self.prefix = Some(string.parse().map_err(|e| ObjectListError {
                source: prefix.to_owned(),
                kind: ObjectListErrorKind::Prefix(e),
            })?)
        }
        Ok(())
    }

    #[inline]
    fn set_common_prefix(
        &mut self,
        list: &[std::borrow::Cow<'_, str>],
    ) -> Result<(), ObjectListError> {
        for val in list.iter() {
            self.common_prefixes
                .push(val.parse().map_err(|e| ObjectListError {
                    source: val.to_string(),
                    kind: ObjectListErrorKind::CommonPrefix(e),
                })?);
        }
        Ok(())
    }

    #[inline]
    fn set_max_keys(&mut self, max_keys: &str) -> Result<(), ObjectListError> {
        self.max_keys = max_keys.parse().map_err(|e| ObjectListError {
            source: max_keys.to_string(),
            kind: ObjectListErrorKind::MaxKeys(e),
        })?;
        Ok(())
    }

    #[inline]
    fn set_next_continuation_token_str(&mut self, token: &str) -> Result<(), ObjectListError> {
        self.next_continuation_token = token.to_owned();
        Ok(())
    }

    #[inline]
    fn set_list(&mut self, list: Vec<Item>) -> Result<(), ObjectListError> {
        self.object_list = list;
        Ok(())
    }
}

/// decode xml to object list error collection
#[derive(Debug)]
#[non_exhaustive]
pub struct ObjectListError {
    source: String,
    kind: ObjectListErrorKind,
}

impl ObjectListError {
    #[cfg(test)]
    pub(crate) fn test_new() -> Self {
        Self {
            source: "foo".to_string(),
            kind: ObjectListErrorKind::Bar,
        }
    }
}

impl Display for ObjectListError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ObjectListErrorKind::*;
        let kind: &str = match &self.kind {
            KeyCount(_) => "key-count",
            Prefix(_) => "prefix",
            CommonPrefix(_) => "common-prefix",
            MaxKeys(_) => "max-keys",
            #[cfg(test)]
            Bar => "bar",
        };
        write!(f, "parse {kind} failed, gived str: {}", self.source)
    }
}

impl Error for ObjectListError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use ObjectListErrorKind::*;
        match &self.kind {
            KeyCount(e) | MaxKeys(e) => Some(e),
            Prefix(e) | CommonPrefix(e) => Some(e),
            #[cfg(test)]
            Bar => None,
        }
    }
}

impl ListError for ObjectListError {}

/// decode xml to object list error collection
#[derive(Debug)]
#[non_exhaustive]
enum ObjectListErrorKind {
    /// when covert key_count failed ,return this error
    KeyCount(ParseIntError),
    /// when covert prefix failed ,return this error
    Prefix(InvalidObjectDir),
    /// when covert common_prefix failed ,return this error
    CommonPrefix(InvalidObjectDir),
    /// when covert max_keys failed ,return this error
    MaxKeys(ParseIntError),
    #[cfg(test)]
    Bar,
}

impl Client {
    /// 查询默认 bucket 的文件列表
    ///
    /// 查询条件参数有多种方式,具体参考 [`get_object_list`] 文档
    ///
    /// [`get_object_list`]: crate::bucket::Bucket::get_object_list
    #[inline(always)]
    pub async fn get_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>>(
        &self,
        query: Q,
    ) -> Result<ObjectList, ExtractListError> {
        self.get_object_list2(Query::from_iter(query)).await
    }

    /// 查询默认 bucket 的文件列表
    pub async fn get_object_list2(&self, query: Query) -> Result<ObjectList, ExtractListError> {
        let bucket = BucketBase::new(self.bucket.to_owned(), self.endpoint.to_owned());

        let (bucket_url, resource) = bucket.get_url_resource(&query);
        let bucket_arc = Arc::new(bucket.clone());

        let mut list = ObjectList::<ArcPointer> {
            object_list: Vec::with_capacity(query.get_max_keys()),
            bucket,
            ..Default::default()
        };

        let response = self.builder(Method::GET, bucket_url, resource)?;
        let content = response.send_adjust_error().await?;

        list.decode(&content.text().await?, || {
            Object::from_bucket(bucket_arc.clone())
        })?;

        list.set_client(Arc::new(self.clone()));
        list.set_search_query(query);

        Ok(list)
    }

    /// # 可将 object 列表导出到外部类型(关注便捷性)
    /// 可以参考下面示例,或者项目中的 `examples/custom.rs`
    /// ## 示例
    /// ```rust
    /// use aliyun_oss_client::{
    ///     decode::{ListError, RefineObject, RefineObjectList},
    ///     object::ExtractListError,
    ///     Client,
    /// };
    /// use dotenv::dotenv;
    /// use thiserror::Error;
    ///
    /// #[derive(Debug)]
    /// struct MyFile {
    ///     key: String,
    ///     #[allow(dead_code)]
    ///     other: String,
    /// }
    /// impl RefineObject<MyError> for MyFile {
    ///     fn set_key(&mut self, key: &str) -> Result<(), MyError> {
    ///         self.key = key.to_string();
    ///         Ok(())
    ///     }
    /// }
    ///
    /// #[derive(Default, Debug)]
    /// struct MyBucket {
    ///     name: String,
    ///     files: Vec<MyFile>,
    /// }
    ///
    /// impl RefineObjectList<MyFile, MyError> for MyBucket {
    ///     fn set_name(&mut self, name: &str) -> Result<(), MyError> {
    ///         self.name = name.to_string();
    ///         Ok(())
    ///     }
    ///     fn set_list(&mut self, list: Vec<MyFile>) -> Result<(), MyError> {
    ///         self.files = list;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// #[derive(Debug, Error)]
    /// #[error("my error")]
    /// enum MyError {}
    ///
    /// impl ListError for MyError {}
    ///
    /// async fn run() -> Result<(), ExtractListError> {
    ///     dotenv().ok();
    ///     use aliyun_oss_client::BucketName;
    ///
    ///     let client = Client::from_env().unwrap();
    ///
    ///     // 除了设置Default 外,还可以做更多设置
    ///     let mut bucket = MyBucket::default();
    ///
    ///     // 利用闭包对 MyFile 做一下初始化设置
    ///     let init_file = || MyFile {
    ///         key: String::default(),
    ///         other: "abc".to_string(),
    ///     };
    ///     //let bucket_name = env::var("ALIYUN_BUCKET").unwrap();
    ///     let bucket_name = "abc".parse::<BucketName>().unwrap();
    ///
    ///     client
    ///         .base_object_list(bucket_name, [], &mut bucket, init_file)
    ///         .await?;
    ///
    ///     println!("bucket: {:?}", bucket);
    ///
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub async fn base_object_list<
        Name: Into<BucketName>,
        Q: IntoIterator<Item = (QueryKey, QueryValue)>,
        List,
        Item,
        F,
        E: ListError,
        ItemErr: Error + 'static,
    >(
        &self,
        name: Name,
        query: Q,
        list: &mut List,
        init_object: F,
    ) -> Result<(), ExtractListError>
    where
        List: RefineObjectList<Item, E, ItemErr>,
        Item: RefineObject<ItemErr>,
        F: FnMut() -> Item,
    {
        let query = Query::from_iter(query);
        let name = name.into();

        self.base_object_list2(&name, &query, list, init_object)
            .await
    }

    /// # 可将 object 列表导出到外部类型(关注性能)
    pub async fn base_object_list2<List, Item, F, E: ListError, ItemErr: Error + 'static>(
        &self,
        name: &BucketName,
        query: &Query,
        list: &mut List,
        init_object: F,
    ) -> Result<(), ExtractListError>
    where
        List: RefineObjectList<Item, E, ItemErr>,
        Item: RefineObject<ItemErr>,
        F: FnMut() -> Item,
    {
        let (bucket_url, resource) = get_url_resource_with_bucket(self.as_ref(), name, query);

        let response = self.builder(Method::GET, bucket_url, resource)?;
        let content = response.send_adjust_error().await?;

        list.decode(&content.text().await?, init_object)?;

        Ok(())
    }
}

/// 为 [`base_object_list`] 方法,返回一个统一的 Error
///
/// [`base_object_list`]: crate::client::Client::base_object_list
#[derive(Debug)]
#[non_exhaustive]
pub struct ExtractListError {
    pub(crate) kind: ExtractListErrorKind,
}

/// [`ExtractListError`] 类型的枚举
///
/// [`ExtractListError`]: crate::object::ExtractListError
#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum ExtractListErrorKind {
    #[doc(hidden)]
    Builder(BuilderError),

    #[doc(hidden)]
    Reqwest(reqwest::Error),

    /// 解析 xml 错误
    Decode(InnerListError),

    /// 用于 Stream
    NoMoreFile,
}

impl From<InnerListError> for ExtractListError {
    fn from(value: InnerListError) -> Self {
        use ExtractListErrorKind::*;
        Self {
            kind: Decode(value),
        }
    }
}
impl From<BuilderError> for ExtractListError {
    fn from(value: BuilderError) -> Self {
        use ExtractListErrorKind::*;
        Self {
            kind: Builder(value),
        }
    }
}
impl From<reqwest::Error> for ExtractListError {
    fn from(value: reqwest::Error) -> Self {
        use ExtractListErrorKind::*;
        Self {
            kind: Reqwest(value),
        }
    }
}
impl Display for ExtractListError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ExtractListErrorKind::*;
        match &self.kind {
            Builder(_) => "builder error".fmt(f),
            Reqwest(_) => "reqwest error".fmt(f),
            Decode(_) => "decode xml failed".fmt(f),
            NoMoreFile => "no more file".fmt(f),
        }
    }
}
impl Error for ExtractListError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use ExtractListErrorKind::*;
        match &self.kind {
            Builder(e) => Some(e),
            Reqwest(e) => Some(e),
            Decode(e) => e.get_source(),
            NoMoreFile => None,
        }
    }
}

#[cfg(feature = "blocking")]
impl ClientRc {
    /// 查询默认 bucket 的文件列表
    ///
    /// 查询条件参数有多种方式,具体参考 [`get_object_list`](../bucket/struct.Bucket.html#method.get_object_list) 文档
    pub fn get_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>>(
        self,
        query: Q,
    ) -> Result<ObjectList<RcPointer>, ExtractListError> {
        let name = self.get_bucket_name();
        let bucket = BucketBase::new(name.clone(), self.get_endpoint().to_owned());

        let mut list = ObjectList::<RcPointer>::default();
        list.set_bucket(bucket.clone());

        let bucket_arc = Rc::new(bucket);

        let query = Query::from_iter(query);

        let (bucket_url, resource) = bucket_arc.get_url_resource(&query);

        let response = self.builder(Method::GET, bucket_url, resource)?;
        let content = response.send_adjust_error()?;

        list.decode(&content.text()?, || {
            Object::<RcPointer>::from_bucket(bucket_arc.clone())
        })?;

        list.set_client(Rc::new(self));
        list.set_search_query(query);

        Ok(list)
    }

    /// 可将 object 列表导出到外部 struct
    #[inline]
    pub fn base_object_list<
        Name: Into<BucketName>,
        Q: IntoIterator<Item = (QueryKey, QueryValue)>,
        List,
        Item,
        F,
        E: ListError,
        ItemErr: Error + 'static,
    >(
        &self,
        name: Name,
        query: Q,
        list: &mut List,
        init_object: F,
    ) -> Result<(), ExtractListError>
    where
        List: RefineObjectList<Item, E, ItemErr>,
        Item: RefineObject<ItemErr>,
        F: FnMut() -> Item,
    {
        let bucket = BucketBase::new(name.into(), self.get_endpoint().to_owned());

        let query = Query::from_iter(query);
        let (bucket_url, resource) = bucket.get_url_resource(&query);

        let response = self.builder(Method::GET, bucket_url, resource)?;
        let content = response.send_adjust_error()?;

        list.decode(&content.text()?, init_object)?;

        Ok(())
    }
}

#[cfg(feature = "blocking")]
impl Iterator for ObjectList<RcPointer> {
    type Item = ObjectList<RcPointer>;
    fn next(&mut self) -> Option<Self> {
        if !self.next_continuation_token.is_empty() {
            self.search_query
                .insert(CONTINUATION_TOKEN, self.next_continuation_token.to_owned());
            self.get_object_list().ok()
        } else {
            None
        }
    }
}

// use std::task::Poll::{self, Ready};

// impl Stream for ObjectList<ArcPointer> {
//     type Item = ObjectList<ArcPointer>;

//     fn poll_next(
//         self: std::pin::Pin<&mut Self>,
//         cx: &mut std::task::Context<'_>,
//     ) -> Poll<Option<Self::Item>> {
//         match self.next_query() {
//             Some(query) => {
//                 let mut url = self.bucket.to_url();
//                 url.set_search_query(&query);

//                 let canonicalized = CanonicalizedResource::from_bucket_query(&self.bucket, &query);

//                 let builder = self.builder(Method::GET, url, canonicalized);
//                 match builder {
//                     Err(err) => Ready(None),
//                     Ok(builder) => {
//                         let waker = cx.waker().clone();

//                         std::thread::spawn(move || {
//                             let response = builder.send_adjust_error();

//                             let response = futures::executor::block_on(response);
//                             let text = response.unwrap().text();
//                             let text = futures::executor::block_on(text);

//                             let text = text.unwrap();

//                             let bucket_arc = Arc::new(self.bucket);

//                             let init_object = || {
//                                 let object = Object::<ArcPointer>::default();
//                                 object.base.set_bucket(bucket_arc.clone());
//                                 object
//                             };

//                             self.decode(&text, init_object).unwrap();

//                             self.set_search_query(query);

//                             waker.wake();
//                         });

//                         Poll::Pending
//                     }
//                 }
//             }
//             None => Ready(None),
//         }
//     }
// }

#[oss_gen_rc]
impl PartialEq<Object<ArcPointer>> for Object<ArcPointer> {
    #[inline]
    fn eq(&self, other: &Object<ArcPointer>) -> bool {
        self.base == other.base
            && self.last_modified == other.last_modified
            && self.etag == other.etag
            && self._type == other._type
            && self.size == other.size
            && self.storage_class == other.storage_class
    }
}

impl<T: PointerFamily> PartialEq<DateTime<Utc>> for Object<T> {
    #[inline]
    fn eq(&self, other: &DateTime<Utc>) -> bool {
        &self.last_modified == other
    }
}

impl<T: PointerFamily> PartialEq<u64> for Object<T> {
    #[inline]
    fn eq(&self, other: &u64) -> bool {
        &self.size == other
    }
}

#[oss_gen_rc]
impl PartialEq<ObjectBase<ArcPointer>> for Object<ArcPointer> {
    #[inline]
    fn eq(&self, other: &ObjectBase<ArcPointer>) -> bool {
        &self.base == other
    }
}

/// 未来计划支持的功能
#[derive(Default)]
#[doc(hidden)]
pub struct PutObject<'a> {
    pub forbid_overwrite: bool,
    pub server_side_encryption: Option<Encryption>,
    pub server_side_data_encryption: Option<Encryption>,
    pub server_side_encryption_key_id: Option<&'a str>,
    pub object_acl: ObjectAcl,
    pub storage_class: StorageClass,
    pub tagging: Option<&'a str>,
}

/// 未来计划支持的功能
#[derive(Default)]
#[doc(hidden)]
pub enum Encryption {
    #[default]
    Aes256,
    Kms,
    Sm4,
}

/// 未来计划支持的功能
#[derive(Default)]
#[doc(hidden)]
pub enum ObjectAcl {
    #[default]
    Default,
    Private,
    PublicRead,
    PublicReadWrite,
}

/// 存储类型
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StorageClass {
    kind: StorageClassKind,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[non_exhaustive]
enum StorageClassKind {
    /// Standard 默认
    #[default]
    Standard,
    /// IA
    IA,
    /// Archive
    Archive,
    /// ColdArchive
    ColdArchive,
}

impl StorageClass {
    /// Archive
    pub const ARCHIVE: Self = Self {
        kind: StorageClassKind::Archive,
    };
    /// IA
    pub const IA: Self = Self {
        kind: StorageClassKind::IA,
    };
    /// Standard
    pub const STANDARD: Self = Self {
        kind: StorageClassKind::Standard,
    };
    /// ColdArchive
    pub const COLD_ARCHIVE: Self = Self {
        kind: StorageClassKind::ColdArchive,
    };

    /// init StorageClass
    pub fn new(s: &str) -> Option<StorageClass> {
        let start_char = s.chars().next()?;

        let kind = match start_char {
            'a' | 'A' => StorageClassKind::Archive,
            'i' | 'I' => StorageClassKind::IA,
            's' | 'S' => StorageClassKind::Standard,
            'c' | 'C' => StorageClassKind::ColdArchive,
            _ => return None,
        };
        Some(Self { kind })
    }
}

/// 未来计划支持的功能
#[derive(Default)]
#[doc(hidden)]
pub struct CopyObject<'a> {
    pub forbid_overwrite: bool,
    pub copy_source: &'a str,
    pub copy_source_if_match: Option<&'a str>,
    pub copy_source_if_none_match: Option<&'a str>,
    pub copy_source_if_unmodified_since: Option<&'a str>,
    pub copy_source_if_modified_since: Option<&'a str>,
    pub metadata_directive: CopyDirective,
    pub server_side_encryption: Option<Encryption>,
    pub server_side_encryption_key_id: Option<&'a str>,
    pub object_acl: ObjectAcl,
    pub storage_class: StorageClass,
    pub tagging: Option<&'a str>,
    pub tagging_directive: CopyDirective,
}

/// 未来计划支持的功能
#[derive(Default)]
#[doc(hidden)]
pub enum CopyDirective {
    #[default]
    Copy,
    Replace,
}