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
use super::core::ZoneFile;
use super::parser;
use assembly_core::nom::{error::Error as NomError, error::ErrorKind, Err as NomErr};
use displaydoc::Display;
use std::convert::TryFrom;
use std::io::Read;
use std::{fs, io};
use thiserror::Error;

/// Error when loading a LUZ file
#[derive(Debug, Error, Display)]
pub enum LoadError {
    /// Failed to open the file
    FileOpen(io::Error),
    /// Failed to read from the file
    Read(io::Error),
    /// Missing bytes
    Incomplete,
    /// Failed to parse (recoverable)
    ParseError(ErrorKind),
    /// Failed to parse (fatal)
    ParseFailure(ErrorKind),
}

type LoadResult<T> = Result<T, LoadError>;

// Generates a LoadError from a nom error
impl From<NomErr<NomError<&[u8]>>> for LoadError {
    fn from(e: NomErr<NomError<&[u8]>>) -> LoadError {
        match e {
            // Need to translate the error here, as this lives longer than the input
            NomErr::Incomplete(_) => LoadError::Incomplete,
            NomErr::Error(e) => LoadError::ParseError(e.code),
            NomErr::Failure(e) => LoadError::ParseFailure(e.code),
        }
    }
}

#[allow(clippy::upper_case_acronyms)]
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<Vec<u8>> {
    type Error = LoadError;

    fn try_from(filename: &str) -> LoadResult<Self> {
        fs::File::open(filename)
            .map_err(LoadError::FileOpen)
            .and_then(ZoneFile::try_from)
    }
}

impl TryFrom<fs::File> for ZoneFile<Vec<u8>> {
    type Error = LoadError;

    fn try_from(file: fs::File) -> LoadResult<Self> {
        ZoneFile::try_from_luz(&mut io::BufReader::new(file))
    }
}

impl<T> TryFromLUZ<T> for ZoneFile<Vec<u8>>
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)
            })
    }
}