rocketmq_common/utils/
file_utils.rs1use std::fs::File;
19use std::io::Read;
20use std::io::Write;
21use std::io::{self};
22use std::path::Path;
23use std::path::PathBuf;
24
25use parking_lot::Mutex;
26use tracing::warn;
27
28static LOCK: Mutex<()> = Mutex::new(());
29
30pub fn file_to_string(file_name: &str) -> Result<String, io::Error> {
31 if !PathBuf::from(file_name).exists() {
32 warn!("file not exist:{}", file_name);
33 return Ok("".to_string());
34 }
35 let file = File::open(file_name)?;
36 file_to_string_impl(&file)
37}
38
39pub fn file_to_string_impl(file: &File) -> Result<String, io::Error> {
40 let file_length = file.metadata()?.len() as usize;
41 let mut data = vec![0; file_length];
42 let result = file.take(file_length as u64).read_exact(&mut data);
43
44 match result {
45 Ok(_) => Ok(String::from_utf8_lossy(&data).to_string()),
46 Err(_) => Err(io::Error::new(
47 io::ErrorKind::InvalidData,
48 "Failed to read file",
49 )),
50 }
51}
52
53pub fn string_to_file(str_content: &str, file_name: &str) -> io::Result<()> {
54 let lock = LOCK.lock(); let bak_file = format!("{file_name}.bak");
57
58 if let Ok(prev_content) = file_to_string(file_name) {
60 string_to_file_not_safe(&prev_content, &bak_file)?;
61 }
62
63 string_to_file_not_safe(str_content, file_name)?;
65 drop(lock);
66 Ok(())
67}
68
69fn string_to_file_not_safe(str_content: &str, file_name: &str) -> io::Result<()> {
70 if let Some(parent) = Path::new(file_name).parent() {
72 std::fs::create_dir_all(parent)?;
73 }
74 let file = File::create(file_name)?;
75
76 write_string_to_file(&file, str_content, "UTF-8")
77}
78
79fn write_string_to_file(file: &File, data: &str, _encoding: &str) -> io::Result<()> {
80 let mut os = io::BufWriter::new(file);
81
82 os.write_all(data.as_bytes())?;
83
84 Ok(())
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90
91 #[test]
92 fn test_file_to_string() {
93 let temp_file = tempfile::NamedTempFile::new().unwrap();
95 let file_path = temp_file.path().to_str().unwrap();
96
97 let content = "Hello, World!";
99 std::fs::write(file_path, content).unwrap();
100
101 let result = file_to_string(file_path);
103
104 assert!(result.is_ok());
106 assert_eq!(result.unwrap(), content);
107 }
108
109 #[test]
110 fn test_string_to_file() {
111 let temp_file = tempfile::NamedTempFile::new().unwrap();
113 let file_path = temp_file.path().to_str().unwrap();
114
115 let content = "Hello, World!";
117 let result = string_to_file(content, file_path);
118
119 assert!(result.is_ok());
121 assert_eq!(std::fs::read_to_string(file_path).unwrap(), content);
122 }
123}