summaryrefslogtreecommitdiff
path: root/support/texlab/src/distro/miktex.rs
blob: c7a92d572e5109350818d1cd8b955f7aa35b10c4 (plain)
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
use std::{
    ffi::OsStr,
    fs,
    io::{self, Cursor},
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use byteorder::{LittleEndian, ReadBytesExt};

use super::kpsewhich::{self, Resolver};

pub fn load_resolver() -> Result<Resolver> {
    let root_directories = kpsewhich::root_directories()?;
    let resolver = kpsewhich::parse_database(&root_directories, read_database)?;
    Ok(resolver)
}

const DATABASE_PATH: &str = "miktex/data/le";
const FNDB_SIGNATURE: u32 = 0x42_44_4e_46;
const FNDB_WORD_SIZE: u32 = 4;
const FNDB_TABLE_POINTER_OFFSET: u32 = 4 * FNDB_WORD_SIZE;
const FNDB_TABLE_SIZE_OFFSET: u32 = 6 * FNDB_WORD_SIZE;
const FNDB_ENTRY_SIZE: u32 = 4 * FNDB_WORD_SIZE;

fn read_database(directory: &Path) -> Result<Vec<PathBuf>> {
    let database_directory = directory.join(DATABASE_PATH);
    if !database_directory.exists() {
        return Ok(Vec::new());
    }

    let mut database = Vec::new();
    for file in fs::read_dir(database_directory)?.filter_map(Result::ok) {
        if file.path().extension().and_then(OsStr::to_str) == Some("fndb-5") {
            let bytes = fs::read(file.path())?;
            database.extend(parse_database(&bytes).context("parsing kpsewhich database")?);
        }
    }
    Ok(database)
}

fn parse_database(bytes: &[u8]) -> io::Result<Vec<PathBuf>> {
    let mut reader = Cursor::new(bytes);
    if reader.read_u32::<LittleEndian>()? != FNDB_SIGNATURE {
        return Err(io::ErrorKind::InvalidData.into());
    }

    reader.set_position(u64::from(FNDB_TABLE_POINTER_OFFSET));
    let table_address = reader.read_u32::<LittleEndian>()?;

    reader.set_position(u64::from(FNDB_TABLE_SIZE_OFFSET));
    let table_size = reader.read_u32::<LittleEndian>()?;

    let mut files = Vec::new();
    for i in 0..table_size {
        let offset = table_address + i * FNDB_ENTRY_SIZE as u32;
        reader.set_position(u64::from(offset));
        let file_name_offset = reader.read_u32::<LittleEndian>()? as usize;
        let directory_offset = reader.read_u32::<LittleEndian>()? as usize;
        let file_name = read_string(bytes, file_name_offset)?;
        let directory = read_string(bytes, directory_offset)?;

        let file = PathBuf::from(directory).join(file_name);
        files.push(file);
    }

    Ok(files)
}

fn read_string(bytes: &[u8], offset: usize) -> io::Result<&str> {
    let mut byte = bytes[offset];
    let mut length = 0;
    while byte != 0x00 {
        length += 1;
        byte = bytes[offset + length];
    }

    std::str::from_utf8(&bytes[offset..offset + length])
        .map_err(|_| io::ErrorKind::InvalidData.into())
}