opendal_core/blocking/copy.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::Copier as AsyncCopier;
19use crate::*;
20
21/// BlockingCopier is designed to drive long-running copy operations in a
22/// blocking manner.
23pub struct Copier {
24 handle: tokio::runtime::Handle,
25 copier: Option<AsyncCopier>,
26}
27
28/// # Safety
29///
30/// BlockingCopier will only be accessed by `&mut Self`.
31unsafe impl Sync for Copier {}
32
33impl Copier {
34 /// Create a new blocking copier.
35 pub(crate) fn new(handle: tokio::runtime::Handle, copier: AsyncCopier) -> Self {
36 Self {
37 handle,
38 copier: Some(copier),
39 }
40 }
41
42 /// Abort the pending copy operation.
43 pub fn abort(&mut self) -> Result<()> {
44 let Some(copier) = self.copier.as_mut() else {
45 return Ok(());
46 };
47
48 self.handle.block_on(copier.abort())
49 }
50}
51
52impl Iterator for Copier {
53 type Item = Result<usize>;
54
55 fn next(&mut self) -> Option<Self::Item> {
56 let copier = self.copier.as_mut()?;
57
58 match self.handle.block_on(copier.next()) {
59 Ok(Some(n)) => Some(Ok(n)),
60 Ok(None) => {
61 self.copier = None;
62 None
63 }
64 Err(err) => Some(Err(err)),
65 }
66 }
67}
68
69impl Drop for Copier {
70 fn drop(&mut self) {
71 if let Some(v) = self.copier.take() {
72 self.handle.block_on(async move { drop(v) });
73 }
74 }
75}