aboutsummaryrefslogtreecommitdiff
path: root/stockton-levels/src/q3/entities.rs
blob: 9eb0a6159f78dfcc23f7107ecea50fc84eea27a5 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
 * Copyright (C) Oscar Shrimpton 2020
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

use std::collections::HashMap;
use std::str;

use super::Q3BspFile;
use crate::coords::CoordSystem;
use crate::traits::entities::*;
use crate::types::{ParseError, Result};

const QUOTE: u8 = b'"';
const END_BRACKET: u8 = b'}';
const START_BRACKET: u8 = b'{';

/// Internal enum to parse through the entities string.
#[derive(PartialEq, Eq)]
enum ParseState {
    InKey,
    InValue,
    AfterKey,
    InsideEntity,
    OutsideEntity,
}

/// Parse the given data as an Entities lump
pub fn from_data(data: &[u8]) -> Result<Box<[Entity]>> {
    use self::ParseState::*;

    let string = str::from_utf8(data).unwrap();

    let mut attrs = HashMap::new();
    let mut entities = Vec::new();

    let mut state = ParseState::OutsideEntity;

    let mut key_start = 0;
    let mut key_end = 0;
    let mut val_start = 0;
    let mut val_end;

    for (i, chr) in string.bytes().enumerate() {
        match chr {
            QUOTE => match state {
                InsideEntity => {
                    state = ParseState::InKey;
                    key_start = i + 1;
                }
                InKey => {
                    state = ParseState::AfterKey;
                    key_end = i;
                }
                AfterKey => {
                    state = ParseState::InValue;
                    val_start = i + 1;
                }
                InValue => {
                    state = ParseState::InsideEntity;
                    val_end = i;

                    attrs.insert(
                        string[key_start..key_end].to_owned(),
                        string[val_start..val_end].to_owned(),
                    );
                }
                _ => {
                    return Err(ParseError::Invalid);
                }
            },
            END_BRACKET => {
                if state != InsideEntity {
                    return Err(ParseError::Invalid);
                }

                state = OutsideEntity;

                entities.push(Entity { attributes: attrs });
                attrs = HashMap::new();
            }
            START_BRACKET => {
                if state != OutsideEntity {
                    return Err(ParseError::Invalid);
                }
                state = InsideEntity;
            }
            _ => {}
        }
    }
    Ok(entities.into_boxed_slice())
}

impl<T: CoordSystem> HasEntities for Q3BspFile<T> {
    type EntitiesIter<'a> = std::slice::Iter<'a, Entity>;

    fn entities_iter(&self) -> Self::EntitiesIter<'_> {
        self.entities.iter()
    }
}