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 //! filemanager 16 #![allow(missing_docs)] 17 18 use crate::config::KERNEL_FILE_NODE_SIZE; 19 #[cfg(not(feature = "host"))] 20 use crate::utils::hdc_log::*; 21 use std::fs::OpenOptions; 22 use std::fs::{self, File}; 23 use std::io::Read; 24 25 pub struct FileManager { 26 path: Option<String>, 27 file: Option<File>, 28 } 29 30 impl FileManager { remove_filenull31 pub fn remove_file(path: &str) -> std::io::Result<()> { 32 fs::remove_file(path) 33 } 34 newnull35 pub fn new(file_path: String) -> FileManager { 36 FileManager { 37 path: Some(file_path), 38 file: None, 39 } 40 } 41 opennull42 pub fn open(&mut self) -> (bool, String) { 43 let mut result = false; 44 let mut err_msg = String::from(""); 45 if let Some(path) = &self.path { 46 let mut _file = OpenOptions::new().read(true).open(path); 47 match _file { 48 Ok(f) => { 49 self.file = Some(f); 50 result = true; 51 } 52 Err(e) => { 53 err_msg = format!("Transfer {} failed: {:?}.", path, e); 54 crate::error!("{err_msg}"); 55 result = false; 56 } 57 } 58 } 59 (result, err_msg) 60 } 61 file_sizenull62 pub fn file_size(&self) -> u64 { 63 if let Some(f) = &self.file { 64 let meta_size: u64 = match f.metadata() { 65 Ok(meta) => meta.len(), 66 Err(e) => { 67 crate::warn!("failed to get file metadata, error: {:#?}", e); 68 0 69 } 70 }; 71 if meta_size == KERNEL_FILE_NODE_SIZE.into() || meta_size == 0 { 72 let node_size = self.buffer_read(meta_size) as u64; 73 return node_size; 74 } else { 75 return meta_size; 76 } 77 } 78 0 79 } 80 buffer_readnull81 pub fn buffer_read(&self, meta_size: u64) -> usize { 82 let mut buf = [0u8; KERNEL_FILE_NODE_SIZE as usize]; 83 let mut read_len = 0usize; 84 if let Some(path) = &self.path { 85 let mut _file = File::open(path); 86 if let Ok(mut f) = _file { 87 loop { 88 let single_len = match f.read(&mut buf[read_len..]) { 89 Ok(len) => len, 90 Err(e) => { 91 crate::warn!( 92 "failed to read kernel file node with buffer, error: {:#?}", 93 e 94 ); 95 break; 96 } 97 }; 98 read_len += single_len; 99 if single_len == 0 || meta_size == 0 { 100 break; 101 } 102 } 103 } 104 } 105 read_len 106 } 107 } 108