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
use std::{fs, io};
use std::io::{Read};
use std::convert::TryFrom;
use super::core::ZoneFile;
use super::parser;
use nom::{Context,ErrorKind};
#[derive(Debug)]
pub enum LoadError {
FileOpen(io::Error),
Read(io::Error),
Incomplete,
ParseError(ErrorKind),
ParseFailure,
}
type LoadResult<T> = Result<T, LoadError>;
impl From<nom::Err<&[u8]>> for LoadError {
fn from(e: nom::Err<&[u8]>) -> LoadError {
match e {
nom::Err::Incomplete(_) => LoadError::Incomplete,
nom::Err::Error(Context::Code(_,k)) => LoadError::ParseError(k),
nom::Err::Failure(_) => LoadError::ParseFailure,
}
}
}
pub trait TryFromLUZ<T>
where T: Read, Self: Sized {
type Error;
fn try_from_luz(buf: &mut T) -> Result<Self, Self::Error>;
}
impl TryFrom<&str> for ZoneFile {
type Error = LoadError;
fn try_from(filename: &str) -> LoadResult<ZoneFile> {
fs::File::open(filename)
.map_err(LoadError::FileOpen)
.and_then(ZoneFile::try_from)
}
}
impl TryFrom<fs::File> for ZoneFile {
type Error = LoadError;
fn try_from(file: fs::File) -> LoadResult<ZoneFile> {
ZoneFile::try_from_luz(&mut io::BufReader::new(file))
}
}
impl<T> TryFromLUZ<T> for ZoneFile
where T: Read {
type Error = LoadError;
fn try_from_luz(buf: &mut T) -> Result<Self, Self::Error> {
let mut bytes: Vec<u8> = Vec::new();
buf.read_to_end(&mut bytes)
.map_err(LoadError::Read)
.and_then(|_| parser::parse_zone_file(&bytes)
.map_err(LoadError::from).map(|r| r.1))
}
}