-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.rs
86 lines (75 loc) · 2.27 KB
/
build.rs
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
use std::env;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Result, Write};
use std::path::Path;
macro_rules! template {
() => {
"\
// Generated by build.rs, DO NOT edit
/// Linux specific error codes defined in `errno.h`.
#[repr(i32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinuxError {{
{0}\
}}
impl TryFrom<i32> for LinuxError {{
type Error = i32;
fn try_from(value: i32) -> Result<Self, Self::Error> {{
use self::LinuxError::*;
match value {{
{1} _ => Err(value),
}}
}}
}}
impl LinuxError {{
/// Returns the error description.
pub const fn as_str(&self) -> &'static str {{
use self::LinuxError::*;
match self {{
{2} }}
}}
/// Returns the error code value in `i32`.
pub const fn code(self) -> i32 {{
self as i32
}}
}}
"
};
}
fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
gen_linux_errno(&Path::new(&out_dir).join("linux_errno.rs")).unwrap();
}
fn gen_linux_errno(dest_path: &Path) -> Result<()> {
let mut enum_define = Vec::new();
let mut try_from_i32 = Vec::new();
let mut detail_info = Vec::new();
let file = File::open("src/errno.h")?;
for line in BufReader::new(file).lines().map_while(Result::ok) {
if line.starts_with("#define") {
let mut iter = line.split_whitespace();
if let Some(name) = iter.nth(1) {
if let Some(num) = iter.next() {
let description = if let Some(pos) = line.find("/* ") {
String::from(line[pos + 3..].trim_end_matches(" */"))
} else {
format!("Error number {num}")
};
writeln!(enum_define, " /// {description}\n {name} = {num},")?;
writeln!(try_from_i32, " {num} => Ok({name}),")?;
writeln!(detail_info, " {name} => \"{description}\",")?;
}
}
}
}
fs::write(
dest_path,
format!(
template!(),
String::from_utf8_lossy(&enum_define),
String::from_utf8_lossy(&try_from_i32),
String::from_utf8_lossy(&detail_info)
),
)?;
Ok(())
}