1use crate::raw::{
8 BTRFS_DEFRAG_RANGE_COMPRESS, BTRFS_DEFRAG_RANGE_COMPRESS_LEVEL,
9 BTRFS_DEFRAG_RANGE_NOCOMPRESS, BTRFS_DEFRAG_RANGE_START_IO,
10 btrfs_ioc_defrag_range, btrfs_ioctl_defrag_range_args,
11};
12use std::{
13 mem,
14 os::{fd::AsRawFd, unix::io::BorrowedFd},
15};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum CompressType {
23 Zlib = 1,
24 Lzo = 2,
25 Zstd = 3,
26}
27
28impl std::fmt::Display for CompressType {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 match self {
31 Self::Zlib => f.write_str("zlib"),
32 Self::Lzo => f.write_str("lzo"),
33 Self::Zstd => f.write_str("zstd"),
34 }
35 }
36}
37
38impl std::str::FromStr for CompressType {
39 type Err = String;
40
41 fn from_str(s: &str) -> Result<Self, Self::Err> {
42 match s.to_ascii_lowercase().as_str() {
43 "zlib" => Ok(Self::Zlib),
44 "lzo" => Ok(Self::Lzo),
45 "zstd" => Ok(Self::Zstd),
46 _ => Err(format!(
47 "unknown compress type '{s}'; expected zlib, lzo, or zstd"
48 )),
49 }
50 }
51}
52
53#[derive(Debug, Clone)]
58pub struct DefragRangeArgs {
59 pub start: u64,
61 pub len: u64,
63 pub flush: bool,
65 pub extent_thresh: u32,
69 pub compress: Option<CompressSpec>,
72 pub nocomp: bool,
75}
76
77#[derive(Debug, Clone, Copy)]
79pub struct CompressSpec {
80 pub compress_type: CompressType,
82 pub level: Option<i8>,
87}
88
89impl DefragRangeArgs {
90 pub fn new() -> Self {
93 Self {
94 start: 0,
95 len: u64::MAX,
96 flush: false,
97 extent_thresh: 0,
98 compress: None,
99 nocomp: false,
100 }
101 }
102
103 pub fn start(mut self, start: u64) -> Self {
105 self.start = start;
106 self
107 }
108
109 pub fn len(mut self, len: u64) -> Self {
111 self.len = len;
112 self
113 }
114
115 pub fn flush(mut self) -> Self {
117 self.flush = true;
118 self
119 }
120
121 pub fn extent_thresh(mut self, thresh: u32) -> Self {
124 self.extent_thresh = thresh;
125 self
126 }
127
128 pub fn compress(mut self, spec: CompressSpec) -> Self {
130 self.compress = Some(spec);
131 self.nocomp = false;
132 self
133 }
134
135 pub fn nocomp(mut self) -> Self {
137 self.nocomp = true;
138 self.compress = None;
139 self
140 }
141}
142
143impl Default for DefragRangeArgs {
144 fn default() -> Self {
145 Self::new()
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
156 fn compress_type_display() {
157 assert_eq!(format!("{}", CompressType::Zlib), "zlib");
158 assert_eq!(format!("{}", CompressType::Lzo), "lzo");
159 assert_eq!(format!("{}", CompressType::Zstd), "zstd");
160 }
161
162 #[test]
165 fn compress_type_from_str() {
166 assert_eq!("zlib".parse::<CompressType>().unwrap(), CompressType::Zlib);
167 assert_eq!("lzo".parse::<CompressType>().unwrap(), CompressType::Lzo);
168 assert_eq!("zstd".parse::<CompressType>().unwrap(), CompressType::Zstd);
169 }
170
171 #[test]
172 fn compress_type_from_str_case_insensitive() {
173 assert_eq!("ZLIB".parse::<CompressType>().unwrap(), CompressType::Zlib);
174 assert_eq!("Zstd".parse::<CompressType>().unwrap(), CompressType::Zstd);
175 }
176
177 #[test]
178 fn compress_type_from_str_invalid() {
179 assert!("lz4".parse::<CompressType>().is_err());
180 assert!("".parse::<CompressType>().is_err());
181 }
182
183 #[test]
186 fn defrag_args_defaults() {
187 let args = DefragRangeArgs::new();
188 assert_eq!(args.start, 0);
189 assert_eq!(args.len, u64::MAX);
190 assert!(!args.flush);
191 assert_eq!(args.extent_thresh, 0);
192 assert!(args.compress.is_none());
193 assert!(!args.nocomp);
194 }
195
196 #[test]
197 fn defrag_args_builder_chain() {
198 let args = DefragRangeArgs::new()
199 .start(4096)
200 .len(1024 * 1024)
201 .flush()
202 .extent_thresh(256 * 1024);
203 assert_eq!(args.start, 4096);
204 assert_eq!(args.len, 1024 * 1024);
205 assert!(args.flush);
206 assert_eq!(args.extent_thresh, 256 * 1024);
207 }
208
209 #[test]
210 fn defrag_args_compress_clears_nocomp() {
211 let args = DefragRangeArgs::new().nocomp().compress(CompressSpec {
212 compress_type: CompressType::Zstd,
213 level: None,
214 });
215 assert!(args.compress.is_some());
216 assert!(!args.nocomp);
217 }
218
219 #[test]
220 fn defrag_args_nocomp_clears_compress() {
221 let args = DefragRangeArgs::new()
222 .compress(CompressSpec {
223 compress_type: CompressType::Zlib,
224 level: Some(3),
225 })
226 .nocomp();
227 assert!(args.compress.is_none());
228 assert!(args.nocomp);
229 }
230
231 #[test]
232 fn defrag_args_default_trait() {
233 let a = DefragRangeArgs::default();
234 let b = DefragRangeArgs::new();
235 assert_eq!(a.start, b.start);
236 assert_eq!(a.len, b.len);
237 }
238}
239
240pub fn defrag_range(fd: BorrowedFd, args: &DefragRangeArgs) -> nix::Result<()> {
246 let mut raw: btrfs_ioctl_defrag_range_args = unsafe { mem::zeroed() };
247
248 raw.start = args.start;
249 raw.len = args.len;
250 raw.extent_thresh = args.extent_thresh;
251
252 if args.flush {
253 raw.flags |= BTRFS_DEFRAG_RANGE_START_IO as u64;
254 }
255
256 if args.nocomp {
257 raw.flags |= BTRFS_DEFRAG_RANGE_NOCOMPRESS as u64;
258 } else if let Some(spec) = args.compress {
259 raw.flags |= BTRFS_DEFRAG_RANGE_COMPRESS as u64;
260 match spec.level {
261 None => {
262 raw.__bindgen_anon_1.compress_type = spec.compress_type as u32;
263 }
264 Some(level) => {
265 raw.flags |= BTRFS_DEFRAG_RANGE_COMPRESS_LEVEL as u64;
266 raw.__bindgen_anon_1.compress.type_ = spec.compress_type as u8;
267 raw.__bindgen_anon_1.compress.level = level;
268 }
269 }
270 }
271
272 unsafe { btrfs_ioc_defrag_range(fd.as_raw_fd(), &mut raw) }?;
273 Ok(())
274}