frostwalker 0.1.2

A TOML-like configuration language parser with zero dependencies outside of std.
Documentation
//! Module containing the formatter which turns the tokens into a HashMap.
use super::{Token, Class};
use std::collections::HashMap;

/// This function creates a HashMap from tokens.
///
/// It does not do any verification of the source tokens and may panic if something goes wrong.
///
/// ```
/// use frostwalker::{formatter, Token, Class};
/// 
/// let identifier = Token { class: Class::IDENTIFIER, value: Some("key".to_string()) };
/// let equals = Token { class: Class::EQUALS, value: None };
/// let value = Token { class: Class::LITERAL, value: Some("5".to_string()) };
///
/// let hashmap = formatter::format(vec![identifier, equals, value]);
/// assert_eq!(hashmap.get("key").unwrap(), "5");
/// ```
pub fn format(tree: Vec<Token>) -> HashMap<String, String> {
	let mut output = HashMap::new();
	let mut current_key = "".to_string();
	let mut current_index;
	let mut i = 0;
	while i < tree.len() {
		if tree[i].class == Class::IDENTIFIER {
			current_key = tree[i].value.clone().unwrap_or("".to_string());
			i = i + 1;
			continue;
		}

		if (tree[i].class == Class::LITERAL || tree[i].class == Class::BOOLEAN) && current_key != "".to_string() {
			output.insert(current_key, tree[i].value.clone().unwrap_or("".to_string()));
			current_key = "".to_string();
			i = i + 1;
			continue;
		}

		if tree[i].class == Class::SEPARATOR && current_key != "".to_string() && tree[i].value.clone().unwrap_or("".to_string()) == "[".to_string() {
			current_index = 0;
			loop {
				i = i + 1;
				output.insert(format!("{}[{}]", current_key, current_index), tree[i].value.clone().unwrap_or("".to_string()));
				current_index = current_index + 1;
				i = i + 1;
				if tree[i].class == Class::SEPARATOR && tree[i].value.clone().unwrap_or("".to_string()) == ",".to_string() {
					continue;
				} else {
					break;
				}
			}
			output.insert(current_key.clone(), (current_index).to_string());
		}

		i = i + 1;
	}
	return output;
}