linux_bzimage_builder/
encoder.rs1use std::{
6 ffi::{OsStr, OsString},
7 io::Write,
8 str::FromStr,
9};
10
11use libflate::{gzip, zlib};
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub enum PayloadEncoding {
16 #[default]
17 #[serde(rename = "raw")]
18 Raw,
19 #[serde(rename = "gzip")]
20 Gzip,
21 #[serde(rename = "zlib")]
22 Zlib,
23}
24
25impl FromStr for PayloadEncoding {
26 type Err = String;
27
28 fn from_str(s: &str) -> Result<Self, Self::Err> {
29 match s {
30 "raw" => Ok(Self::Raw),
31 "gzip" => Ok(Self::Gzip),
32 "zlib" => Ok(Self::Zlib),
33 _ => Err(format!("Invalid encoding format: {}", s)),
34 }
35 }
36}
37
38impl From<OsString> for PayloadEncoding {
39 fn from(os_string: OsString) -> Self {
40 PayloadEncoding::from_str(&os_string.to_string_lossy()).unwrap()
41 }
42}
43
44impl From<&OsStr> for PayloadEncoding {
45 fn from(os_str: &OsStr) -> Self {
46 PayloadEncoding::from_str(&os_str.to_string_lossy()).unwrap()
47 }
48}
49
50pub fn encode_kernel(kernel: Vec<u8>, encoding: PayloadEncoding) -> Vec<u8> {
52 match encoding {
53 PayloadEncoding::Raw => kernel,
54 PayloadEncoding::Gzip => {
55 let mut encoder = gzip::Encoder::new(Vec::new()).unwrap();
56 encoder.write_all(&kernel).unwrap();
57 encoder.finish().into_result().unwrap()
58 }
59 PayloadEncoding::Zlib => {
60 let mut encoder = zlib::Encoder::new(Vec::new()).unwrap();
61 encoder.write_all(&kernel).unwrap();
62 encoder.finish().into_result().unwrap()
63 }
64 }
65}