opendal/services/memory/
writer.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 std::sync::Arc;
19
20use super::core::*;
21use crate::raw::oio;
22use crate::raw::*;
23use crate::*;
24
25pub struct MemoryWriter {
26    core: Arc<MemoryCore>,
27    path: String,
28    op: OpWrite,
29    buf: Option<oio::QueueBuf>,
30}
31
32impl MemoryWriter {
33    pub fn new(core: Arc<MemoryCore>, path: String, op: OpWrite) -> Self {
34        Self {
35            core,
36            path,
37            op,
38            buf: None,
39        }
40    }
41}
42
43impl oio::Write for MemoryWriter {
44    async fn write(&mut self, bs: Buffer) -> Result<()> {
45        let mut buf = self.buf.take().unwrap_or_default();
46        buf.push(bs);
47        self.buf = Some(buf);
48        Ok(())
49    }
50
51    async fn close(&mut self) -> Result<Metadata> {
52        let buf = self.buf.take().unwrap_or_default();
53        let content = buf.collect();
54
55        let mut metadata = Metadata::new(EntryMode::FILE);
56        metadata.set_content_length(content.len() as u64);
57
58        if let Some(v) = self.op.cache_control() {
59            metadata.set_cache_control(v);
60        }
61        if let Some(v) = self.op.content_disposition() {
62            metadata.set_content_disposition(v);
63        }
64        if let Some(v) = self.op.content_type() {
65            metadata.set_content_type(v);
66        }
67        if let Some(v) = self.op.content_encoding() {
68            metadata.set_content_encoding(v);
69        }
70
71        let value = MemoryValue {
72            metadata: metadata.clone(),
73            content,
74        };
75
76        self.core.set(&self.path, value)?;
77
78        Ok(metadata)
79    }
80
81    async fn abort(&mut self) -> Result<()> {
82        self.buf = None;
83        Ok(())
84    }
85}