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
#[cfg(feature = "std")]
use super::error::ErrorKind;
#[cfg(all(unix, feature = "std"))]
use super::FILE_MODE;
use crate::encoding::Error;
use alloc::{string::String, vec::Vec};
#[cfg(feature = "std")]
use std::{fs::File, io::Write, path::Path};
#[cfg(all(unix, feature = "std"))]
use std::{fs::OpenOptions, os::unix::fs::OpenOptionsExt};
use subtle_encoding::Encoding;
#[cfg(feature = "std")]
use zeroize::Zeroize;
pub trait Encode: Sized {
fn encode<E: Encoding>(&self, encoding: &E) -> Vec<u8>;
fn encode_to_string<E: Encoding>(&self, encoding: &E) -> Result<String, Error> {
String::from_utf8(self.encode(encoding)).map_err(|_| ErrorKind::Encode.into())
}
#[cfg(feature = "std")]
fn encode_to_writer<W, E>(&self, writer: &mut W, encoding: &E) -> Result<usize, Error>
where
W: Write,
E: Encoding,
{
let mut encoded_bytes = self.encode(encoding);
writer.write_all(encoded_bytes.as_ref())?;
encoded_bytes.zeroize();
Ok(encoded_bytes.len())
}
#[cfg(all(unix, feature = "std"))]
fn encode_to_file<P, E>(&self, path: P, encoding: &E) -> Result<File, Error>
where
P: AsRef<Path>,
E: Encoding,
{
let path = path.as_ref();
let mut file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.mode(FILE_MODE)
.open(path)
.map_err(|e| {
Error::new(
ErrorKind::Io,
Some(&format!("couldn't create {}: {}", path.display(), e)),
)
})?;
self.encode_to_writer(&mut file, encoding)?;
Ok(file)
}
#[cfg(all(not(unix), feature = "std"))]
fn encode_to_file<P, E>(&self, path: P, encoding: &E) -> Result<File, Error>
where
P: AsRef<Path>,
E: Encoding,
{
let path = path.as_ref();
let mut file = File::create(path).map_err(|e| {
Error::new(
ErrorKind::Io,
Some(&format!("couldn't create {}: {}", path.display(), e)),
)
})?;
self.encode_to_writer(&mut file, encoding)?;
Ok(file)
}
}