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
use crate::error::{CobbleError, CobbleResult};
use crate::minecraft::models::extract::Extract;
use crate::minecraft::models::library_downloads::LibraryDownloads;
use crate::minecraft::models::natives::Natives;
use crate::minecraft::models::rule::Rule;
use crate::utils::os::Architecture;
use itertools::Itertools;
use serde::{Deserialize, Serialize};

/// A library need for running the game.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Library {
    /// Information about downloading the library.
    pub downloads: LibraryDownloads,
    /// Name of the library.
    pub name: String,
    /// Available natives.
    pub natives: Option<Natives>,
    /// Rules for this library.
    #[serde(default)]
    pub rules: Vec<Rule>,
    /// Extract options.
    pub extract: Option<Extract>,
}

impl Library {
    /// Checks if the library needs to be used on the current executing machine.
    pub fn check_use(&self) -> bool {
        for rule in &self.rules {
            if !rule.allows() {
                return false;
            }
        }

        true
    }

    /// Extract the package, name and version from the library name.
    pub fn extract_information(&self) -> CobbleResult<(String, String, String)> {
        self.name
            .split(':')
            .map(|x| x.to_string())
            .collect_tuple()
            .ok_or(CobbleError::LibraryNameFormat)
    }

    /// Gets the native library if applicable.
    pub fn get_native(&self) -> Option<String> {
        let arch = Architecture::current();

        if let Some(natives) = &self.natives {
            return natives
                .get_for_current_platform()
                .map(|n| n.replace("${arch}", &arch.get_bits().to_string()));
        }

        None
    }
}