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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Кодирование в текст из ячеек по 28 символов, раскладка по частям, словари.
|
| 2 |
+
//!
|
| 3 |
+
//! Ячейка позиции: `{'x':0000,'y':0000,'z':0000}`
|
| 4 |
+
//! Ячейка-заголовок: `KKKKKKKKNNNNNNNNLLLLLLLL0000` — три поля по 8 цифр и 4 нуля добивки:
|
| 5 |
+
//! K — индекс блока в списке блоков,
|
| 6 |
+
//! N — номер NBT (элемент списка NBT с индексом N-1, 0 — нет NBT),
|
| 7 |
+
//! L — сколько ячеек позиций идёт сразу за заголовком.
|
| 8 |
+
//! Координата — ровно 4 символа: `0005`; отрицательные — `-001`.
|
| 9 |
+
//! Ячейка позиции НЕ валидный JSON (ведущие нули): читать по фиксированным смещениям
|
| 10 |
+
//! 5..9, 14..18, 23..27. Заголовок: 0..8, 8..16, 16..24.
|
| 11 |
+
//!
|
| 12 |
+
//! Раскладка по частям (вариант B): часть = до 857 ячеек (23 996 символов).
|
| 13 |
+
//! Серия позиций не переходит границу части: сервер режет её и пишет в начале
|
| 14 |
+
//! следующей части новый заголовок с теми же k и n. Каждая часть начинается
|
| 15 |
+
//! с заголовка и состоит из целых серий. Если в конце части остаётся одна
|
| 16 |
+
//! ячейка (заголовок с позицией не влезает), часть закрывается на ячейку короче.
|
| 17 |
+
|
| 18 |
+
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
| 19 |
+
use std::fmt;
|
| 20 |
+
|
| 21 |
+
use serde_json::Value;
|
| 22 |
+
|
| 23 |
+
/// (название блока, SNBT или "") → ячейки позиций подряд, по 28 байт на позицию.
|
| 24 |
+
pub type Groups = BTreeMap<(String, String), Vec<u8>>;
|
| 25 |
+
|
| 26 |
+
pub const CELL_LEN: usize = 28;
|
| 27 |
+
pub const CELLS_PER_PART: usize = 857;
|
| 28 |
+
/// 857 × 28 = 23 996 ≤ 24 000.
|
| 29 |
+
pub const PART_CHARS: usize = CELL_LEN * CELLS_PER_PART;
|
| 30 |
+
/// Максимум позиций в одной серии (поле `L` — 8 цифр).
|
| 31 |
+
pub const MAX_RUN: usize = 99_999_999;
|
| 32 |
+
/// Максимальное значение полей `K`, `N` заголовка (8 цифр).
|
| 33 |
+
pub const MAX_KEY: usize = 99_999_999;
|
| 34 |
+
pub const COORD_MIN: i32 = -999;
|
| 35 |
+
pub const COORD_MAX: i32 = 9_999;
|
| 36 |
+
/// Максимум символов в JSON одной части списка.
|
| 37 |
+
pub const DICT_PART_JSON_MAX: usize = 24_000;
|
| 38 |
+
/// Запас под скобки списка `[` и `]`.
|
| 39 |
+
const DICT_JSON_RESERVE: usize = 2;
|
| 40 |
+
/// Максимальная длина одного NBT-элемента в JSON-массиве (с запятой). Больше — tombstone.
|
| 41 |
+
const MAX_NBT_ENTRY: usize = DICT_PART_JSON_MAX - DICT_JSON_RESERVE;
|
| 42 |
+
|
| 43 |
+
const POS_TEMPLATE: &[u8; CELL_LEN] = br#"{'x':0000,'y':0000,'z':0000}"#;
|
| 44 |
+
const HEADER_TEMPLATE: &[u8; CELL_LEN] = b"0000000000000000000000000000";
|
| 45 |
+
|
| 46 |
+
const _: () = assert!(PART_CHARS <= 24_000);
|
| 47 |
+
const _: () = assert!(CELLS_PER_PART >= 2);
|
| 48 |
+
|
| 49 |
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
| 50 |
+
pub enum EncodeError {
|
| 51 |
+
CoordOutOfRange(i32),
|
| 52 |
+
TooManyUniqueBlocks(usize),
|
| 53 |
+
TooManyUniqueNbt(usize),
|
| 54 |
+
EntryTooLong(usize),
|
| 55 |
+
InvalidCells,
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
impl fmt::Display for EncodeError {
|
| 59 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 60 |
+
match self {
|
| 61 |
+
EncodeError::CoordOutOfRange(v) => write!(
|
| 62 |
+
f,
|
| 63 |
+
"координата {v} вне диапазона {COORD_MIN}..{COORD_MAX}, ячейка из 4 символов её не вмещает"
|
| 64 |
+
),
|
| 65 |
+
EncodeError::TooManyUniqueBlocks(n) => write!(
|
| 66 |
+
f,
|
| 67 |
+
"уникальных блоков {n}, максимум {} (индекс блока — 8 цифр в заголовке)",
|
| 68 |
+
MAX_KEY + 1
|
| 69 |
+
),
|
| 70 |
+
EncodeError::TooManyUniqueNbt(n) => write!(
|
| 71 |
+
f,
|
| 72 |
+
"уникальных NBT {n}, максимум {MAX_KEY} (номер NBT — 8 цифр в заголовке, 0 — «нет NBT»)"
|
| 73 |
+
),
|
| 74 |
+
EncodeError::EntryTooLong(n) => write!(
|
| 75 |
+
f,
|
| 76 |
+
"запись словаря ({n} символов JSON) не помещается в одну часть"
|
| 77 |
+
),
|
| 78 |
+
EncodeError::InvalidCells => write!(f, "внутренняя ошибка: некорректные ячейки позиций"),
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
impl std::error::Error for EncodeError {}
|
| 84 |
+
|
| 85 |
+
// ---------------------------------------------------------------- ячейки
|
| 86 |
+
|
| 87 |
+
#[inline]
|
| 88 |
+
fn put4(dst: &mut [u8], v: u32) {
|
| 89 |
+
dst[0] = b'0' + (v / 1000 % 10) as u8;
|
| 90 |
+
dst[1] = b'0' + (v / 100 % 10) as u8;
|
| 91 |
+
dst[2] = b'0' + (v / 10 % 10) as u8;
|
| 92 |
+
dst[3] = b'0' + (v % 10) as u8;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/// Ровно 8 цифр с ведущими нулями (v ≤ 99 999 999).
|
| 96 |
+
#[inline]
|
| 97 |
+
fn put8(dst: &mut [u8], mut v: u32) {
|
| 98 |
+
for i in (0..8).rev() {
|
| 99 |
+
dst[i] = b'0' + (v % 10) as u8;
|
| 100 |
+
v /= 10;
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
#[inline]
|
| 105 |
+
fn put_coord(dst: &mut [u8], v: i32) -> Result<(), EncodeError> {
|
| 106 |
+
if !(COORD_MIN..=COORD_MAX).contains(&v) {
|
| 107 |
+
return Err(EncodeError::CoordOutOfRange(v));
|
| 108 |
+
}
|
| 109 |
+
if v >= 0 {
|
| 110 |
+
put4(dst, v as u32);
|
| 111 |
+
} else {
|
| 112 |
+
let a = (-v) as u32;
|
| 113 |
+
dst[0] = b'-';
|
| 114 |
+
dst[1] = b'0' + (a / 100) as u8;
|
| 115 |
+
dst[2] = b'0' + (a / 10 % 10) as u8;
|
| 116 |
+
dst[3] = b'0' + (a % 10) as u8;
|
| 117 |
+
}
|
| 118 |
+
Ok(())
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/// Координата → ровно 4 символа. `-1` → `-001`, `5` → `0005`, `-123` → `-123`.
|
| 122 |
+
pub fn encode_coord(v: i32) -> Result<String, EncodeError> {
|
| 123 |
+
let mut b = [0u8; 4];
|
| 124 |
+
put_coord(&mut b, v)?;
|
| 125 |
+
Ok(String::from_utf8_lossy(&b).into_owned())
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
/// Дописывает ячейку позиции (28 байт). Без форматирования строк — горячий путь.
|
| 129 |
+
#[inline]
|
| 130 |
+
pub fn push_position(buf: &mut Vec<u8>, x: i32, y: i32, z: i32) -> Result<(), EncodeError> {
|
| 131 |
+
let mut cell = *POS_TEMPLATE;
|
| 132 |
+
put_coord(&mut cell[5..9], x)?;
|
| 133 |
+
put_coord(&mut cell[14..18], y)?;
|
| 134 |
+
put_coord(&mut cell[23..27], z)?;
|
| 135 |
+
buf.extend_from_slice(&cell);
|
| 136 |
+
Ok(())
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
fn push_header(buf: &mut Vec<u8>, k: usize, n: usize, l: usize) {
|
| 140 |
+
debug_assert!(k <= MAX_KEY && n <= MAX_KEY && l <= MAX_RUN);
|
| 141 |
+
let mut cell = *HEADER_TEMPLATE;
|
| 142 |
+
put8(&mut cell[0..8], k as u32);
|
| 143 |
+
put8(&mut cell[8..16], n as u32);
|
| 144 |
+
put8(&mut cell[16..24], l as u32);
|
| 145 |
+
buf.extend_from_slice(&cell);
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// ---------------------------------------------------------------- раскладка по частям
|
| 149 |
+
|
| 150 |
+
/// Раскладывает серии по частям (вариант B). Чистая структура без ввода-вывода.
|
| 151 |
+
pub struct Layout {
|
| 152 |
+
text: Vec<u8>,
|
| 153 |
+
part_ends: Vec<usize>,
|
| 154 |
+
cells_in_part: usize,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
impl Layout {
|
| 158 |
+
pub fn with_capacity(bytes: usize) -> Self {
|
| 159 |
+
Layout {
|
| 160 |
+
text: Vec::with_capacity(bytes),
|
| 161 |
+
part_ends: Vec::new(),
|
| 162 |
+
cells_in_part: 0,
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
fn close_part(&mut self) {
|
| 167 |
+
if self.cells_in_part > 0 {
|
| 168 |
+
self.part_ends.push(self.text.len());
|
| 169 |
+
self.cells_in_part = 0;
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
/// Добавляет все позиции блока `k` с NBT `n`. `cells` — ячейки позиций, кратно 28 байт.
|
| 174 |
+
pub fn push_group(&mut self, k: usize, n: usize, cells: &[u8]) {
|
| 175 |
+
debug_assert_eq!(cells.len() % CELL_LEN, 0);
|
| 176 |
+
let count = cells.len() / CELL_LEN;
|
| 177 |
+
let mut done = 0usize;
|
| 178 |
+
while done < count {
|
| 179 |
+
// заголовок + хотя бы одна позиция должны влезть
|
| 180 |
+
if CELLS_PER_PART - self.cells_in_part < 2 {
|
| 181 |
+
self.close_part();
|
| 182 |
+
}
|
| 183 |
+
let space = CELLS_PER_PART - self.cells_in_part;
|
| 184 |
+
let take = (count - done).min(space - 1).min(MAX_RUN);
|
| 185 |
+
push_header(&mut self.text, k, n, take);
|
| 186 |
+
self.text
|
| 187 |
+
.extend_from_slice(&cells[done * CELL_LEN..(done + take) * CELL_LEN]);
|
| 188 |
+
self.cells_in_part += 1 + take;
|
| 189 |
+
done += take;
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/// Текст и конец каждой части (смещение в байтах).
|
| 194 |
+
pub fn finish(mut self) -> (Vec<u8>, Vec<usize>) {
|
| 195 |
+
self.close_part();
|
| 196 |
+
(self.text, self.part_ends)
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/// Часть текста с номером `index` (с нуля). `None` — индекс вне диапазона.
|
| 201 |
+
pub fn text_part<'a>(text: &'a str, part_ends: &[usize], index: usize) -> Option<&'a str> {
|
| 202 |
+
let end = *part_ends.get(index)?;
|
| 203 |
+
let start = if index == 0 { 0 } else { part_ends[index - 1] };
|
| 204 |
+
text.get(start..end)
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
// ---------------------------------------------------------------- кодирование
|
| 208 |
+
|
| 209 |
+
pub struct Encoded {
|
| 210 |
+
pub text: String,
|
| 211 |
+
pub part_ends: Vec<usize>,
|
| 212 |
+
/// Названия блоков по порядку сортировки; индекс = `k`.
|
| 213 |
+
pub blocks: Vec<String>,
|
| 214 |
+
/// SNBT-строки по порядку сортировки; индекс = `n - 1`.
|
| 215 |
+
pub nbt: Vec<String>,
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
/// Влезают ли индексы блоков (с 0) и номера NBT (с 1) в 8 цифр заголовка.
|
| 219 |
+
fn check_key_limits(blocks: usize, nbt: usize) -> Result<(), EncodeError> {
|
| 220 |
+
if blocks > MAX_KEY + 1 {
|
| 221 |
+
return Err(EncodeError::TooManyUniqueBlocks(blocks));
|
| 222 |
+
}
|
| 223 |
+
if nbt > MAX_KEY {
|
| 224 |
+
return Err(EncodeError::TooManyUniqueNbt(nbt));
|
| 225 |
+
}
|
| 226 |
+
Ok(())
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// Группы позиций → текст, границы частей, список блоков и список NBT.
|
| 230 |
+
/// `k` — индекс блока в списке (с 0), `n` — индекс в списке NBT плюс 1
|
| 231 |
+
/// (0 — «нет NBT»). Списки отсортированы, результат детерминирован.
|
| 232 |
+
pub fn encode(groups: &Groups) -> Result<Encoded, EncodeError> {
|
| 233 |
+
if groups
|
| 234 |
+
.values()
|
| 235 |
+
.any(|c| c.is_empty() || c.len() % CELL_LEN != 0)
|
| 236 |
+
{
|
| 237 |
+
return Err(EncodeError::InvalidCells);
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
let mut block_names: Vec<&str> = Vec::new();
|
| 241 |
+
for (name, _) in groups.keys() {
|
| 242 |
+
if block_names.last().copied() != Some(name.as_str()) {
|
| 243 |
+
block_names.push(name.as_str());
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
let nbt_set: BTreeSet<&str> = groups
|
| 248 |
+
.keys()
|
| 249 |
+
.filter(|key| !key.1.is_empty())
|
| 250 |
+
.map(|key| key.1.as_str())
|
| 251 |
+
.collect();
|
| 252 |
+
// По размеру (меньшие первыми, при равенстве — по тексту); индексы в ячейках считаются по этому порядку.
|
| 253 |
+
let mut nbt_list: Vec<&str> = nbt_set.into_iter().collect();
|
| 254 |
+
nbt_list.sort_by_key(|s| s.chars().count());
|
| 255 |
+
let nbt_index: HashMap<&str, usize> = nbt_list.iter().enumerate().map(|(i, s)| (*s, i)).collect();
|
| 256 |
+
check_key_limits(block_names.len(), nbt_list.len())?;
|
| 257 |
+
|
| 258 |
+
let total: usize = groups.values().map(|c| c.len()).sum();
|
| 259 |
+
let mut layout = Layout::with_capacity(total + groups.len() * CELL_LEN * 2 + CELL_LEN * 64);
|
| 260 |
+
for ((name, snbt), cells) in groups {
|
| 261 |
+
let k = block_names
|
| 262 |
+
.binary_search(&name.as_str())
|
| 263 |
+
.map_err(|_| EncodeError::InvalidCells)?;
|
| 264 |
+
let n = if snbt.is_empty() {
|
| 265 |
+
0
|
| 266 |
+
} else {
|
| 267 |
+
let i = *nbt_index
|
| 268 |
+
.get(snbt.as_str())
|
| 269 |
+
.ok_or(EncodeError::InvalidCells)?;
|
| 270 |
+
// слишком большой NBT — tombstone: блок хранит n = 0
|
| 271 |
+
if nbt_entry_json_len(nbt_list[i]) > MAX_NBT_ENTRY {
|
| 272 |
+
0
|
| 273 |
+
} else {
|
| 274 |
+
i + 1
|
| 275 |
+
}
|
| 276 |
+
};
|
| 277 |
+
layout.push_group(k, n, cells);
|
| 278 |
+
}
|
| 279 |
+
let (bytes, part_ends) = layout.finish();
|
| 280 |
+
let text = String::from_utf8(bytes).map_err(|_| EncodeError::InvalidCells)?;
|
| 281 |
+
|
| 282 |
+
let blocks: Vec<String> = block_names.iter().map(|n| n.to_string()).collect();
|
| 283 |
+
// Tombstone — пустая строка (в JSON-списке это число 0), место в списке остаётся.
|
| 284 |
+
let nbt: Vec<String> = nbt_list
|
| 285 |
+
.iter()
|
| 286 |
+
.map(|n| {
|
| 287 |
+
if nbt_entry_json_len(n) > MAX_NBT_ENTRY {
|
| 288 |
+
String::new()
|
| 289 |
+
} else {
|
| 290 |
+
n.to_string()
|
| 291 |
+
}
|
| 292 |
+
})
|
| 293 |
+
.collect();
|
| 294 |
+
|
| 295 |
+
Ok(Encoded {
|
| 296 |
+
text,
|
| 297 |
+
part_ends,
|
| 298 |
+
blocks,
|
| 299 |
+
nbt,
|
| 300 |
+
})
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// ---------------------------------------------------------------- нарезка списков
|
| 304 |
+
|
| 305 |
+
/// Длина элемента в JSON-массиве (символов, с запятой).
|
| 306 |
+
pub fn entry_json_len(e: &str) -> usize {
|
| 307 |
+
Value::String(e.to_string()).to_string().chars().count() + 1
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
/// Тело ответа части списка: `["stone","dirt"]`.
|
| 311 |
+
pub fn list_part_json(entries: &[String]) -> Value {
|
| 312 |
+
Value::Array(entries.iter().map(|e| Value::String(e.clone())).collect())
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
/// Длина NBT-элемента в JSON-массиве: элемент — уже готовый JSON-словарь (символов, с запятой).
|
| 316 |
+
/// Tombstone (пустая строка) — `0,`.
|
| 317 |
+
pub fn nbt_entry_json_len(e: &str) -> usize {
|
| 318 |
+
if e.is_empty() {
|
| 319 |
+
2
|
| 320 |
+
} else {
|
| 321 |
+
e.chars().count() + 1
|
| 322 |
+
}
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
/// Тело ответа части списка NBT: массив словарей `[{"Lock":"key"}, …]`.
|
| 326 |
+
pub fn nbt_part_json(entries: &[String]) -> Value {
|
| 327 |
+
Value::Array(
|
| 328 |
+
entries
|
| 329 |
+
.iter()
|
| 330 |
+
.map(|e| {
|
| 331 |
+
if e.is_empty() {
|
| 332 |
+
Value::from(0)
|
| 333 |
+
} else {
|
| 334 |
+
serde_json::from_str(e).unwrap_or(Value::Null)
|
| 335 |
+
}
|
| 336 |
+
})
|
| 337 |
+
.collect(),
|
| 338 |
+
)
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/// Режет список строк так, чтобы JSON каждой части был ≤ `max_json_chars` символов.
|
| 342 |
+
pub fn split_list(
|
| 343 |
+
entries: &[String],
|
| 344 |
+
max_json_chars: usize,
|
| 345 |
+
) -> Result<Vec<Vec<String>>, EncodeError> {
|
| 346 |
+
split_list_with(entries, max_json_chars, entry_json_len)
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
/// То же для списка NBT-словарей.
|
| 350 |
+
pub fn split_nbt_list(
|
| 351 |
+
entries: &[String],
|
| 352 |
+
max_json_chars: usize,
|
| 353 |
+
) -> Result<Vec<Vec<String>>, EncodeError> {
|
| 354 |
+
split_list_with(entries, max_json_chars, nbt_entry_json_len)
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
fn split_list_with(
|
| 358 |
+
entries: &[String],
|
| 359 |
+
max_json_chars: usize,
|
| 360 |
+
len_of: fn(&str) -> usize,
|
| 361 |
+
) -> Result<Vec<Vec<String>>, EncodeError> {
|
| 362 |
+
let budget = max_json_chars.saturating_sub(DICT_JSON_RESERVE);
|
| 363 |
+
let mut parts: Vec<Vec<String>> = Vec::new();
|
| 364 |
+
let mut current: Vec<String> = Vec::new();
|
| 365 |
+
let mut used = 0usize;
|
| 366 |
+
for e in entries {
|
| 367 |
+
let len = len_of(e);
|
| 368 |
+
if len > budget {
|
| 369 |
+
return Err(EncodeError::EntryTooLong(len));
|
| 370 |
+
}
|
| 371 |
+
if used + len > budget && !current.is_empty() {
|
| 372 |
+
parts.push(std::mem::take(&mut current));
|
| 373 |
+
used = 0;
|
| 374 |
+
}
|
| 375 |
+
current.push(e.clone());
|
| 376 |
+
used += len;
|
| 377 |
+
}
|
| 378 |
+
if !current.is_empty() {
|
| 379 |
+
parts.push(current);
|
| 380 |
+
}
|
| 381 |
+
Ok(parts)
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
#[cfg(test)]
|
| 385 |
+
mod tests {
|
| 386 |
+
use super::*;
|
| 387 |
+
use serde_json::json;
|
| 388 |
+
|
| 389 |
+
// ---- помощники ----
|
| 390 |
+
fn cells(n: usize) -> Vec<u8> {
|
| 391 |
+
let mut b = Vec::new();
|
| 392 |
+
for i in 0..n {
|
| 393 |
+
push_position(&mut b, i as i32, 0, 0).unwrap();
|
| 394 |
+
}
|
| 395 |
+
b
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
fn cv(c: &str) -> i32 {
|
| 399 |
+
if let Some(rest) = c.strip_prefix('-') {
|
| 400 |
+
-rest.parse::<i32>().unwrap()
|
| 401 |
+
} else {
|
| 402 |
+
c.parse().unwrap()
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/// Читает часть так, как её читает клиент: заголовок, затем срез из l ячеек.
|
| 407 |
+
fn runs(part: &str) -> Vec<(usize, usize, Vec<i32>)> {
|
| 408 |
+
assert_eq!(part.len() % CELL_LEN, 0);
|
| 409 |
+
let mut out = Vec::new();
|
| 410 |
+
let mut i = 0;
|
| 411 |
+
while i < part.len() {
|
| 412 |
+
let h = &part[i..i + CELL_LEN];
|
| 413 |
+
assert!(h.bytes().all(|b| b.is_ascii_digit()), "заголовок: {h}");
|
| 414 |
+
assert!(h.ends_with("0000"), "заголовок: {h}");
|
| 415 |
+
let k: usize = h[0..8].parse().unwrap();
|
| 416 |
+
let n: usize = h[8..16].parse().unwrap();
|
| 417 |
+
let l: usize = h[16..24].parse().unwrap();
|
| 418 |
+
i += CELL_LEN;
|
| 419 |
+
let slice = &part[i..i + l * CELL_LEN];
|
| 420 |
+
let xs = (0..l)
|
| 421 |
+
.map(|j| cv(&slice[j * CELL_LEN + 5..j * CELL_LEN + 9]))
|
| 422 |
+
.collect();
|
| 423 |
+
i += l * CELL_LEN;
|
| 424 |
+
out.push((k, n, xs));
|
| 425 |
+
}
|
| 426 |
+
out
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
fn layout(groups: &[(usize, usize, usize)]) -> (String, Vec<usize>) {
|
| 430 |
+
let mut l = Layout::with_capacity(0);
|
| 431 |
+
for &(k, n, count) in groups {
|
| 432 |
+
l.push_group(k, n, &cells(count));
|
| 433 |
+
}
|
| 434 |
+
let (bytes, ends) = l.finish();
|
| 435 |
+
(String::from_utf8(bytes).unwrap(), ends)
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
fn all_parts<'a>(text: &'a str, ends: &[usize]) -> Vec<&'a str> {
|
| 439 |
+
(0..ends.len()).map(|i| text_part(text, ends, i).unwrap()).collect()
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
fn merged(parts: &[&str]) -> BTreeMap<(usize, usize), Vec<i32>> {
|
| 443 |
+
let mut m: BTreeMap<(usize, usize), Vec<i32>> = BTreeMap::new();
|
| 444 |
+
for p in parts {
|
| 445 |
+
for (k, n, xs) in runs(p) {
|
| 446 |
+
m.entry((k, n)).or_default().extend(xs);
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
m
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
// ---- ячейки ----
|
| 453 |
+
#[test]
|
| 454 |
+
fn coord_cells() {
|
| 455 |
+
assert_eq!(encode_coord(0).unwrap(), "0000");
|
| 456 |
+
assert_eq!(encode_coord(5).unwrap(), "0005");
|
| 457 |
+
assert_eq!(encode_coord(123).unwrap(), "0123");
|
| 458 |
+
assert_eq!(encode_coord(-1).unwrap(), "-001");
|
| 459 |
+
assert_eq!(encode_coord(-123).unwrap(), "-123");
|
| 460 |
+
assert_eq!(encode_coord(COORD_MAX).unwrap(), "9999");
|
| 461 |
+
assert_eq!(encode_coord(COORD_MIN).unwrap(), "-999");
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
#[test]
|
| 465 |
+
fn coord_out_of_range() {
|
| 466 |
+
assert_eq!(encode_coord(10_000), Err(EncodeError::CoordOutOfRange(10_000)));
|
| 467 |
+
assert_eq!(encode_coord(-1000), Err(EncodeError::CoordOutOfRange(-1000)));
|
| 468 |
+
assert!(encode_coord(i32::MIN).is_err());
|
| 469 |
+
assert!(encode_coord(i32::MAX).is_err());
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
#[test]
|
| 473 |
+
fn position_cell_format() {
|
| 474 |
+
let mut b = Vec::new();
|
| 475 |
+
push_position(&mut b, 1, -1, 9999).unwrap();
|
| 476 |
+
assert_eq!(b.len(), CELL_LEN);
|
| 477 |
+
assert_eq!(String::from_utf8(b).unwrap(), r#"{'x':0001,'y':-001,'z':9999}"#);
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
#[test]
|
| 481 |
+
fn position_cell_zero_and_min() {
|
| 482 |
+
let mut b = Vec::new();
|
| 483 |
+
push_position(&mut b, 0, -999, 0).unwrap();
|
| 484 |
+
assert_eq!(String::from_utf8(b).unwrap(), r#"{'x':0000,'y':-999,'z':0000}"#);
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
#[test]
|
| 488 |
+
fn position_cell_rejects_range() {
|
| 489 |
+
let mut b = Vec::new();
|
| 490 |
+
assert_eq!(push_position(&mut b, 0, 0, 10_000), Err(EncodeError::CoordOutOfRange(10_000)));
|
| 491 |
+
assert_eq!(push_position(&mut b, -1000, 0, 0), Err(EncodeError::CoordOutOfRange(-1000)));
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
#[test]
|
| 495 |
+
fn header_cell_format() {
|
| 496 |
+
let mut b = Vec::new();
|
| 497 |
+
push_header(&mut b, 12, 3, 456);
|
| 498 |
+
assert_eq!(b.len(), CELL_LEN);
|
| 499 |
+
assert_eq!(
|
| 500 |
+
String::from_utf8(b).unwrap(),
|
| 501 |
+
["00000012", "00000003", "00000456", "0000"].concat()
|
| 502 |
+
);
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
#[test]
|
| 506 |
+
fn header_cell_wide_values() {
|
| 507 |
+
let mut b = Vec::new();
|
| 508 |
+
push_header(&mut b, MAX_KEY, 0, 856);
|
| 509 |
+
assert_eq!(
|
| 510 |
+
String::from_utf8(b).unwrap(),
|
| 511 |
+
["99999999", "00000000", "00000856", "0000"].concat()
|
| 512 |
+
);
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
#[test]
|
| 516 |
+
fn part_size_constants() {
|
| 517 |
+
assert_eq!(PART_CHARS, 23_996);
|
| 518 |
+
assert_eq!(PART_CHARS % CELL_LEN, 0);
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
// ---- раскладка по частям ----
|
| 522 |
+
#[test]
|
| 523 |
+
fn layout_empty() {
|
| 524 |
+
let (text, ends) = layout(&[]);
|
| 525 |
+
assert!(text.is_empty());
|
| 526 |
+
assert!(ends.is_empty());
|
| 527 |
+
assert_eq!(text_part(&text, &ends, 0), None);
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
#[test]
|
| 531 |
+
fn layout_one_position() {
|
| 532 |
+
let (text, ends) = layout(&[(0, 0, 1)]);
|
| 533 |
+
assert_eq!(ends, vec![2 * CELL_LEN]);
|
| 534 |
+
assert_eq!(
|
| 535 |
+
text,
|
| 536 |
+
[
|
| 537 |
+
"00000000",
|
| 538 |
+
"00000000",
|
| 539 |
+
"00000001",
|
| 540 |
+
"0000",
|
| 541 |
+
r#"{'x':0000,'y':0000,'z':0000}"#,
|
| 542 |
+
]
|
| 543 |
+
.concat()
|
| 544 |
+
);
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
#[test]
|
| 548 |
+
fn layout_exactly_one_full_part() {
|
| 549 |
+
let (text, ends) = layout(&[(0, 0, CELLS_PER_PART - 1)]);
|
| 550 |
+
assert_eq!(ends, vec![PART_CHARS]);
|
| 551 |
+
assert_eq!(text.len(), PART_CHARS);
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
#[test]
|
| 555 |
+
fn layout_one_over_splits_run_with_new_header() {
|
| 556 |
+
let (text, ends) = layout(&[(3, 7, CELLS_PER_PART)]);
|
| 557 |
+
assert_eq!(ends, vec![PART_CHARS, PART_CHARS + 2 * CELL_LEN]);
|
| 558 |
+
let parts = all_parts(&text, &ends);
|
| 559 |
+
let r0 = runs(parts[0]);
|
| 560 |
+
let r1 = runs(parts[1]);
|
| 561 |
+
assert_eq!(r0.len(), 1);
|
| 562 |
+
assert_eq!(r1.len(), 1);
|
| 563 |
+
assert_eq!((r0[0].0, r0[0].1, r0[0].2.len()), (3, 7, CELLS_PER_PART - 1));
|
| 564 |
+
assert_eq!((r1[0].0, r1[0].1, r1[0].2.len()), (3, 7, 1));
|
| 565 |
+
let merged = merged(&parts);
|
| 566 |
+
assert_eq!(merged[&(3, 7)], (0..CELLS_PER_PART as i32).collect::<Vec<_>>());
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
#[test]
|
| 570 |
+
fn layout_one_cell_left_closes_part_early() {
|
| 571 |
+
// 1 + 855 = 856 ячеек; остаётся 1 — заголовок с позицией не влезет
|
| 572 |
+
let (text, ends) = layout(&[(0, 0, CELLS_PER_PART - 2), (1, 0, 1)]);
|
| 573 |
+
assert_eq!(ends, vec![(CELLS_PER_PART - 1) * CELL_LEN, (CELLS_PER_PART + 1) * CELL_LEN]);
|
| 574 |
+
let parts = all_parts(&text, &ends);
|
| 575 |
+
assert_eq!(runs(parts[1]), vec![(1, 0, vec![0])]);
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
#[test]
|
| 579 |
+
fn layout_two_cells_left_fit_exactly() {
|
| 580 |
+
// 1 + 854 = 855 ячеек; остаётся 2 — влезает заголовок и одна позиция
|
| 581 |
+
let (_, ends) = layout(&[(0, 0, CELLS_PER_PART - 3), (1, 0, 1)]);
|
| 582 |
+
assert_eq!(ends, vec![PART_CHARS]);
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
#[test]
|
| 586 |
+
fn layout_part_not_closed_when_not_full() {
|
| 587 |
+
let (_, ends) = layout(&[(0, 0, CELLS_PER_PART - 2)]);
|
| 588 |
+
assert_eq!(ends, vec![(CELLS_PER_PART - 1) * CELL_LEN]);
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
#[test]
|
| 592 |
+
fn layout_big_input_parts_are_self_contained() {
|
| 593 |
+
let (text, ends) = layout(&[(0, 0, 3000), (1, 1, 10), (2, 0, 900)]);
|
| 594 |
+
let parts = all_parts(&text, &ends);
|
| 595 |
+
assert!(parts.len() > 3);
|
| 596 |
+
for p in &parts {
|
| 597 |
+
assert!(p.len() <= PART_CHARS);
|
| 598 |
+
assert_eq!(p.len() % CELL_LEN, 0);
|
| 599 |
+
assert!(!runs(p).is_empty()); // каждая часть читается с первого заголовка
|
| 600 |
+
}
|
| 601 |
+
let m = merged(&parts);
|
| 602 |
+
assert_eq!(m[&(0, 0)], (0..3000).collect::<Vec<_>>());
|
| 603 |
+
assert_eq!(m[&(1, 1)], (0..10).collect::<Vec<_>>());
|
| 604 |
+
assert_eq!(m[&(2, 0)], (0..900).collect::<Vec<_>>());
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
#[test]
|
| 608 |
+
fn text_part_bounds() {
|
| 609 |
+
let (text, ends) = layout(&[(0, 0, CELLS_PER_PART)]);
|
| 610 |
+
assert!(text_part(&text, &ends, 0).is_some());
|
| 611 |
+
assert!(text_part(&text, &ends, 1).is_some());
|
| 612 |
+
assert_eq!(text_part(&text, &ends, 2), None);
|
| 613 |
+
assert_eq!(text_part(&text, &ends, usize::MAX), None);
|
| 614 |
+
assert_eq!(text_part(&text, &ends, 0).unwrap().len(), PART_CHARS);
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
// ---- encode ----
|
| 618 |
+
fn group(cells_n: usize) -> Vec<u8> {
|
| 619 |
+
cells(cells_n)
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
#[test]
|
| 623 |
+
fn encode_empty() {
|
| 624 |
+
let e = encode(&Groups::new()).unwrap();
|
| 625 |
+
assert!(e.text.is_empty());
|
| 626 |
+
assert!(e.part_ends.is_empty());
|
| 627 |
+
assert!(e.blocks.is_empty());
|
| 628 |
+
assert!(e.nbt.is_empty());
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
#[test]
|
| 632 |
+
fn encode_assigns_keys_in_sorted_order() {
|
| 633 |
+
let mut g = Groups::new();
|
| 634 |
+
g.insert(("minecraft:dirt".into(), String::new()), group(2));
|
| 635 |
+
g.insert(("minecraft:chest".into(), r#"{id:"c"}"#.into()), group(1));
|
| 636 |
+
g.insert(("minecraft:chest".into(), r#"{id:"a"}"#.into()), group(1));
|
| 637 |
+
let e = encode(&g).unwrap();
|
| 638 |
+
assert_eq!(e.blocks, vec!["minecraft:chest", "minecraft:dirt"]);
|
| 639 |
+
assert_eq!(e.nbt, vec![r#"{id:"a"}"#, r#"{id:"c"}"#]);
|
| 640 |
+
assert_eq!(e.part_ends.len(), 1);
|
| 641 |
+
let r = runs(&e.text);
|
| 642 |
+
assert_eq!(r, vec![(0, 1, vec![0]), (0, 2, vec![0]), (1, 0, vec![0, 1])]);
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
#[test]
|
| 646 |
+
fn nbt_sorted_by_size_and_indices_follow() {
|
| 647 |
+
let mut g = Groups::new();
|
| 648 |
+
g.insert(("a".into(), r#"{"k":"long long"}"#.into()), group(1));
|
| 649 |
+
g.insert(("b".into(), r#"{"k":"s"}"#.into()), group(1));
|
| 650 |
+
let e = encode(&g).unwrap();
|
| 651 |
+
assert_eq!(e.nbt, vec![r#"{"k":"s"}"#, r#"{"k":"long long"}"#]);
|
| 652 |
+
let r = runs(&e.text);
|
| 653 |
+
assert_eq!(r, vec![(0, 2, vec![0]), (1, 1, vec![0])]);
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
#[test]
|
| 657 |
+
fn oversized_nbt_becomes_tombstone() {
|
| 658 |
+
let big = format!(r#"{{"k":"{}"}}"#, "x".repeat(DICT_PART_JSON_MAX));
|
| 659 |
+
let mut g = Groups::new();
|
| 660 |
+
g.insert(("a".into(), r#"{"k":"s"}"#.into()), group(1));
|
| 661 |
+
g.insert(("b".into(), big), group(1));
|
| 662 |
+
let e = encode(&g).unwrap();
|
| 663 |
+
assert_eq!(e.nbt, vec![r#"{"k":"s"}"#.to_string(), String::new()]);
|
| 664 |
+
let r = runs(&e.text);
|
| 665 |
+
assert_eq!(r, vec![(0, 1, vec![0]), (1, 0, vec![0])]);
|
| 666 |
+
let parts = split_nbt_list(&e.nbt, DICT_PART_JSON_MAX).unwrap();
|
| 667 |
+
assert_eq!(nbt_part_json(&parts[0]), json!([{ "k": "s" }, 0]));
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
#[test]
|
| 671 |
+
fn nbt_that_does_not_fit_goes_to_next_part() {
|
| 672 |
+
let a = format!(r#"{{"k":"{}"}}"#, "x".repeat(15_000));
|
| 673 |
+
let b = format!(r#"{{"k":"{}"}}"#, "y".repeat(15_000));
|
| 674 |
+
let parts = split_nbt_list(&[a, b], DICT_PART_JSON_MAX).unwrap();
|
| 675 |
+
assert_eq!(parts.len(), 2);
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
#[test]
|
| 679 |
+
fn encode_is_deterministic() {
|
| 680 |
+
let mut g = Groups::new();
|
| 681 |
+
g.insert(("b".into(), String::new()), group(3));
|
| 682 |
+
g.insert(("a".into(), String::new()), group(2));
|
| 683 |
+
let e1 = encode(&g).unwrap();
|
| 684 |
+
let e2 = encode(&g).unwrap();
|
| 685 |
+
assert_eq!(e1.text, e2.text);
|
| 686 |
+
assert_eq!(e1.part_ends, e2.part_ends);
|
| 687 |
+
assert_eq!(e1.blocks[0], "a");
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
#[test]
|
| 691 |
+
fn encode_rejects_bad_cells() {
|
| 692 |
+
let mut g = Groups::new();
|
| 693 |
+
g.insert(("a".into(), String::new()), vec![0u8; CELL_LEN - 1]);
|
| 694 |
+
assert!(matches!(encode(&g), Err(EncodeError::InvalidCells)));
|
| 695 |
+
let mut g = Groups::new();
|
| 696 |
+
g.insert(("a".into(), String::new()), Vec::new());
|
| 697 |
+
assert!(matches!(encode(&g), Err(EncodeError::InvalidCells)));
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
#[test]
|
| 701 |
+
fn key_limits() {
|
| 702 |
+
assert!(check_key_limits(MAX_KEY + 1, MAX_KEY).is_ok());
|
| 703 |
+
assert_eq!(
|
| 704 |
+
check_key_limits(MAX_KEY + 2, 0),
|
| 705 |
+
Err(EncodeError::TooManyUniqueBlocks(MAX_KEY + 2))
|
| 706 |
+
);
|
| 707 |
+
assert_eq!(
|
| 708 |
+
check_key_limits(0, MAX_KEY + 1),
|
| 709 |
+
Err(EncodeError::TooManyUniqueNbt(MAX_KEY + 1))
|
| 710 |
+
);
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
#[test]
|
| 714 |
+
fn many_unique_blocks_use_wide_keys() {
|
| 715 |
+
let mut g = Groups::new();
|
| 716 |
+
for i in 0..10_001 {
|
| 717 |
+
g.insert((format!("b{i:05}"), String::new()), group(1));
|
| 718 |
+
}
|
| 719 |
+
let e = encode(&g).unwrap();
|
| 720 |
+
assert_eq!(e.blocks.len(), 10_001);
|
| 721 |
+
let parts = all_parts(&e.text, &e.part_ends);
|
| 722 |
+
let m = merged(&parts);
|
| 723 |
+
assert_eq!(m.len(), 10_001);
|
| 724 |
+
assert!(m.contains_key(&(10_000, 0)));
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
// ---- списки ----
|
| 728 |
+
fn entries(n: usize, value_len: usize) -> Vec<String> {
|
| 729 |
+
(0..n)
|
| 730 |
+
.map(|i| format!("{:0>width$}", i, width = value_len))
|
| 731 |
+
.collect()
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
fn json_len(part: &[String]) -> usize {
|
| 735 |
+
list_part_json(part).to_string().chars().count()
|
| 736 |
+
}
|
| 737 |
+
|
| 738 |
+
#[test]
|
| 739 |
+
fn list_json_shape() {
|
| 740 |
+
let e = vec!["stone".to_string(), "dirt".to_string()];
|
| 741 |
+
assert_eq!(list_part_json(&e), json!(["stone", "dirt"]));
|
| 742 |
+
assert_eq!(list_part_json(&e).to_string(), r#"["stone","dirt"]"#);
|
| 743 |
+
assert_eq!(list_part_json(&[]), json!([]));
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
#[test]
|
| 747 |
+
fn split_list_empty() {
|
| 748 |
+
assert!(split_list(&[], DICT_PART_JSON_MAX).unwrap().is_empty());
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
#[test]
|
| 752 |
+
fn split_list_single_part() {
|
| 753 |
+
let e = entries(10, 20);
|
| 754 |
+
let parts = split_list(&e, DICT_PART_JSON_MAX).unwrap();
|
| 755 |
+
assert_eq!(parts, vec![e]);
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
#[test]
|
| 759 |
+
fn split_list_respects_limit_and_keeps_order() {
|
| 760 |
+
let e = entries(3000, 40);
|
| 761 |
+
let parts = split_list(&e, DICT_PART_JSON_MAX).unwrap();
|
| 762 |
+
assert!(parts.len() > 1);
|
| 763 |
+
for (i, p) in parts.iter().enumerate() {
|
| 764 |
+
assert!(!p.is_empty());
|
| 765 |
+
assert!(json_len(p) <= DICT_PART_JSON_MAX, "часть {i}: {}", json_len(p));
|
| 766 |
+
}
|
| 767 |
+
let flat: Vec<String> = parts.into_iter().flatten().collect();
|
| 768 |
+
assert_eq!(flat, e);
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
#[test]
|
| 772 |
+
fn split_list_small_limit_boundary() {
|
| 773 |
+
let e = entries(5, 10);
|
| 774 |
+
let one = entry_json_len(&e[0]);
|
| 775 |
+
assert_eq!(split_list(&e, DICT_JSON_RESERVE + one).unwrap().len(), 5);
|
| 776 |
+
assert_eq!(split_list(&e, DICT_JSON_RESERVE + one * 2).unwrap().len(), 3);
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
#[test]
|
| 780 |
+
fn split_list_json_never_exceeds_limit() {
|
| 781 |
+
let e = entries(20, 5);
|
| 782 |
+
for max in 10..300 {
|
| 783 |
+
if let Ok(parts) = split_list(&e, max) {
|
| 784 |
+
for p in &parts {
|
| 785 |
+
assert!(json_len(p) <= max, "лимит {max}: {}", json_len(p));
|
| 786 |
+
}
|
| 787 |
+
}
|
| 788 |
+
}
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
#[test]
|
| 792 |
+
fn split_list_entry_too_long() {
|
| 793 |
+
let e = vec!["x".repeat(30_000)];
|
| 794 |
+
assert!(matches!(
|
| 795 |
+
split_list(&e, DICT_PART_JSON_MAX),
|
| 796 |
+
Err(EncodeError::EntryTooLong(_))
|
| 797 |
+
));
|
| 798 |
+
}
|
| 799 |
+
}
|
http.rs
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, Path, RawQuery, State},
|
| 10 |
+
http::StatusCode,
|
| 11 |
+
response::{IntoResponse, Response},
|
| 12 |
+
routing::{get, post},
|
| 13 |
+
Json, Router,
|
| 14 |
+
};
|
| 15 |
+
use serde_json::{json, Value};
|
| 16 |
+
use tracing::{info, warn};
|
| 17 |
+
use uuid::Uuid;
|
| 18 |
+
|
| 19 |
+
use crate::encoder;
|
| 20 |
+
use crate::loader::{self, LoaderConfig};
|
| 21 |
+
use crate::nbt;
|
| 22 |
+
use crate::store::{Schematic, Store};
|
| 23 |
+
|
| 24 |
+
/// Жёсткий срок на весь `/upload` (скачивание + разбор + кодирование).
|
| 25 |
+
/// Меньше клиентского таймаута в 3 с: клиент всегда получает ответ.
|
| 26 |
+
pub const UPLOAD_DEADLINE: Duration = Duration::from_millis(2500);
|
| 27 |
+
|
| 28 |
+
#[derive(Clone)]
|
| 29 |
+
pub struct AppState {
|
| 30 |
+
pub store: Store,
|
| 31 |
+
pub client: reqwest::Client,
|
| 32 |
+
pub loader: Arc<LoaderConfig>,
|
| 33 |
+
pub deadline: Duration,
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
impl AppState {
|
| 37 |
+
pub fn new(store: Store, client: reqwest::Client, loader: LoaderConfig) -> Self {
|
| 38 |
+
AppState {
|
| 39 |
+
store,
|
| 40 |
+
client,
|
| 41 |
+
loader: Arc::new(loader),
|
| 42 |
+
deadline: UPLOAD_DEADLINE,
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
#[derive(Debug)]
|
| 48 |
+
pub enum ApiError {
|
| 49 |
+
BadRequest(String),
|
| 50 |
+
NotFound(String),
|
| 51 |
+
Internal(String),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
impl IntoResponse for ApiError {
|
| 55 |
+
fn into_response(self) -> Response {
|
| 56 |
+
let (status, message) = match self {
|
| 57 |
+
ApiError::BadRequest(m) => (StatusCode::BAD_REQUEST, m),
|
| 58 |
+
ApiError::NotFound(m) => (StatusCode::NOT_FOUND, m),
|
| 59 |
+
ApiError::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),
|
| 60 |
+
};
|
| 61 |
+
(status, Json(json!({ "error": message }))).into_response()
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
pub fn router(state: AppState) -> Router {
|
| 66 |
+
Router::new()
|
| 67 |
+
.route("/", get(index))
|
| 68 |
+
.route("/upload", post(upload))
|
| 69 |
+
.route("/get/:uuid/blocks", get(blocks_info))
|
| 70 |
+
.route("/get/:uuid/blocks/:index", get(blocks_part))
|
| 71 |
+
.route("/get/:uuid/nbt", get(nbt_info))
|
| 72 |
+
.route("/get/:uuid/nbt/:index", get(nbt_part))
|
| 73 |
+
.route("/get/:uuid/parts", get(parts_info))
|
| 74 |
+
.route("/get/:uuid/parts/:index", get(parts_part))
|
| 75 |
+
.route("/:uuid/status", get(status))
|
| 76 |
+
.route("/get/:uuid/status", get(status))
|
| 77 |
+
// тело /upload — одна ссылка
|
| 78 |
+
.layer(DefaultBodyLimit::max(16 * 1024))
|
| 79 |
+
.with_state(state)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
fn parse_uuid(s: &str) -> Result<Uuid, ApiError> {
|
| 83 |
+
Uuid::parse_str(s).map_err(|_| ApiError::BadRequest(format!("некорректный UUID: {s}")))
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
fn parse_index(s: &str) -> Result<usize, ApiError> {
|
| 87 |
+
s.parse::<usize>()
|
| 88 |
+
.map_err(|_| ApiError::BadRequest(format!("некорректный индекс: {s}")))
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
fn find(state: &AppState, uuid: &str) -> Result<Arc<Schematic>, ApiError> {
|
| 92 |
+
let id = parse_uuid(uuid)?;
|
| 93 |
+
state
|
| 94 |
+
.store
|
| 95 |
+
.get(&id)
|
| 96 |
+
.ok_or_else(|| ApiError::NotFound("схематика с таким UUID не найдена".into()))
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
fn out_of_range(index: usize) -> ApiError {
|
| 100 |
+
ApiError::NotFound(format!("индекс {index} вне диапазона"))
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
async fn index() -> Json<Value> {
|
| 104 |
+
Json(json!({
|
| 105 |
+
"service": "litematic-host",
|
| 106 |
+
"endpoints": [
|
| 107 |
+
"POST /upload?x=0&y=0&z=0",
|
| 108 |
+
"GET /get/{uuid}/blocks",
|
| 109 |
+
"GET /get/{uuid}/blocks/{index}",
|
| 110 |
+
"GET /get/{uuid}/nbt",
|
| 111 |
+
"GET /get/{uuid}/nbt/{index}",
|
| 112 |
+
"GET /get/{uuid}/parts",
|
| 113 |
+
"GET /get/{uuid}/parts/{index}",
|
| 114 |
+
"GET /{uuid}/status",
|
| 115 |
+
],
|
| 116 |
+
}))
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/// Сдвиг из query-строки `/upload?x=..&y=..&z=..`. Нет параметра — 0.
|
| 120 |
+
/// Неизвестные параметры игнорируются. Повтор параметра — побеждает последний.
|
| 121 |
+
fn parse_offset(query: Option<&str>) -> Result<[i32; 3], ApiError> {
|
| 122 |
+
let mut offset = [0i32; 3];
|
| 123 |
+
let Some(q) = query else {
|
| 124 |
+
return Ok(offset);
|
| 125 |
+
};
|
| 126 |
+
for pair in q.split('&').filter(|p| !p.is_empty()) {
|
| 127 |
+
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
| 128 |
+
let slot = match key {
|
| 129 |
+
"x" => 0,
|
| 130 |
+
"y" => 1,
|
| 131 |
+
"z" => 2,
|
| 132 |
+
_ => continue,
|
| 133 |
+
};
|
| 134 |
+
offset[slot] = value.parse::<i32>().map_err(|_| {
|
| 135 |
+
ApiError::BadRequest(format!(
|
| 136 |
+
"параметр {key} должен быть целым числом i32, получено: {value:?}"
|
| 137 |
+
))
|
| 138 |
+
})?;
|
| 139 |
+
}
|
| 140 |
+
Ok(offset)
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/// Скачивание + разбор + кодирование. Без таймаута — его ставит вызывающий.
|
| 144 |
+
async fn process(
|
| 145 |
+
state: &AppState,
|
| 146 |
+
url: reqwest::Url,
|
| 147 |
+
offset: [i32; 3],
|
| 148 |
+
cancel: Arc<AtomicBool>,
|
| 149 |
+
) -> Result<Schematic, ApiError> {
|
| 150 |
+
let data = loader::download(&state.client, url, &state.loader)
|
| 151 |
+
.await
|
| 152 |
+
.map_err(|e| {
|
| 153 |
+
warn!(error = %e, "ошибка скачивания");
|
| 154 |
+
ApiError::BadRequest(e.to_string())
|
| 155 |
+
})?;
|
| 156 |
+
info!(bytes = data.len(), "файл скачан, разбор");
|
| 157 |
+
|
| 158 |
+
// CPU-работа уходит с async-потока. Поток нельзя отменить снаружи,
|
| 159 |
+
// поэтому он сам проверяет флаг `cancel` на каждом слое по y.
|
| 160 |
+
tokio::task::spawn_blocking(move || -> Result<Schematic, String> {
|
| 161 |
+
let groups = nbt::parse_litematic_gz(&data, &nbt::Limits::default(), offset, &cancel)
|
| 162 |
+
.map_err(|e| e.to_string())?;
|
| 163 |
+
Schematic::build(&groups).map_err(|e| e.to_string())
|
| 164 |
+
})
|
| 165 |
+
.await
|
| 166 |
+
.map_err(|e| ApiError::Internal(format!("внутренняя ошибка: {e}")))?
|
| 167 |
+
.map_err(|e| {
|
| 168 |
+
warn!(error = %e, "ошибка разбора");
|
| 169 |
+
ApiError::BadRequest(e)
|
| 170 |
+
})
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
async fn upload(
|
| 174 |
+
State(state): State<AppState>,
|
| 175 |
+
RawQuery(query): RawQuery,
|
| 176 |
+
body: Bytes,
|
| 177 |
+
) -> Result<Json<String>, ApiError> {
|
| 178 |
+
let offset = parse_offset(query.as_deref())?;
|
| 179 |
+
let text = std::str::from_utf8(&body)
|
| 180 |
+
.map_err(|_| ApiError::BadRequest("тело запроса должно быть текстом UTF-8 со ссылкой".into()))?;
|
| 181 |
+
let url = loader::parse_url(text).map_err(|e| ApiError::BadRequest(e.to_string()))?;
|
| 182 |
+
let host = url.host_str().unwrap_or("?").to_string();
|
| 183 |
+
info!(%host, ?offset, "загрузка");
|
| 184 |
+
|
| 185 |
+
let started = Instant::now();
|
| 186 |
+
let cancel = Arc::new(AtomicBool::new(false));
|
| 187 |
+
let schematic = match tokio::time::timeout(state.deadline, process(&state, url, offset, cancel.clone())).await {
|
| 188 |
+
Ok(result) => result?,
|
| 189 |
+
Err(_) => {
|
| 190 |
+
cancel.store(true, Ordering::Relaxed);
|
| 191 |
+
warn!(%host, "не уложились в срок");
|
| 192 |
+
return Err(ApiError::BadRequest(format!(
|
| 193 |
+
"обработка не уложилась в {} мс: файл слишком большой или источник слишком медленный",
|
| 194 |
+
state.deadline.as_millis()
|
| 195 |
+
)));
|
| 196 |
+
}
|
| 197 |
+
};
|
| 198 |
+
|
| 199 |
+
let unique = schematic.unique_blocks;
|
| 200 |
+
let parts = schematic.part_ends.len();
|
| 201 |
+
let id = state.store.insert(schematic);
|
| 202 |
+
info!(
|
| 203 |
+
%id,
|
| 204 |
+
unique_blocks = unique,
|
| 205 |
+
parts,
|
| 206 |
+
elapsed_ms = started.elapsed().as_millis() as u64,
|
| 207 |
+
"схематика сохранена"
|
| 208 |
+
);
|
| 209 |
+
Ok(Json(id.to_string()))
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
async fn blocks_info(
|
| 213 |
+
State(state): State<AppState>,
|
| 214 |
+
Path(uuid): Path<String>,
|
| 215 |
+
) -> Result<Json<Value>, ApiError> {
|
| 216 |
+
let s = find(&state, &uuid)?;
|
| 217 |
+
Ok(Json(json!({
|
| 218 |
+
"unique_blocks": s.unique_blocks,
|
| 219 |
+
"parts": s.block_parts.len(),
|
| 220 |
+
})))
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
async fn blocks_part(
|
| 224 |
+
State(state): State<AppState>,
|
| 225 |
+
Path((uuid, index)): Path<(String, String)>,
|
| 226 |
+
) -> Result<Json<Value>, ApiError> {
|
| 227 |
+
let s = find(&state, &uuid)?;
|
| 228 |
+
let i = parse_index(&index)?;
|
| 229 |
+
let part = s.block_parts.get(i).ok_or_else(|| out_of_range(i))?;
|
| 230 |
+
Ok(Json(encoder::list_part_json(part)))
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
async fn nbt_info(
|
| 234 |
+
State(state): State<AppState>,
|
| 235 |
+
Path(uuid): Path<String>,
|
| 236 |
+
) -> Result<Json<Value>, ApiError> {
|
| 237 |
+
let s = find(&state, &uuid)?;
|
| 238 |
+
Ok(Json(json!({
|
| 239 |
+
"unique_nbt": s.unique_nbt,
|
| 240 |
+
"parts": s.nbt_parts.len(),
|
| 241 |
+
})))
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
async fn nbt_part(
|
| 245 |
+
State(state): State<AppState>,
|
| 246 |
+
Path((uuid, index)): Path<(String, String)>,
|
| 247 |
+
) -> Result<Json<Value>, ApiError> {
|
| 248 |
+
let s = find(&state, &uuid)?;
|
| 249 |
+
let i = parse_index(&index)?;
|
| 250 |
+
let part = s.nbt_parts.get(i).ok_or_else(|| out_of_range(i))?;
|
| 251 |
+
Ok(Json(encoder::nbt_part_json(part)))
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
async fn parts_info(
|
| 255 |
+
State(state): State<AppState>,
|
| 256 |
+
Path(uuid): Path<String>,
|
| 257 |
+
) -> Result<Json<Value>, ApiError> {
|
| 258 |
+
let s = find(&state, &uuid)?;
|
| 259 |
+
Ok(Json(json!({ "parts": s.part_ends.len() })))
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
async fn parts_part(
|
| 263 |
+
State(state): State<AppState>,
|
| 264 |
+
Path((uuid, index)): Path<(String, String)>,
|
| 265 |
+
) -> Result<Json<Value>, ApiError> {
|
| 266 |
+
let s = find(&state, &uuid)?;
|
| 267 |
+
let i = parse_index(&index)?;
|
| 268 |
+
let chunk = encoder::text_part(&s.text, &s.part_ends, i).ok_or_else(|| out_of_range(i))?;
|
| 269 |
+
Ok(Json(json!({ "index": i, "data": chunk })))
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
/// Схематика разбирается прямо в `/upload`, поэтому любая найденная — готова.
|
| 273 |
+
async fn status(
|
| 274 |
+
State(state): State<AppState>,
|
| 275 |
+
Path(uuid): Path<String>,
|
| 276 |
+
) -> Result<Json<Value>, ApiError> {
|
| 277 |
+
let s = find(&state, &uuid)?;
|
| 278 |
+
Ok(Json(json!({
|
| 279 |
+
"status": "ready",
|
| 280 |
+
"unique_blocks": s.unique_blocks,
|
| 281 |
+
"unique_nbt": s.unique_nbt,
|
| 282 |
+
"blocks_parts": s.block_parts.len(),
|
| 283 |
+
"nbt_parts": s.nbt_parts.len(),
|
| 284 |
+
"parts": s.part_ends.len(),
|
| 285 |
+
"text_chars": s.text.len(),
|
| 286 |
+
})))
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
#[cfg(test)]
|
| 290 |
+
mod tests {
|
| 291 |
+
use super::*;
|
| 292 |
+
use crate::encoder::Groups;
|
| 293 |
+
use axum::body::Body;
|
| 294 |
+
use axum::http::Request;
|
| 295 |
+
use http_body_util::BodyExt;
|
| 296 |
+
use tower::ServiceExt;
|
| 297 |
+
|
| 298 |
+
fn app() -> (Router, AppState) {
|
| 299 |
+
let cfg = LoaderConfig::default();
|
| 300 |
+
let client = loader::build_client(&cfg).unwrap();
|
| 301 |
+
let state = AppState::new(Store::default(), client, cfg);
|
| 302 |
+
(router(state.clone()), state)
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
async fn call(app: &Router, req: Request<Body>) -> (StatusCode, String) {
|
| 306 |
+
let resp = app.clone().oneshot(req).await.unwrap();
|
| 307 |
+
let status = resp.status();
|
| 308 |
+
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
| 309 |
+
(status, String::from_utf8(bytes.to_vec()).unwrap())
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
async fn get_json(app: &Router, uri: &str) -> (StatusCode, Value) {
|
| 313 |
+
let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
|
| 314 |
+
let (status, body) = call(app, req).await;
|
| 315 |
+
(status, serde_json::from_str(&body).unwrap())
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
fn cells(list: &[(i32, i32, i32)]) -> Vec<u8> {
|
| 319 |
+
let mut b = Vec::new();
|
| 320 |
+
for &(x, y, z) in list {
|
| 321 |
+
encoder::push_position(&mut b, x, y, z).unwrap();
|
| 322 |
+
}
|
| 323 |
+
b
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
fn header(k: usize, n: usize, l: usize) -> String {
|
| 327 |
+
format!("{k:08}{n:08}{l:08}0000")
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
fn pos(x: &str, y: &str, z: &str) -> String {
|
| 331 |
+
format!(r#"{{'x':{x},'y':{y},'z':{z}}}"#)
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
/// chest с NBT в (1,1,1); dirt в (5,5,5); stone в (0,0,0) и (-1,2,3).
|
| 335 |
+
fn sample_groups() -> Groups {
|
| 336 |
+
let mut g = Groups::new();
|
| 337 |
+
g.insert(
|
| 338 |
+
("chest".into(), r#"{"Lock":"key"}"#.into()),
|
| 339 |
+
cells(&[(1, 1, 1)]),
|
| 340 |
+
);
|
| 341 |
+
g.insert(("dirt".into(), String::new()), cells(&[(5, 5, 5)]));
|
| 342 |
+
g.insert(
|
| 343 |
+
("stone".into(), String::new()),
|
| 344 |
+
cells(&[(0, 0, 0), (-1, 2, 3)]),
|
| 345 |
+
);
|
| 346 |
+
g
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
fn sample_id(state: &AppState) -> Uuid {
|
| 350 |
+
state.store.insert(Schematic::build(&sample_groups()).unwrap())
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
#[tokio::test]
|
| 354 |
+
async fn full_read_cycle() {
|
| 355 |
+
let (app, state) = app();
|
| 356 |
+
let id = sample_id(&state);
|
| 357 |
+
|
| 358 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/blocks")).await;
|
| 359 |
+
assert_eq!(st, StatusCode::OK);
|
| 360 |
+
assert_eq!(v, json!({ "unique_blocks": 3, "parts": 1 }));
|
| 361 |
+
|
| 362 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/blocks/0")).await;
|
| 363 |
+
assert_eq!(st, StatusCode::OK);
|
| 364 |
+
assert_eq!(v, json!(["chest", "dirt", "stone"]));
|
| 365 |
+
|
| 366 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/nbt")).await;
|
| 367 |
+
assert_eq!(st, StatusCode::OK);
|
| 368 |
+
assert_eq!(v, json!({ "unique_nbt": 1, "parts": 1 }));
|
| 369 |
+
|
| 370 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/nbt/0")).await;
|
| 371 |
+
assert_eq!(st, StatusCode::OK);
|
| 372 |
+
assert_eq!(v, json!([{ "Lock": "key" }]));
|
| 373 |
+
|
| 374 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/parts")).await;
|
| 375 |
+
assert_eq!(st, StatusCode::OK);
|
| 376 |
+
assert_eq!(v, json!({ "parts": 1 }));
|
| 377 |
+
|
| 378 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/parts/0")).await;
|
| 379 |
+
assert_eq!(st, StatusCode::OK);
|
| 380 |
+
let expected = [
|
| 381 |
+
header(0, 1, 1),
|
| 382 |
+
pos("0001", "0001", "0001"),
|
| 383 |
+
header(1, 0, 1),
|
| 384 |
+
pos("0005", "0005", "0005"),
|
| 385 |
+
header(2, 0, 2),
|
| 386 |
+
pos("0000", "0000", "0000"),
|
| 387 |
+
pos("-001", "0002", "0003"),
|
| 388 |
+
]
|
| 389 |
+
.concat();
|
| 390 |
+
assert_eq!(v["index"], 0);
|
| 391 |
+
assert_eq!(v["data"], json!(expected));
|
| 392 |
+
assert_eq!(expected.len(), 7 * 28);
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
#[tokio::test]
|
| 396 |
+
async fn index_out_of_range_is_404() {
|
| 397 |
+
let (app, state) = app();
|
| 398 |
+
let id = sample_id(&state);
|
| 399 |
+
for tail in ["blocks/1", "nbt/1", "parts/1"] {
|
| 400 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/{tail}")).await;
|
| 401 |
+
assert_eq!(st, StatusCode::NOT_FOUND, "{tail}");
|
| 402 |
+
assert!(v["error"].is_string());
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
#[tokio::test]
|
| 407 |
+
async fn unknown_uuid_is_404() {
|
| 408 |
+
let (app, _) = app();
|
| 409 |
+
let id = Uuid::new_v4();
|
| 410 |
+
for tail in ["blocks", "blocks/0", "nbt", "nbt/0", "parts", "parts/0"] {
|
| 411 |
+
let (st, _) = get_json(&app, &format!("/get/{id}/{tail}")).await;
|
| 412 |
+
assert_eq!(st, StatusCode::NOT_FOUND, "{tail}");
|
| 413 |
+
}
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
#[tokio::test]
|
| 417 |
+
async fn bad_uuid_is_400() {
|
| 418 |
+
let (app, _) = app();
|
| 419 |
+
for tail in ["blocks", "blocks/0", "nbt", "nbt/0", "parts", "parts/0"] {
|
| 420 |
+
let (st, _) = get_json(&app, &format!("/get/not-a-uuid/{tail}")).await;
|
| 421 |
+
assert_eq!(st, StatusCode::BAD_REQUEST, "{tail}");
|
| 422 |
+
}
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
#[tokio::test]
|
| 426 |
+
async fn status_endpoint() {
|
| 427 |
+
let (app, state) = app();
|
| 428 |
+
let id = sample_id(&state);
|
| 429 |
+
for uri in [format!("/{id}/status"), format!("/get/{id}/status")] {
|
| 430 |
+
let (st, v) = get_json(&app, &uri).await;
|
| 431 |
+
assert_eq!(st, StatusCode::OK, "{uri}");
|
| 432 |
+
assert_eq!(
|
| 433 |
+
v,
|
| 434 |
+
json!({
|
| 435 |
+
"status": "ready",
|
| 436 |
+
"unique_blocks": 3,
|
| 437 |
+
"unique_nbt": 1,
|
| 438 |
+
"blocks_parts": 1,
|
| 439 |
+
"nbt_parts": 1,
|
| 440 |
+
"parts": 1,
|
| 441 |
+
"text_chars": 196,
|
| 442 |
+
})
|
| 443 |
+
);
|
| 444 |
+
}
|
| 445 |
+
let (st, _) = get_json(&app, &format!("/{}/status", Uuid::new_v4())).await;
|
| 446 |
+
assert_eq!(st, StatusCode::NOT_FOUND);
|
| 447 |
+
let (st, _) = get_json(&app, "/not-a-uuid/status").await;
|
| 448 |
+
assert_eq!(st, StatusCode::BAD_REQUEST);
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
#[tokio::test]
|
| 452 |
+
async fn bad_index_is_400() {
|
| 453 |
+
let (app, state) = app();
|
| 454 |
+
let id = sample_id(&state);
|
| 455 |
+
let (st, _) = get_json(&app, &format!("/get/{id}/parts/abc")).await;
|
| 456 |
+
assert_eq!(st, StatusCode::BAD_REQUEST);
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
#[tokio::test]
|
| 460 |
+
async fn empty_schematic_has_zero_parts() {
|
| 461 |
+
let (app, state) = app();
|
| 462 |
+
let id = state.store.insert(Schematic::build(&Groups::new()).unwrap());
|
| 463 |
+
let (_, v) = get_json(&app, &format!("/get/{id}/blocks")).await;
|
| 464 |
+
assert_eq!(v, json!({ "unique_blocks": 0, "parts": 0 }));
|
| 465 |
+
let (_, v) = get_json(&app, &format!("/get/{id}/nbt")).await;
|
| 466 |
+
assert_eq!(v, json!({ "unique_nbt": 0, "parts": 0 }));
|
| 467 |
+
let (_, v) = get_json(&app, &format!("/get/{id}/parts")).await;
|
| 468 |
+
assert_eq!(v, json!({ "parts": 0 }));
|
| 469 |
+
let (st, _) = get_json(&app, &format!("/get/{id}/parts/0")).await;
|
| 470 |
+
assert_eq!(st, StatusCode::NOT_FOUND);
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
#[tokio::test]
|
| 474 |
+
async fn long_run_is_split_across_parts_with_new_headers() {
|
| 475 |
+
let (app, state) = app();
|
| 476 |
+
let mut g = Groups::new();
|
| 477 |
+
let list: Vec<(i32, i32, i32)> = (0..2000).map(|i| (i, 0, 0)).collect();
|
| 478 |
+
g.insert(("stone".into(), String::new()), cells(&list));
|
| 479 |
+
let id = state.store.insert(Schematic::build(&g).unwrap());
|
| 480 |
+
|
| 481 |
+
let (_, v) = get_json(&app, &format!("/get/{id}/parts")).await;
|
| 482 |
+
assert_eq!(v, json!({ "parts": 3 }));
|
| 483 |
+
|
| 484 |
+
// 856 + 856 + 288 позиций, перед каждой серией свой заголовок
|
| 485 |
+
let sizes = [857 * 28, 857 * 28, 289 * 28];
|
| 486 |
+
let counts = [856usize, 856, 288];
|
| 487 |
+
for i in 0..3 {
|
| 488 |
+
let (st, v) = get_json(&app, &format!("/get/{id}/parts/{i}")).await;
|
| 489 |
+
assert_eq!(st, StatusCode::OK);
|
| 490 |
+
let data = v["data"].as_str().unwrap();
|
| 491 |
+
assert_eq!(data.len(), sizes[i]);
|
| 492 |
+
assert_eq!(&data[..28], header(0, 0, counts[i]));
|
| 493 |
+
}
|
| 494 |
+
let (st, _) = get_json(&app, &format!("/get/{id}/parts/3")).await;
|
| 495 |
+
assert_eq!(st, StatusCode::NOT_FOUND);
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
#[test]
|
| 500 |
+
fn offset_parsing() {
|
| 501 |
+
assert_eq!(parse_offset(None).unwrap(), [0, 0, 0]);
|
| 502 |
+
assert_eq!(parse_offset(Some("")).unwrap(), [0, 0, 0]);
|
| 503 |
+
assert_eq!(parse_offset(Some("x=1&y=-2&z=3")).unwrap(), [1, -2, 3]);
|
| 504 |
+
assert_eq!(parse_offset(Some("y=5")).unwrap(), [0, 5, 0]);
|
| 505 |
+
assert_eq!(parse_offset(Some("foo=1&z=2")).unwrap(), [0, 0, 2]);
|
| 506 |
+
assert_eq!(parse_offset(Some("x=1&x=2")).unwrap(), [2, 0, 0]);
|
| 507 |
+
assert_eq!(parse_offset(Some("x=+7")).unwrap(), [7, 0, 0]);
|
| 508 |
+
for bad in ["x=abc", "x=", "y=1.5", "z=99999999999", "x"] {
|
| 509 |
+
assert!(
|
| 510 |
+
matches!(parse_offset(Some(bad)), Err(ApiError::BadRequest(_))),
|
| 511 |
+
"{bad}"
|
| 512 |
+
);
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
#[tokio::test]
|
| 517 |
+
async fn upload_rejects_bad_offset() {
|
| 518 |
+
let (app, _) = app();
|
| 519 |
+
for uri in ["/upload?x=abc", "/upload?y=1.5", "/upload?x=1&z=99999999999"] {
|
| 520 |
+
let req = Request::builder()
|
| 521 |
+
.method("POST")
|
| 522 |
+
.uri(uri)
|
| 523 |
+
.body(Body::from("https://example.com/a.litematic"))
|
| 524 |
+
.unwrap();
|
| 525 |
+
let (st, text) = call(&app, req).await;
|
| 526 |
+
assert_eq!(st, StatusCode::BAD_REQUEST, "{uri}");
|
| 527 |
+
let v: Value = serde_json::from_str(&text).unwrap();
|
| 528 |
+
assert!(v["error"].as_str().unwrap().contains("параметр"));
|
| 529 |
+
}
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
#[tokio::test]
|
| 533 |
+
async fn upload_accepts_offset_in_query() {
|
| 534 |
+
// ссылка локальная — отклоняется по ссылке, а не по сдвигу
|
| 535 |
+
let (app, _) = app();
|
| 536 |
+
let req = Request::builder()
|
| 537 |
+
.method("POST")
|
| 538 |
+
.uri("/upload?x=100&y=64&z=-20")
|
| 539 |
+
.body(Body::from("http://127.0.0.1:1/a.litematic"))
|
| 540 |
+
.unwrap();
|
| 541 |
+
let (st, text) = call(&app, req).await;
|
| 542 |
+
assert_eq!(st, StatusCode::BAD_REQUEST);
|
| 543 |
+
let v: Value = serde_json::from_str(&text).unwrap();
|
| 544 |
+
assert!(!v["error"].as_str().unwrap().contains("параметр"));
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
#[tokio::test]
|
| 548 |
+
async fn upload_rejects_bad_links() {
|
| 549 |
+
let (app, _) = app();
|
| 550 |
+
for body in ["", "not a url", "ftp://example.com/a.litematic", "http://127.0.0.1:1/a.litematic"] {
|
| 551 |
+
let req = Request::builder()
|
| 552 |
+
.method("POST")
|
| 553 |
+
.uri("/upload")
|
| 554 |
+
.body(Body::from(body))
|
| 555 |
+
.unwrap();
|
| 556 |
+
let (st, text) = call(&app, req).await;
|
| 557 |
+
assert_eq!(st, StatusCode::BAD_REQUEST, "{body:?}");
|
| 558 |
+
let v: Value = serde_json::from_str(&text).unwrap();
|
| 559 |
+
assert!(v["error"].as_str().unwrap().len() > 5);
|
| 560 |
+
}
|
| 561 |
+
}
|
| 562 |
+
}
|
loader.rs
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Скачивание файла по ссылке: лимит размера, таймаут, защита от обращений во внутреннюю сеть.
|
| 2 |
+
|
| 3 |
+
use std::fmt;
|
| 4 |
+
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
| 5 |
+
use std::time::Duration;
|
| 6 |
+
|
| 7 |
+
use reqwest::{redirect, Client, Url};
|
| 8 |
+
|
| 9 |
+
#[derive(Debug, Clone)]
|
| 10 |
+
pub struct LoaderConfig {
|
| 11 |
+
pub max_bytes: usize,
|
| 12 |
+
pub timeout: Duration,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
impl Default for LoaderConfig {
|
| 16 |
+
fn default() -> Self {
|
| 17 |
+
LoaderConfig {
|
| 18 |
+
max_bytes: 10 * 1024 * 1024,
|
| 19 |
+
timeout: Duration::from_millis(1500),
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
#[derive(Debug)]
|
| 25 |
+
pub enum LoadError {
|
| 26 |
+
InvalidUrl(String),
|
| 27 |
+
Forbidden(String),
|
| 28 |
+
Request(String),
|
| 29 |
+
Status(u16),
|
| 30 |
+
TooLarge(usize),
|
| 31 |
+
Timeout,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
impl fmt::Display for LoadError {
|
| 35 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 36 |
+
match self {
|
| 37 |
+
LoadError::InvalidUrl(m) => write!(f, "некорректная ссылка: {m}"),
|
| 38 |
+
LoadError::Forbidden(m) => write!(f, "ссылка запрещена: {m}"),
|
| 39 |
+
LoadError::Request(m) => write!(f, "не удалось скачать файл: {m}"),
|
| 40 |
+
LoadError::Status(c) => write!(f, "сервер ответил кодом {c}"),
|
| 41 |
+
LoadError::TooLarge(n) => write!(f, "файл больше {n} байт"),
|
| 42 |
+
LoadError::Timeout => write!(f, "превышено время ожидания при скачивании"),
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
impl std::error::Error for LoadError {}
|
| 48 |
+
|
| 49 |
+
fn is_public_v4(ip: Ipv4Addr) -> bool {
|
| 50 |
+
let o = ip.octets();
|
| 51 |
+
!(ip.is_loopback()
|
| 52 |
+
|| ip.is_private()
|
| 53 |
+
|| ip.is_link_local()
|
| 54 |
+
|| ip.is_unspecified()
|
| 55 |
+
|| ip.is_broadcast()
|
| 56 |
+
|| ip.is_documentation()
|
| 57 |
+
|| o[0] == 0
|
| 58 |
+
|| (o[0] == 100 && (o[1] & 0xC0) == 64)) // 100.64.0.0/10
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
fn is_public_v6(ip: Ipv6Addr) -> bool {
|
| 62 |
+
if let Some(v4) = ip.to_ipv4_mapped() {
|
| 63 |
+
return is_public_v4(v4);
|
| 64 |
+
}
|
| 65 |
+
let s = ip.segments();
|
| 66 |
+
!(ip.is_loopback()
|
| 67 |
+
|| ip.is_unspecified()
|
| 68 |
+
|| (s[0] & 0xfe00) == 0xfc00 // fc00::/7
|
| 69 |
+
|| (s[0] & 0xffc0) == 0xfe80) // fe80::/10
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/// Разрешён ли хост: только публичные адреса, без localhost и служебных зон.
|
| 73 |
+
/// DNS-имена, резолвящиеся во внутренние адреса, эта проверка не ловит.
|
| 74 |
+
pub fn host_allowed(url: &Url) -> bool {
|
| 75 |
+
if !matches!(url.scheme(), "http" | "https") {
|
| 76 |
+
return false;
|
| 77 |
+
}
|
| 78 |
+
let host = match url.host_str() {
|
| 79 |
+
Some(h) => h.trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase(),
|
| 80 |
+
None => return false,
|
| 81 |
+
};
|
| 82 |
+
if let Ok(ip) = host.parse::<IpAddr>() {
|
| 83 |
+
return match ip {
|
| 84 |
+
IpAddr::V4(v4) => is_public_v4(v4),
|
| 85 |
+
IpAddr::V6(v6) => is_public_v6(v6),
|
| 86 |
+
};
|
| 87 |
+
}
|
| 88 |
+
!(host == "localhost"
|
| 89 |
+
|| host.ends_with(".localhost")
|
| 90 |
+
|| host.ends_with(".local")
|
| 91 |
+
|| host.ends_with(".internal"))
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
/// Тело запроса → проверенный URL.
|
| 95 |
+
pub fn parse_url(text: &str) -> Result<Url, LoadError> {
|
| 96 |
+
let t = text.trim();
|
| 97 |
+
if t.is_empty() {
|
| 98 |
+
return Err(LoadError::InvalidUrl("пустое тело запроса, ожидается прямая ссылка".into()));
|
| 99 |
+
}
|
| 100 |
+
let url = Url::parse(t).map_err(|e| LoadError::InvalidUrl(e.to_string()))?;
|
| 101 |
+
if !matches!(url.scheme(), "http" | "https") {
|
| 102 |
+
return Err(LoadError::InvalidUrl("поддерживаются только http и https".into()));
|
| 103 |
+
}
|
| 104 |
+
if !host_allowed(&url) {
|
| 105 |
+
return Err(LoadError::Forbidden("адрес локальный или служебный".into()));
|
| 106 |
+
}
|
| 107 |
+
Ok(url)
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
pub fn build_client(cfg: &LoaderConfig) -> Result<Client, reqwest::Error> {
|
| 111 |
+
let policy = redirect::Policy::custom(|attempt| {
|
| 112 |
+
if attempt.previous().len() >= 5 {
|
| 113 |
+
attempt.error("слишком много перенаправлений")
|
| 114 |
+
} else if !host_allowed(attempt.url()) {
|
| 115 |
+
attempt.error("перенаправление на запрещённый адрес")
|
| 116 |
+
} else {
|
| 117 |
+
attempt.follow()
|
| 118 |
+
}
|
| 119 |
+
});
|
| 120 |
+
Client::builder()
|
| 121 |
+
.timeout(cfg.timeout)
|
| 122 |
+
.connect_timeout(Duration::from_millis(1000))
|
| 123 |
+
.redirect(policy)
|
| 124 |
+
.user_agent("litematic-host/0.1")
|
| 125 |
+
.build()
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
fn map_err(e: reqwest::Error) -> LoadError {
|
| 129 |
+
if e.is_timeout() {
|
| 130 |
+
LoadError::Timeout
|
| 131 |
+
} else {
|
| 132 |
+
LoadError::Request(e.to_string())
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/// Скачивает файл, не читая больше `cfg.max_bytes`.
|
| 137 |
+
pub async fn download(client: &Client, url: Url, cfg: &LoaderConfig) -> Result<Vec<u8>, LoadError> {
|
| 138 |
+
let mut resp = client.get(url).send().await.map_err(map_err)?;
|
| 139 |
+
if !resp.status().is_success() {
|
| 140 |
+
return Err(LoadError::Status(resp.status().as_u16()));
|
| 141 |
+
}
|
| 142 |
+
if let Some(len) = resp.content_length() {
|
| 143 |
+
if len > cfg.max_bytes as u64 {
|
| 144 |
+
return Err(LoadError::TooLarge(cfg.max_bytes));
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
let mut buf: Vec<u8> = Vec::new();
|
| 148 |
+
while let Some(chunk) = resp.chunk().await.map_err(map_err)? {
|
| 149 |
+
if buf.len() + chunk.len() > cfg.max_bytes {
|
| 150 |
+
return Err(LoadError::TooLarge(cfg.max_bytes));
|
| 151 |
+
}
|
| 152 |
+
buf.extend_from_slice(&chunk);
|
| 153 |
+
}
|
| 154 |
+
Ok(buf)
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
#[cfg(test)]
|
| 158 |
+
mod tests {
|
| 159 |
+
use super::*;
|
| 160 |
+
|
| 161 |
+
#[test]
|
| 162 |
+
fn accepts_public_urls() {
|
| 163 |
+
assert!(parse_url("https://example.com/a.litematic").is_ok());
|
| 164 |
+
assert!(parse_url(" http://8.8.8.8/x \n").is_ok());
|
| 165 |
+
assert!(parse_url("https://cdn.example.com/file?id=1&x=2").is_ok());
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
#[test]
|
| 169 |
+
fn rejects_bad_input() {
|
| 170 |
+
assert!(matches!(parse_url(""), Err(LoadError::InvalidUrl(_))));
|
| 171 |
+
assert!(matches!(parse_url(" "), Err(LoadError::InvalidUrl(_))));
|
| 172 |
+
assert!(matches!(parse_url("not a url"), Err(LoadError::InvalidUrl(_))));
|
| 173 |
+
assert!(matches!(parse_url("ftp://example.com/a"), Err(LoadError::InvalidUrl(_))));
|
| 174 |
+
assert!(matches!(parse_url("file:///etc/passwd"), Err(LoadError::InvalidUrl(_))));
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
#[test]
|
| 178 |
+
fn rejects_internal_hosts() {
|
| 179 |
+
for u in [
|
| 180 |
+
"http://localhost/x",
|
| 181 |
+
"http://foo.localhost/x",
|
| 182 |
+
"http://127.0.0.1:8080/x",
|
| 183 |
+
"http://10.0.0.1/",
|
| 184 |
+
"http://192.168.1.1/",
|
| 185 |
+
"http://172.16.0.1/",
|
| 186 |
+
"http://169.254.169.254/latest/meta-data",
|
| 187 |
+
"http://100.64.0.1/",
|
| 188 |
+
"http://0.0.0.0/",
|
| 189 |
+
"http://[::1]/",
|
| 190 |
+
"http://[fe80::1]/",
|
| 191 |
+
"http://[fd00::1]/",
|
| 192 |
+
"http://[::ffff:127.0.0.1]/",
|
| 193 |
+
"http://2130706433/",
|
| 194 |
+
"http://printer.local/",
|
| 195 |
+
] {
|
| 196 |
+
assert!(matches!(parse_url(u), Err(LoadError::Forbidden(_))), "{u}");
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
}
|
main.rs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
mod encoder;
|
| 2 |
+
mod http;
|
| 3 |
+
mod loader;
|
| 4 |
+
mod nbt;
|
| 5 |
+
mod store;
|
| 6 |
+
|
| 7 |
+
use std::net::SocketAddr;
|
| 8 |
+
|
| 9 |
+
use tracing::info;
|
| 10 |
+
use tracing_subscriber::EnvFilter;
|
| 11 |
+
|
| 12 |
+
#[tokio::main]
|
| 13 |
+
async fn main() {
|
| 14 |
+
tracing_subscriber::fmt()
|
| 15 |
+
.with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
|
| 16 |
+
.init();
|
| 17 |
+
|
| 18 |
+
let port = std::env::var("PORT")
|
| 19 |
+
.ok()
|
| 20 |
+
.and_then(|p| p.parse::<u16>().ok())
|
| 21 |
+
.unwrap_or(7860);
|
| 22 |
+
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
| 23 |
+
|
| 24 |
+
let loader_cfg = loader::LoaderConfig::default();
|
| 25 |
+
let client = loader::build_client(&loader_cfg).expect("не удалось создать HTTP-клиент");
|
| 26 |
+
let state = http::AppState::new(store::Store::default(), client, loader_cfg);
|
| 27 |
+
let app = http::router(state);
|
| 28 |
+
|
| 29 |
+
let listener = tokio::net::TcpListener::bind(addr)
|
| 30 |
+
.await
|
| 31 |
+
.expect("не удалось занять порт");
|
| 32 |
+
info!(%addr, "сервис запущен");
|
| 33 |
+
axum::serve(listener, app)
|
| 34 |
+
.with_graceful_shutdown(shutdown_signal())
|
| 35 |
+
.await
|
| 36 |
+
.expect("ошибка сервера");
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
async fn shutdown_signal() {
|
| 40 |
+
let ctrl_c = async {
|
| 41 |
+
let _ = tokio::signal::ctrl_c().await;
|
| 42 |
+
};
|
| 43 |
+
#[cfg(unix)]
|
| 44 |
+
let term = async {
|
| 45 |
+
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
| 46 |
+
Ok(mut s) => {
|
| 47 |
+
s.recv().await;
|
| 48 |
+
}
|
| 49 |
+
Err(_) => std::future::pending::<()>().await,
|
| 50 |
+
}
|
| 51 |
+
};
|
| 52 |
+
#[cfg(not(unix))]
|
| 53 |
+
let term = std::future::pending::<()>();
|
| 54 |
+
|
| 55 |
+
tokio::select! {
|
| 56 |
+
_ = ctrl_c => {},
|
| 57 |
+
_ = term => {},
|
| 58 |
+
}
|
| 59 |
+
info!("остановка");
|
| 60 |
+
}
|
nbt.rs
ADDED
|
@@ -0,0 +1,1188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Разбор .litematic: gzip → NBT → группы позиций.
|
| 2 |
+
//!
|
| 3 |
+
//! Результат — `Groups`: (название блока, SNBT tile entity или "") → готовые ячейки
|
| 4 |
+
//! позиций по 28 байт. Ячейки пишутся прямо в горячем цикле (без промежуточных
|
| 5 |
+
//! списков координат и без форматирования строк). Массивы NBT не копируются:
|
| 6 |
+
//! `BlockStates` читается прямо из распакованного буфера.
|
| 7 |
+
|
| 8 |
+
use std::collections::btree_map::Entry;
|
| 9 |
+
use std::collections::BTreeMap;
|
| 10 |
+
use std::fmt::{self, Write as _};
|
| 11 |
+
use std::io::Read;
|
| 12 |
+
use std::sync::atomic::{AtomicBool, Ordering};
|
| 13 |
+
|
| 14 |
+
use crate::encoder::{self, Groups};
|
| 15 |
+
|
| 16 |
+
pub type Pos = (i32, i32, i32);
|
| 17 |
+
/// Сдвиг (x, y, z), который прибавляется ко всем позициям.
|
| 18 |
+
pub type Offset = [i32; 3];
|
| 19 |
+
|
| 20 |
+
const MAX_DEPTH: usize = 64;
|
| 21 |
+
const AIR: [&str; 3] = ["minecraft:air", "minecraft:cave_air", "minecraft:void_air"];
|
| 22 |
+
|
| 23 |
+
#[derive(Debug, Clone)]
|
| 24 |
+
pub struct Limits {
|
| 25 |
+
/// Максимум байт после распаковки gzip.
|
| 26 |
+
pub max_decompressed: usize,
|
| 27 |
+
/// Максимум непустых (не воздух) блоков.
|
| 28 |
+
pub max_blocks: usize,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
impl Default for Limits {
|
| 32 |
+
fn default() -> Self {
|
| 33 |
+
Limits {
|
| 34 |
+
max_decompressed: 64 * 1024 * 1024,
|
| 35 |
+
max_blocks: 500_000,
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
| 41 |
+
pub enum NbtError {
|
| 42 |
+
Gzip(String),
|
| 43 |
+
TooLarge(usize),
|
| 44 |
+
Malformed(String),
|
| 45 |
+
NotLitematic(String),
|
| 46 |
+
TooManyBlocks(usize),
|
| 47 |
+
Coord(String),
|
| 48 |
+
Cancelled,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
impl fmt::Display for NbtError {
|
| 52 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 53 |
+
match self {
|
| 54 |
+
NbtError::Gzip(m) => write!(f, "не удалось распаковать gzip: {m}"),
|
| 55 |
+
NbtError::TooLarge(n) => write!(f, "после распаковки файл больше {n} байт"),
|
| 56 |
+
NbtError::Malformed(m) => write!(f, "повреждённый файл: {m}"),
|
| 57 |
+
NbtError::NotLitematic(m) => write!(f, "это не .litematic: {m}"),
|
| 58 |
+
NbtError::TooManyBlocks(n) => {
|
| 59 |
+
write!(f, "схематика слишком большая: больше {n} непустых блоков")
|
| 60 |
+
}
|
| 61 |
+
NbtError::Coord(m) => write!(f, "{m}"),
|
| 62 |
+
NbtError::Cancelled => write!(f, "обработка отменена: не уложились в срок"),
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
impl std::error::Error for NbtError {}
|
| 68 |
+
|
| 69 |
+
fn malformed(msg: impl Into<String>) -> NbtError {
|
| 70 |
+
NbtError::Malformed(msg.into())
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// ---------------------------------------------------------------- gzip
|
| 74 |
+
|
| 75 |
+
/// Распаковывает gzip с ограничением размера результата.
|
| 76 |
+
pub fn gunzip(data: &[u8], limit: usize) -> Result<Vec<u8>, NbtError> {
|
| 77 |
+
if data.len() < 2 || data[0] != 0x1f || data[1] != 0x8b {
|
| 78 |
+
return Err(NbtError::NotLitematic(
|
| 79 |
+
"ожидается gzip-сжатый NBT (файл не начинается с gzip-заголовка)".to_string(),
|
| 80 |
+
));
|
| 81 |
+
}
|
| 82 |
+
let decoder = flate2::read::GzDecoder::new(data);
|
| 83 |
+
let mut out = Vec::new();
|
| 84 |
+
decoder
|
| 85 |
+
.take(limit as u64 + 1)
|
| 86 |
+
.read_to_end(&mut out)
|
| 87 |
+
.map_err(|e| NbtError::Gzip(e.to_string()))?;
|
| 88 |
+
if out.len() > limit {
|
| 89 |
+
return Err(NbtError::TooLarge(limit));
|
| 90 |
+
}
|
| 91 |
+
Ok(out)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// ---------------------------------------------------------------- NBT
|
| 95 |
+
|
| 96 |
+
/// Массивы хранятся как сырые байты (big-endian) — без копирования.
|
| 97 |
+
#[allow(dead_code)]
|
| 98 |
+
#[derive(Debug, Clone, PartialEq)]
|
| 99 |
+
pub enum Tag<'a> {
|
| 100 |
+
Byte(i8),
|
| 101 |
+
Short(i16),
|
| 102 |
+
Int(i32),
|
| 103 |
+
Long(i64),
|
| 104 |
+
Float(f32),
|
| 105 |
+
Double(f64),
|
| 106 |
+
ByteArray(&'a [u8]),
|
| 107 |
+
String(String),
|
| 108 |
+
List(Vec<Tag<'a>>),
|
| 109 |
+
Compound(BTreeMap<String, Tag<'a>>),
|
| 110 |
+
IntArray(&'a [u8]),
|
| 111 |
+
LongArray(&'a [u8]),
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
impl<'a> Tag<'a> {
|
| 115 |
+
fn get(&self, key: &str) -> Option<&Tag<'a>> {
|
| 116 |
+
if let Tag::Compound(m) = self {
|
| 117 |
+
m.get(key)
|
| 118 |
+
} else {
|
| 119 |
+
None
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
fn as_int(&self) -> Option<i32> {
|
| 124 |
+
if let Tag::Int(v) = self {
|
| 125 |
+
Some(*v)
|
| 126 |
+
} else {
|
| 127 |
+
None
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
fn as_str(&self) -> Option<&str> {
|
| 132 |
+
if let Tag::String(s) = self {
|
| 133 |
+
Some(s.as_str())
|
| 134 |
+
} else {
|
| 135 |
+
None
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
struct Reader<'a> {
|
| 141 |
+
buf: &'a [u8],
|
| 142 |
+
pos: usize,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
impl<'a> Reader<'a> {
|
| 146 |
+
fn new(buf: &'a [u8]) -> Self {
|
| 147 |
+
Reader { buf, pos: 0 }
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
fn remaining(&self) -> usize {
|
| 151 |
+
self.buf.len() - self.pos
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
fn take(&mut self, n: usize) -> Result<&'a [u8], NbtError> {
|
| 155 |
+
let end = self
|
| 156 |
+
.pos
|
| 157 |
+
.checked_add(n)
|
| 158 |
+
.filter(|&e| e <= self.buf.len())
|
| 159 |
+
.ok_or_else(|| malformed("неожиданный конец данных"))?;
|
| 160 |
+
let slice = &self.buf[self.pos..end];
|
| 161 |
+
self.pos = end;
|
| 162 |
+
Ok(slice)
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
fn u8(&mut self) -> Result<u8, NbtError> {
|
| 166 |
+
Ok(self.take(1)?[0])
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
fn u16(&mut self) -> Result<u16, NbtError> {
|
| 170 |
+
Ok(u16::from_be_bytes(self.take(2)?.try_into().unwrap()))
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
fn i16(&mut self) -> Result<i16, NbtError> {
|
| 174 |
+
Ok(i16::from_be_bytes(self.take(2)?.try_into().unwrap()))
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
fn i32(&mut self) -> Result<i32, NbtError> {
|
| 178 |
+
Ok(i32::from_be_bytes(self.take(4)?.try_into().unwrap()))
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
fn i64(&mut self) -> Result<i64, NbtError> {
|
| 182 |
+
Ok(i64::from_be_bytes(self.take(8)?.try_into().unwrap()))
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
fn len(&mut self) -> Result<usize, NbtError> {
|
| 186 |
+
let n = self.i32()?;
|
| 187 |
+
usize::try_from(n).map_err(|_| malformed("отрицательная длина"))
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
fn string(&mut self) -> Result<String, NbtError> {
|
| 191 |
+
let n = self.u16()? as usize;
|
| 192 |
+
let bytes = self.take(n)?;
|
| 193 |
+
Ok(String::from_utf8_lossy(bytes).into_owned())
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
fn payload(&mut self, id: u8, depth: usize) -> Result<Tag<'a>, NbtError> {
|
| 197 |
+
if depth > MAX_DEPTH {
|
| 198 |
+
return Err(malformed("слишком глубокая вложенность"));
|
| 199 |
+
}
|
| 200 |
+
Ok(match id {
|
| 201 |
+
1 => Tag::Byte(self.u8()? as i8),
|
| 202 |
+
2 => Tag::Short(self.i16()?),
|
| 203 |
+
3 => Tag::Int(self.i32()?),
|
| 204 |
+
4 => Tag::Long(self.i64()?),
|
| 205 |
+
5 => Tag::Float(f32::from_bits(self.i32()? as u32)),
|
| 206 |
+
6 => Tag::Double(f64::from_bits(self.i64()? as u64)),
|
| 207 |
+
7 => {
|
| 208 |
+
let n = self.len()?;
|
| 209 |
+
Tag::ByteArray(self.take(n)?)
|
| 210 |
+
}
|
| 211 |
+
8 => Tag::String(self.string()?),
|
| 212 |
+
9 => {
|
| 213 |
+
let elem = self.u8()?;
|
| 214 |
+
let n = self.len()?;
|
| 215 |
+
if n > 0 && elem == 0 {
|
| 216 |
+
return Err(malformed("список с типом элементов End"));
|
| 217 |
+
}
|
| 218 |
+
if n > self.remaining() {
|
| 219 |
+
return Err(malformed("длина списка больше оставшихся данных"));
|
| 220 |
+
}
|
| 221 |
+
let mut items = Vec::with_capacity(n);
|
| 222 |
+
for _ in 0..n {
|
| 223 |
+
items.push(self.payload(elem, depth + 1)?);
|
| 224 |
+
}
|
| 225 |
+
Tag::List(items)
|
| 226 |
+
}
|
| 227 |
+
10 => {
|
| 228 |
+
let mut map = BTreeMap::new();
|
| 229 |
+
loop {
|
| 230 |
+
let t = self.u8()?;
|
| 231 |
+
if t == 0 {
|
| 232 |
+
break;
|
| 233 |
+
}
|
| 234 |
+
let name = self.string()?;
|
| 235 |
+
let value = self.payload(t, depth + 1)?;
|
| 236 |
+
map.insert(name, value);
|
| 237 |
+
}
|
| 238 |
+
Tag::Compound(map)
|
| 239 |
+
}
|
| 240 |
+
11 => {
|
| 241 |
+
let n = self.len()?;
|
| 242 |
+
let size = n.checked_mul(4).ok_or_else(|| malformed("длина массива"))?;
|
| 243 |
+
Tag::IntArray(self.take(size)?)
|
| 244 |
+
}
|
| 245 |
+
12 => {
|
| 246 |
+
let n = self.len()?;
|
| 247 |
+
let size = n.checked_mul(8).ok_or_else(|| malformed("длина массива"))?;
|
| 248 |
+
Tag::LongArray(self.take(size)?)
|
| 249 |
+
}
|
| 250 |
+
other => return Err(malformed(format!("неизвестный тип тега {other}"))),
|
| 251 |
+
})
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/// Разбирает несжатый NBT. Корень обязан быть compound.
|
| 256 |
+
pub fn parse_nbt(data: &[u8]) -> Result<Tag<'_>, NbtError> {
|
| 257 |
+
let mut r = Reader::new(data);
|
| 258 |
+
let id = r.u8()?;
|
| 259 |
+
if id != 10 {
|
| 260 |
+
return Err(malformed("корневой тег не compound"));
|
| 261 |
+
}
|
| 262 |
+
let _root_name = r.string()?;
|
| 263 |
+
r.payload(10, 0)
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
// ---------------------------------------------------------------- SNBT
|
| 267 |
+
|
| 268 |
+
fn write_quoted(s: &str, out: &mut String) {
|
| 269 |
+
out.push('"');
|
| 270 |
+
for c in s.chars() {
|
| 271 |
+
match c {
|
| 272 |
+
'"' => out.push_str("\\\""),
|
| 273 |
+
'\\' => out.push_str("\\\\"),
|
| 274 |
+
_ => out.push(c),
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
out.push('"');
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
fn write_key(k: &str, out: &mut String) {
|
| 281 |
+
let plain = !k.is_empty()
|
| 282 |
+
&& k.chars()
|
| 283 |
+
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'));
|
| 284 |
+
if plain {
|
| 285 |
+
out.push_str(k);
|
| 286 |
+
} else {
|
| 287 |
+
write_quoted(k, out);
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
fn write_compound(map: &BTreeMap<String, Tag<'_>>, skip: &[&str], out: &mut String) {
|
| 292 |
+
out.push('{');
|
| 293 |
+
let mut first = true;
|
| 294 |
+
for (k, v) in map {
|
| 295 |
+
if skip.iter().any(|s| *s == k.as_str()) {
|
| 296 |
+
continue;
|
| 297 |
+
}
|
| 298 |
+
if !first {
|
| 299 |
+
out.push(',');
|
| 300 |
+
}
|
| 301 |
+
first = false;
|
| 302 |
+
write_key(k, out);
|
| 303 |
+
out.push(':');
|
| 304 |
+
write_snbt(v, out);
|
| 305 |
+
}
|
| 306 |
+
out.push('}');
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
fn write_snbt(tag: &Tag<'_>, out: &mut String) {
|
| 310 |
+
match tag {
|
| 311 |
+
Tag::Byte(v) => {
|
| 312 |
+
let _ = write!(out, "{v}b");
|
| 313 |
+
}
|
| 314 |
+
Tag::Short(v) => {
|
| 315 |
+
let _ = write!(out, "{v}s");
|
| 316 |
+
}
|
| 317 |
+
Tag::Int(v) => {
|
| 318 |
+
let _ = write!(out, "{v}");
|
| 319 |
+
}
|
| 320 |
+
Tag::Long(v) => {
|
| 321 |
+
let _ = write!(out, "{v}L");
|
| 322 |
+
}
|
| 323 |
+
Tag::Float(v) => {
|
| 324 |
+
let _ = write!(out, "{v}f");
|
| 325 |
+
}
|
| 326 |
+
Tag::Double(v) => {
|
| 327 |
+
let _ = write!(out, "{v}d");
|
| 328 |
+
}
|
| 329 |
+
Tag::String(s) => write_quoted(s, out),
|
| 330 |
+
Tag::ByteArray(b) => {
|
| 331 |
+
out.push_str("[B;");
|
| 332 |
+
for (i, x) in b.iter().enumerate() {
|
| 333 |
+
if i > 0 {
|
| 334 |
+
out.push(',');
|
| 335 |
+
}
|
| 336 |
+
let _ = write!(out, "{}b", *x as i8);
|
| 337 |
+
}
|
| 338 |
+
out.push(']');
|
| 339 |
+
}
|
| 340 |
+
Tag::IntArray(b) => {
|
| 341 |
+
out.push_str("[I;");
|
| 342 |
+
for (i, c) in b.chunks_exact(4).enumerate() {
|
| 343 |
+
if i > 0 {
|
| 344 |
+
out.push(',');
|
| 345 |
+
}
|
| 346 |
+
let _ = write!(out, "{}", i32::from_be_bytes(c.try_into().unwrap()));
|
| 347 |
+
}
|
| 348 |
+
out.push(']');
|
| 349 |
+
}
|
| 350 |
+
Tag::LongArray(b) => {
|
| 351 |
+
out.push_str("[L;");
|
| 352 |
+
for (i, c) in b.chunks_exact(8).enumerate() {
|
| 353 |
+
if i > 0 {
|
| 354 |
+
out.push(',');
|
| 355 |
+
}
|
| 356 |
+
let _ = write!(out, "{}L", i64::from_be_bytes(c.try_into().unwrap()));
|
| 357 |
+
}
|
| 358 |
+
out.push(']');
|
| 359 |
+
}
|
| 360 |
+
Tag::List(items) => {
|
| 361 |
+
out.push('[');
|
| 362 |
+
for (i, t) in items.iter().enumerate() {
|
| 363 |
+
if i > 0 {
|
| 364 |
+
out.push(',');
|
| 365 |
+
}
|
| 366 |
+
write_snbt(t, out);
|
| 367 |
+
}
|
| 368 |
+
out.push(']');
|
| 369 |
+
}
|
| 370 |
+
Tag::Compound(m) => write_compound(m, &[], out),
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
/// SNBT compound без ключей из `skip`. Ключи по алфавиту — результат детерминирован.
|
| 375 |
+
pub fn compound_snbt(map: &BTreeMap<String, Tag<'_>>, skip: &[&str]) -> String {
|
| 376 |
+
let mut s = String::new();
|
| 377 |
+
write_compound(map, skip, &mut s);
|
| 378 |
+
s
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
/// NBT compound как JSON-словарь `{ключ: текст}`: значение — обычный текст для строк, SNBT-текст для остального
|
| 382 |
+
/// (числа, списки, вложенные compound; экранирует serde_json). Ключи из `skip` и пустые теги (`{}`, `[]`) пропускаются, порядок — по алфавиту.
|
| 383 |
+
pub fn compound_dict_json(map: &BTreeMap<String, Tag<'_>>, skip: &[&str]) -> String {
|
| 384 |
+
let mut obj = serde_json::Map::new();
|
| 385 |
+
for (k, v) in map {
|
| 386 |
+
if skip.iter().any(|s| *s == k.as_str()) {
|
| 387 |
+
continue;
|
| 388 |
+
}
|
| 389 |
+
let t = match v {
|
| 390 |
+
Tag::String(s) => s.clone(),
|
| 391 |
+
_ => {
|
| 392 |
+
let mut t = String::new();
|
| 393 |
+
write_snbt(v, &mut t);
|
| 394 |
+
// пустые теги (`{}`, `[]`) не храним
|
| 395 |
+
if t == "{}" || t == "[]" {
|
| 396 |
+
continue;
|
| 397 |
+
}
|
| 398 |
+
t
|
| 399 |
+
}
|
| 400 |
+
};
|
| 401 |
+
obj.insert(k.clone(), serde_json::Value::String(t));
|
| 402 |
+
}
|
| 403 |
+
serde_json::Value::Object(obj).to_string()
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
// ---------------------------------------------------------------- litematic
|
| 407 |
+
|
| 408 |
+
/// Gzip → группы позиций со сдвигом `offset`.
|
| 409 |
+
pub fn parse_litematic_gz(
|
| 410 |
+
gz: &[u8],
|
| 411 |
+
limits: &Limits,
|
| 412 |
+
offset: Offset,
|
| 413 |
+
cancel: &AtomicBool,
|
| 414 |
+
) -> Result<Groups, NbtError> {
|
| 415 |
+
let raw = gunzip(gz, limits.max_decompressed)?;
|
| 416 |
+
parse_litematic(&raw, limits.max_blocks, offset, cancel)
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
/// Несжатый NBT → группы «(блок, SNBT) → ячейки позиций».
|
| 420 |
+
/// Воздух пропускается. Регионы обходятся по имени, внутри региона — в порядке
|
| 421 |
+
/// индекса litematica (y, затем z, затем x), поэтому результат детерминирован.
|
| 422 |
+
/// Позиция = `Position` региона + локальная позиция + `offset`.
|
| 423 |
+
/// `cancel` проверяется на каждом слое по y: взведён — вернётся `Cancelled`.
|
| 424 |
+
pub fn parse_litematic(
|
| 425 |
+
data: &[u8],
|
| 426 |
+
max_blocks: usize,
|
| 427 |
+
offset: Offset,
|
| 428 |
+
cancel: &AtomicBool,
|
| 429 |
+
) -> Result<Groups, NbtError> {
|
| 430 |
+
let root = parse_nbt(data)?;
|
| 431 |
+
let regions = match root.get("Regions") {
|
| 432 |
+
Some(Tag::Compound(m)) => m,
|
| 433 |
+
_ => return Err(NbtError::NotLitematic("нет тега Regions".to_string())),
|
| 434 |
+
};
|
| 435 |
+
let mut groups = Groups::new();
|
| 436 |
+
let mut total = 0usize;
|
| 437 |
+
for (name, region) in regions {
|
| 438 |
+
parse_region(name, region, max_blocks, offset, cancel, &mut total, &mut groups)?;
|
| 439 |
+
}
|
| 440 |
+
Ok(groups)
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
fn bad(region: &str, msg: &str) -> NbtError {
|
| 444 |
+
malformed(format!("регион «{region}»: {msg}"))
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
fn read_vec3(region: &Tag<'_>, key: &str, name: &str) -> Result<[i32; 3], NbtError> {
|
| 448 |
+
let tag = region
|
| 449 |
+
.get(key)
|
| 450 |
+
.ok_or_else(|| bad(name, &format!("нет поля {key}")))?;
|
| 451 |
+
let mut out = [0i32; 3];
|
| 452 |
+
for (slot, axis) in out.iter_mut().zip(["x", "y", "z"]) {
|
| 453 |
+
*slot = tag
|
| 454 |
+
.get(axis)
|
| 455 |
+
.and_then(|t| t.as_int())
|
| 456 |
+
.ok_or_else(|| bad(name, &format!("{key}.{axis} не является числом")))?;
|
| 457 |
+
}
|
| 458 |
+
Ok(out)
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
/// Название блока с состоянием, без префикса `minecraft:`:
|
| 462 |
+
/// `oak_stairs[facing=north,half=bottom]`. Другие пространства имён (`create:cogwheel`)
|
| 463 |
+
/// остаются как есть. Для воздуха возвращает `None`.
|
| 464 |
+
fn palette_name(entry: &Tag<'_>, region: &str) -> Result<Option<String>, NbtError> {
|
| 465 |
+
let name = entry
|
| 466 |
+
.get("Name")
|
| 467 |
+
.and_then(|t| t.as_str())
|
| 468 |
+
.ok_or_else(|| bad(region, "в палитре нет Name"))?;
|
| 469 |
+
if AIR.iter().any(|a| *a == name) {
|
| 470 |
+
return Ok(None);
|
| 471 |
+
}
|
| 472 |
+
let mut s = name.strip_prefix("minecraft:").unwrap_or(name).to_string();
|
| 473 |
+
if let Some(Tag::Compound(props)) = entry.get("Properties") {
|
| 474 |
+
let parts: Vec<String> = props
|
| 475 |
+
.iter()
|
| 476 |
+
.filter_map(|(k, v)| v.as_str().map(|v| format!("{k}={v}")))
|
| 477 |
+
.collect();
|
| 478 |
+
if !parts.is_empty() {
|
| 479 |
+
s.push('[');
|
| 480 |
+
s.push_str(&parts.join(","));
|
| 481 |
+
s.push(']');
|
| 482 |
+
}
|
| 483 |
+
}
|
| 484 |
+
Ok(Some(s))
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
/// Tile entities региона: (индекс ячейки в массиве блоков, SNBT без x/y/z),
|
| 488 |
+
/// по возрастанию индекса. Координаты tile entity — локальные в регионе.
|
| 489 |
+
/// Ключи `x`, `y`, `z` и `id` игнорируются.
|
| 490 |
+
/// Записи без координат, вне региона или без данных пропускаются.
|
| 491 |
+
fn tile_entities(region: &Tag<'_>, abs: [u64; 3]) -> Vec<(u64, String)> {
|
| 492 |
+
let list = match region.get("TileEntities") {
|
| 493 |
+
Some(Tag::List(l)) => l,
|
| 494 |
+
_ => return Vec::new(),
|
| 495 |
+
};
|
| 496 |
+
let mut found: BTreeMap<u64, String> = BTreeMap::new();
|
| 497 |
+
for te in list {
|
| 498 |
+
let coord = |k: &str| te.get(k).and_then(|t| t.as_int());
|
| 499 |
+
let (x, y, z) = match (coord("x"), coord("y"), coord("z")) {
|
| 500 |
+
(Some(x), Some(y), Some(z)) if x >= 0 && y >= 0 && z >= 0 => {
|
| 501 |
+
(x as u64, y as u64, z as u64)
|
| 502 |
+
}
|
| 503 |
+
_ => continue,
|
| 504 |
+
};
|
| 505 |
+
if x >= abs[0] || y >= abs[1] || z >= abs[2] {
|
| 506 |
+
continue;
|
| 507 |
+
}
|
| 508 |
+
let snbt = match te {
|
| 509 |
+
Tag::Compound(m) => compound_dict_json(m, &["x", "y", "z", "id"]),
|
| 510 |
+
_ => continue,
|
| 511 |
+
};
|
| 512 |
+
if snbt == "{}" {
|
| 513 |
+
continue;
|
| 514 |
+
}
|
| 515 |
+
found.insert((y * abs[2] + z) * abs[0] + x, snbt);
|
| 516 |
+
}
|
| 517 |
+
found.into_iter().collect()
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
#[inline]
|
| 521 |
+
fn long_at(raw: &[u8], i: usize) -> u64 {
|
| 522 |
+
let b: [u8; 8] = raw[i * 8..i * 8 + 8].try_into().unwrap();
|
| 523 |
+
u64::from_be_bytes(b)
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
/// Достаёт `bits`-битное значение с номером `index` из упакованного массива.
|
| 527 |
+
/// Litematica упаковывает значения подряд, без выравнивания по границе long.
|
| 528 |
+
#[inline]
|
| 529 |
+
fn get_bits(raw: &[u8], index: u64, bits: u64, mask: u64) -> u64 {
|
| 530 |
+
let start = index * bits;
|
| 531 |
+
let first = (start >> 6) as usize;
|
| 532 |
+
let last = ((start + bits - 1) >> 6) as usize;
|
| 533 |
+
let offset = start & 63;
|
| 534 |
+
let low = long_at(raw, first) >> offset;
|
| 535 |
+
if first == last {
|
| 536 |
+
low & mask
|
| 537 |
+
} else {
|
| 538 |
+
(low | (long_at(raw, last) << (64 - offset))) & mask
|
| 539 |
+
}
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
fn merge(groups: &mut Groups, key: (String, String), buf: Vec<u8>) {
|
| 543 |
+
match groups.entry(key) {
|
| 544 |
+
Entry::Vacant(v) => {
|
| 545 |
+
v.insert(buf);
|
| 546 |
+
}
|
| 547 |
+
Entry::Occupied(mut o) => o.get_mut().extend_from_slice(&buf),
|
| 548 |
+
}
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
fn parse_region(
|
| 552 |
+
name: &str,
|
| 553 |
+
region: &Tag<'_>,
|
| 554 |
+
max_blocks: usize,
|
| 555 |
+
offset: Offset,
|
| 556 |
+
cancel: &AtomicBool,
|
| 557 |
+
total: &mut usize,
|
| 558 |
+
groups: &mut Groups,
|
| 559 |
+
) -> Result<(), NbtError> {
|
| 560 |
+
if cancel.load(Ordering::Relaxed) {
|
| 561 |
+
return Err(NbtError::Cancelled);
|
| 562 |
+
}
|
| 563 |
+
let pos = read_vec3(region, "Position", name)?;
|
| 564 |
+
let size = read_vec3(region, "Size", name)?;
|
| 565 |
+
let abs = size.map(|s| u64::from(s.unsigned_abs()));
|
| 566 |
+
let volume = abs[0]
|
| 567 |
+
.checked_mul(abs[1])
|
| 568 |
+
.and_then(|v| v.checked_mul(abs[2]))
|
| 569 |
+
.ok_or_else(|| bad(name, "размер региона слишком велик"))?;
|
| 570 |
+
if volume == 0 {
|
| 571 |
+
return Ok(()); // пустой регион
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
let palette = match region.get("BlockStatePalette") {
|
| 575 |
+
Some(Tag::List(l)) => l,
|
| 576 |
+
_ => return Err(bad(name, "нет BlockStatePalette")),
|
| 577 |
+
};
|
| 578 |
+
let raw: &[u8] = match region.get("BlockStates") {
|
| 579 |
+
Some(Tag::LongArray(a)) => *a,
|
| 580 |
+
_ => return Err(bad(name, "нет BlockStates")),
|
| 581 |
+
};
|
| 582 |
+
if palette.is_empty() {
|
| 583 |
+
return Err(bad(name, "пустая палитра"));
|
| 584 |
+
}
|
| 585 |
+
let names: Vec<Option<String>> = palette
|
| 586 |
+
.iter()
|
| 587 |
+
.map(|e| palette_name(e, name))
|
| 588 |
+
.collect::<Result<_, _>>()?;
|
| 589 |
+
|
| 590 |
+
let bits = u64::from((usize::BITS - (palette.len() - 1).leading_zeros()).max(2));
|
| 591 |
+
let total_bits = volume
|
| 592 |
+
.checked_mul(bits)
|
| 593 |
+
.ok_or_else(|| bad(name, "размер региона слишком велик"))?;
|
| 594 |
+
let needed = total_bits / 64 + u64::from(total_bits % 64 != 0);
|
| 595 |
+
if ((raw.len() / 8) as u64) < needed {
|
| 596 |
+
return Err(bad(name, "BlockStates короче, чем размер региона"));
|
| 597 |
+
}
|
| 598 |
+
let mask = (1u64 << bits) - 1;
|
| 599 |
+
|
| 600 |
+
// Минимальный угол региона со сдвигом. Размер может быть отрицательным.
|
| 601 |
+
let mut min = [0i64; 3];
|
| 602 |
+
for i in 0..3 {
|
| 603 |
+
let back = if size[i] < 0 { i64::from(size[i]) + 1 } else { 0 };
|
| 604 |
+
min[i] = i64::from(pos[i]) + back + i64::from(offset[i]);
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
let te = tile_entities(region, abs);
|
| 608 |
+
let mut ti = 0usize;
|
| 609 |
+
let mut next_te = te.first().map(|t| t.0).unwrap_or(u64::MAX);
|
| 610 |
+
|
| 611 |
+
let (sx, sy, sz) = (abs[0] as i64, abs[1] as i64, abs[2] as i64);
|
| 612 |
+
let mut bufs: Vec<Vec<u8>> = vec![Vec::new(); palette.len()];
|
| 613 |
+
let mut special: BTreeMap<(usize, String), Vec<u8>> = BTreeMap::new();
|
| 614 |
+
let mut index: u64 = 0;
|
| 615 |
+
|
| 616 |
+
for y in 0..sy {
|
| 617 |
+
if cancel.load(Ordering::Relaxed) {
|
| 618 |
+
return Err(NbtError::Cancelled);
|
| 619 |
+
}
|
| 620 |
+
for z in 0..sz {
|
| 621 |
+
for x in 0..sx {
|
| 622 |
+
let id = get_bits(raw, index, bits, mask) as usize;
|
| 623 |
+
let is_te = index == next_te;
|
| 624 |
+
if is_te {
|
| 625 |
+
ti += 1;
|
| 626 |
+
next_te = te.get(ti).map(|t| t.0).unwrap_or(u64::MAX);
|
| 627 |
+
}
|
| 628 |
+
index += 1;
|
| 629 |
+
let slot = names
|
| 630 |
+
.get(id)
|
| 631 |
+
.ok_or_else(|| bad(name, "индекс блока вне палитры"))?;
|
| 632 |
+
if slot.is_none() {
|
| 633 |
+
continue;
|
| 634 |
+
}
|
| 635 |
+
*total += 1;
|
| 636 |
+
if *total > max_blocks {
|
| 637 |
+
return Err(NbtError::TooManyBlocks(max_blocks));
|
| 638 |
+
}
|
| 639 |
+
let wx = i32::try_from(min[0] + x).map_err(|_| bad(name, "координата вне i32"))?;
|
| 640 |
+
let wy = i32::try_from(min[1] + y).map_err(|_| bad(name, "координата вне i32"))?;
|
| 641 |
+
let wz = i32::try_from(min[2] + z).map_err(|_| bad(name, "координата вне i32"))?;
|
| 642 |
+
let target: &mut Vec<u8> = if is_te {
|
| 643 |
+
special.entry((id, te[ti - 1].1.clone())).or_default()
|
| 644 |
+
} else {
|
| 645 |
+
&mut bufs[id]
|
| 646 |
+
};
|
| 647 |
+
encoder::push_position(target, wx, wy, wz)
|
| 648 |
+
.map_err(|e| NbtError::Coord(e.to_string()))?;
|
| 649 |
+
}
|
| 650 |
+
}
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
for (id, buf) in bufs.into_iter().enumerate() {
|
| 654 |
+
if buf.is_empty() {
|
| 655 |
+
continue;
|
| 656 |
+
}
|
| 657 |
+
if let Some(block) = &names[id] {
|
| 658 |
+
merge(groups, (block.clone(), String::new()), buf);
|
| 659 |
+
}
|
| 660 |
+
}
|
| 661 |
+
for ((id, snbt), buf) in special {
|
| 662 |
+
if let Some(block) = &names[id] {
|
| 663 |
+
merge(groups, (block.clone(), snbt), buf);
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
Ok(())
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
#[cfg(test)]
|
| 670 |
+
mod tests {
|
| 671 |
+
use super::*;
|
| 672 |
+
use flate2::{write::GzEncoder, Compression};
|
| 673 |
+
use std::io::Write;
|
| 674 |
+
|
| 675 |
+
type Palette = Vec<(&'static str, Vec<(&'static str, &'static str)>)>;
|
| 676 |
+
|
| 677 |
+
// ---- минимальный NBT-писатель для тестов ----
|
| 678 |
+
fn w_str(out: &mut Vec<u8>, s: &str) {
|
| 679 |
+
out.extend((s.len() as u16).to_be_bytes());
|
| 680 |
+
out.extend(s.as_bytes());
|
| 681 |
+
}
|
| 682 |
+
fn named(out: &mut Vec<u8>, id: u8, name: &str) {
|
| 683 |
+
out.push(id);
|
| 684 |
+
w_str(out, name);
|
| 685 |
+
}
|
| 686 |
+
fn int_named(out: &mut Vec<u8>, name: &str, v: i32) {
|
| 687 |
+
named(out, 3, name);
|
| 688 |
+
out.extend(v.to_be_bytes());
|
| 689 |
+
}
|
| 690 |
+
fn vec3(out: &mut Vec<u8>, name: &str, v: [i32; 3]) {
|
| 691 |
+
named(out, 10, name);
|
| 692 |
+
int_named(out, "x", v[0]);
|
| 693 |
+
int_named(out, "y", v[1]);
|
| 694 |
+
int_named(out, "z", v[2]);
|
| 695 |
+
out.push(0);
|
| 696 |
+
}
|
| 697 |
+
fn palette_entry(out: &mut Vec<u8>, name: &str, props: &[(&str, &str)]) {
|
| 698 |
+
named(out, 8, "Name");
|
| 699 |
+
w_str(out, name);
|
| 700 |
+
if !props.is_empty() {
|
| 701 |
+
named(out, 10, "Properties");
|
| 702 |
+
for (k, v) in props {
|
| 703 |
+
named(out, 8, k);
|
| 704 |
+
w_str(out, v);
|
| 705 |
+
}
|
| 706 |
+
out.push(0);
|
| 707 |
+
}
|
| 708 |
+
out.push(0);
|
| 709 |
+
}
|
| 710 |
+
fn region_te(
|
| 711 |
+
out: &mut Vec<u8>,
|
| 712 |
+
name: &str,
|
| 713 |
+
pos: [i32; 3],
|
| 714 |
+
size: [i32; 3],
|
| 715 |
+
palette: &Palette,
|
| 716 |
+
states: &[i64],
|
| 717 |
+
tes: &[(i32, i32, i32, &str)],
|
| 718 |
+
) {
|
| 719 |
+
named(out, 10, name);
|
| 720 |
+
vec3(out, "Position", pos);
|
| 721 |
+
vec3(out, "Size", size);
|
| 722 |
+
named(out, 9, "BlockStatePalette");
|
| 723 |
+
out.push(10);
|
| 724 |
+
out.extend((palette.len() as i32).to_be_bytes());
|
| 725 |
+
for (n, p) in palette {
|
| 726 |
+
palette_entry(out, n, p);
|
| 727 |
+
}
|
| 728 |
+
named(out, 12, "BlockStates");
|
| 729 |
+
out.extend((states.len() as i32).to_be_bytes());
|
| 730 |
+
for s in states {
|
| 731 |
+
out.extend(s.to_be_bytes());
|
| 732 |
+
}
|
| 733 |
+
if !tes.is_empty() {
|
| 734 |
+
named(out, 9, "TileEntities");
|
| 735 |
+
out.push(10);
|
| 736 |
+
out.extend((tes.len() as i32).to_be_bytes());
|
| 737 |
+
for (x, y, z, id) in tes {
|
| 738 |
+
int_named(out, "x", *x);
|
| 739 |
+
int_named(out, "y", *y);
|
| 740 |
+
int_named(out, "z", *z);
|
| 741 |
+
named(out, 8, "Lock");
|
| 742 |
+
w_str(out, id);
|
| 743 |
+
out.push(0);
|
| 744 |
+
}
|
| 745 |
+
}
|
| 746 |
+
out.push(0);
|
| 747 |
+
}
|
| 748 |
+
fn region(
|
| 749 |
+
out: &mut Vec<u8>,
|
| 750 |
+
name: &str,
|
| 751 |
+
pos: [i32; 3],
|
| 752 |
+
size: [i32; 3],
|
| 753 |
+
palette: &Palette,
|
| 754 |
+
states: &[i64],
|
| 755 |
+
) {
|
| 756 |
+
region_te(out, name, pos, size, palette, states, &[]);
|
| 757 |
+
}
|
| 758 |
+
fn litematic(regions: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
|
| 759 |
+
let mut out = Vec::new();
|
| 760 |
+
named(&mut out, 10, "");
|
| 761 |
+
named(&mut out, 10, "Regions");
|
| 762 |
+
regions(&mut out);
|
| 763 |
+
out.push(0); // конец Regions
|
| 764 |
+
out.push(0); // конец корня
|
| 765 |
+
out
|
| 766 |
+
}
|
| 767 |
+
/// Независимая упаковка: бит за битом.
|
| 768 |
+
fn pack(values: &[u64], bits: u64) -> Vec<i64> {
|
| 769 |
+
let total_bits = values.len() as u64 * bits;
|
| 770 |
+
let mut longs = vec![0u64; ((total_bits + 63) / 64) as usize];
|
| 771 |
+
for (i, v) in values.iter().enumerate() {
|
| 772 |
+
for b in 0..bits {
|
| 773 |
+
if (*v >> b) & 1 == 1 {
|
| 774 |
+
let p = i as u64 * bits + b;
|
| 775 |
+
longs[(p / 64) as usize] |= 1u64 << (p % 64);
|
| 776 |
+
}
|
| 777 |
+
}
|
| 778 |
+
}
|
| 779 |
+
longs.into_iter().map(|l| l as i64).collect()
|
| 780 |
+
}
|
| 781 |
+
fn air_stone() -> Palette {
|
| 782 |
+
vec![("minecraft:air", vec![]), ("minecraft:stone", vec![])]
|
| 783 |
+
}
|
| 784 |
+
fn gzip(data: &[u8]) -> Vec<u8> {
|
| 785 |
+
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
| 786 |
+
e.write_all(data).unwrap();
|
| 787 |
+
e.finish().unwrap()
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
// ---- чтение результата ----
|
| 791 |
+
fn dec(c: &[u8]) -> i32 {
|
| 792 |
+
let s = std::str::from_utf8(c).unwrap();
|
| 793 |
+
if let Some(r) = s.strip_prefix('-') {
|
| 794 |
+
-r.parse::<i32>().unwrap()
|
| 795 |
+
} else {
|
| 796 |
+
s.parse().unwrap()
|
| 797 |
+
}
|
| 798 |
+
}
|
| 799 |
+
fn positions(buf: &[u8]) -> Vec<Pos> {
|
| 800 |
+
assert_eq!(buf.len() % encoder::CELL_LEN, 0);
|
| 801 |
+
buf.chunks_exact(encoder::CELL_LEN)
|
| 802 |
+
.map(|c| (dec(&c[5..9]), dec(&c[14..18]), dec(&c[23..27])))
|
| 803 |
+
.collect()
|
| 804 |
+
}
|
| 805 |
+
fn key(name: &str) -> (String, String) {
|
| 806 |
+
(name.to_string(), String::new())
|
| 807 |
+
}
|
| 808 |
+
fn parse(data: &[u8], max: usize) -> Result<Groups, NbtError> {
|
| 809 |
+
parse_litematic(data, max, [0, 0, 0], &AtomicBool::new(false))
|
| 810 |
+
}
|
| 811 |
+
fn parse_off(data: &[u8], offset: Offset) -> Result<Groups, NbtError> {
|
| 812 |
+
parse_litematic(data, 1000, offset, &AtomicBool::new(false))
|
| 813 |
+
}
|
| 814 |
+
|
| 815 |
+
#[test]
|
| 816 |
+
fn simple_region() {
|
| 817 |
+
let data = litematic(|o| region(o, "main", [0, 0, 0], [2, 1, 2], &air_stone(), &pack(&[0, 1, 1, 0], 2)));
|
| 818 |
+
let g = parse(&data, 1000).unwrap();
|
| 819 |
+
assert_eq!(g.len(), 1);
|
| 820 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(1, 0, 0), (0, 0, 1)]);
|
| 821 |
+
}
|
| 822 |
+
|
| 823 |
+
#[test]
|
| 824 |
+
fn cells_have_expected_text() {
|
| 825 |
+
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 826 |
+
let g = parse(&data, 10).unwrap();
|
| 827 |
+
let cell = String::from_utf8(g[&key("stone")].clone()).unwrap();
|
| 828 |
+
assert_eq!(cell, r#"{'x':-005,'y':0010,'z':-001}"#);
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
#[test]
|
| 832 |
+
fn empty_regions_tag() {
|
| 833 |
+
let data = litematic(|_| {});
|
| 834 |
+
assert!(parse(&data, 10).unwrap().is_empty());
|
| 835 |
+
}
|
| 836 |
+
|
| 837 |
+
#[test]
|
| 838 |
+
fn empty_region_zero_size() {
|
| 839 |
+
let data = litematic(|o| region(o, "r", [3, 3, 3], [0, 0, 0], &air_stone(), &[]));
|
| 840 |
+
assert!(parse(&data, 10).unwrap().is_empty());
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
#[test]
|
| 844 |
+
fn region_with_only_air() {
|
| 845 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 2, 2], &air_stone(), &pack(&[0; 8], 2)));
|
| 846 |
+
assert!(parse(&data, 10).unwrap().is_empty());
|
| 847 |
+
}
|
| 848 |
+
|
| 849 |
+
#[test]
|
| 850 |
+
fn negative_position() {
|
| 851 |
+
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 852 |
+
let g = parse(&data, 10).unwrap();
|
| 853 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(-5, 10, -1)]);
|
| 854 |
+
}
|
| 855 |
+
|
| 856 |
+
#[test]
|
| 857 |
+
fn negative_size_extends_backwards() {
|
| 858 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [-2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 859 |
+
let g = parse(&data, 10).unwrap();
|
| 860 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(-1, 0, 0), (0, 0, 0)]);
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
#[test]
|
| 864 |
+
fn coordinate_out_of_cell_range() {
|
| 865 |
+
let data = litematic(|o| region(o, "r", [10_000, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 866 |
+
assert!(matches!(parse(&data, 10), Err(NbtError::Coord(_))));
|
| 867 |
+
}
|
| 868 |
+
|
| 869 |
+
#[test]
|
| 870 |
+
fn values_spanning_long_boundary() {
|
| 871 |
+
let names = ["minecraft:air", "minecraft:a", "minecraft:b", "minecraft:c", "minecraft:d"];
|
| 872 |
+
let palette: Palette = names.iter().map(|n| (*n, Vec::new())).collect();
|
| 873 |
+
let values: Vec<u64> = (0..30u64).map(|i| i % 5).collect();
|
| 874 |
+
let states = pack(&values, 3);
|
| 875 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [30, 1, 1], &palette, &states));
|
| 876 |
+
let g = parse(&data, 1000).unwrap();
|
| 877 |
+
assert_eq!(g.len(), 4);
|
| 878 |
+
let expected: Vec<Pos> = (0..30).filter(|i| i % 5 == 2).map(|i| (i, 0, 0)).collect();
|
| 879 |
+
assert_eq!(positions(&g[&key("b")]), expected);
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
#[test]
|
| 883 |
+
fn properties_are_sorted_in_name() {
|
| 884 |
+
let palette: Palette = vec![
|
| 885 |
+
("minecraft:air", vec![]),
|
| 886 |
+
("minecraft:oak_stairs", vec![("half", "bottom"), ("facing", "north")]),
|
| 887 |
+
];
|
| 888 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &palette, &pack(&[1], 2)));
|
| 889 |
+
let g = parse(&data, 10).unwrap();
|
| 890 |
+
assert!(g.contains_key(&key("oak_stairs[facing=north,half=bottom]")));
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
#[test]
|
| 894 |
+
fn multiple_regions_merge_sorted_by_region_name() {
|
| 895 |
+
let data = litematic(|o| {
|
| 896 |
+
region(o, "b", [10, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 897 |
+
region(o, "a", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 898 |
+
});
|
| 899 |
+
let g = parse(&data, 10).unwrap();
|
| 900 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0), (10, 0, 0)]);
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
#[test]
|
| 904 |
+
fn deterministic() {
|
| 905 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [3, 3, 3], &air_stone(), &pack(&[1; 27], 2)));
|
| 906 |
+
assert_eq!(parse(&data, 100).unwrap(), parse(&data, 100).unwrap());
|
| 907 |
+
}
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
// ---- имена без minecraft: ----
|
| 911 |
+
#[test]
|
| 912 |
+
fn block_names_lose_minecraft_prefix_only() {
|
| 913 |
+
let palette: Palette = vec![
|
| 914 |
+
("minecraft:air", vec![]),
|
| 915 |
+
("create:cogwheel", vec![]),
|
| 916 |
+
("minecraft:stone", vec![]),
|
| 917 |
+
];
|
| 918 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &palette, &pack(&[1, 2], 2)));
|
| 919 |
+
let g = parse(&data, 10).unwrap();
|
| 920 |
+
let mut names: Vec<&str> = g.keys().map(|k| k.0.as_str()).collect();
|
| 921 |
+
names.sort();
|
| 922 |
+
assert_eq!(names, vec!["create:cogwheel", "stone"]);
|
| 923 |
+
}
|
| 924 |
+
|
| 925 |
+
#[test]
|
| 926 |
+
fn stripped_name_keeps_properties() {
|
| 927 |
+
let palette: Palette = vec![
|
| 928 |
+
("minecraft:air", vec![]),
|
| 929 |
+
("minecraft:oak_stairs", vec![("facing", "north")]),
|
| 930 |
+
];
|
| 931 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &palette, &pack(&[1], 2)));
|
| 932 |
+
let g = parse(&data, 10).unwrap();
|
| 933 |
+
assert!(g.contains_key(&key("oak_stairs[facing=north]")));
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
// ---- сдвиг ----
|
| 937 |
+
#[test]
|
| 938 |
+
fn offset_shifts_positions() {
|
| 939 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 940 |
+
let g = parse_off(&data, [10, -20, 5]).unwrap();
|
| 941 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(10, -20, 5), (11, -20, 5)]);
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
#[test]
|
| 945 |
+
fn offset_adds_to_region_position() {
|
| 946 |
+
let data = litematic(|o| region(o, "r", [-5, 10, -1], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 947 |
+
let g = parse_off(&data, [100, 1, 1]).unwrap();
|
| 948 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(95, 11, 0)]);
|
| 949 |
+
}
|
| 950 |
+
|
| 951 |
+
#[test]
|
| 952 |
+
fn offset_with_negative_size() {
|
| 953 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [-2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 954 |
+
let g = parse_off(&data, [5, 0, 0]).unwrap();
|
| 955 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(4, 0, 0), (5, 0, 0)]);
|
| 956 |
+
}
|
| 957 |
+
|
| 958 |
+
#[test]
|
| 959 |
+
fn offset_applies_to_every_region() {
|
| 960 |
+
let data = litematic(|o| {
|
| 961 |
+
region(o, "a", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 962 |
+
region(o, "b", [10, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2));
|
| 963 |
+
});
|
| 964 |
+
let g = parse_off(&data, [0, 0, 7]).unwrap();
|
| 965 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 7), (10, 0, 7)]);
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
#[test]
|
| 969 |
+
fn offset_applies_to_tile_entities() {
|
| 970 |
+
let data = litematic(|o| {
|
| 971 |
+
region_te(
|
| 972 |
+
o,
|
| 973 |
+
"r",
|
| 974 |
+
[0, 0, 0],
|
| 975 |
+
[2, 1, 1],
|
| 976 |
+
&air_stone(),
|
| 977 |
+
&pack(&[1, 1], 2),
|
| 978 |
+
&[(1, 0, 0, "minecraft:chest")],
|
| 979 |
+
)
|
| 980 |
+
});
|
| 981 |
+
let g = parse_off(&data, [100, 0, 0]).unwrap();
|
| 982 |
+
let k = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 983 |
+
assert_eq!(positions(&g[&k]), vec![(101, 0, 0)]);
|
| 984 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(100, 0, 0)]);
|
| 985 |
+
}
|
| 986 |
+
|
| 987 |
+
#[test]
|
| 988 |
+
fn offset_pushing_out_of_cell_range_is_error() {
|
| 989 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 990 |
+
assert!(matches!(parse_off(&data, [10_000, 0, 0]), Err(NbtError::Coord(_))));
|
| 991 |
+
assert!(matches!(parse_off(&data, [0, -1000, 0]), Err(NbtError::Coord(_))));
|
| 992 |
+
assert!(parse_off(&data, [9_999, -999, 0]).is_ok());
|
| 993 |
+
}
|
| 994 |
+
|
| 995 |
+
#[test]
|
| 996 |
+
fn offset_overflowing_i32_is_error() {
|
| 997 |
+
let data = litematic(|o| region(o, "r", [1, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 998 |
+
assert!(matches!(parse_off(&data, [i32::MAX, 0, 0]), Err(NbtError::Malformed(_))));
|
| 999 |
+
}
|
| 1000 |
+
|
| 1001 |
+
// ---- tile entities ----
|
| 1002 |
+
#[test]
|
| 1003 |
+
fn tile_entity_splits_group_and_gets_snbt() {
|
| 1004 |
+
let data = litematic(|o| {
|
| 1005 |
+
region_te(
|
| 1006 |
+
o,
|
| 1007 |
+
"r",
|
| 1008 |
+
[0, 0, 0],
|
| 1009 |
+
[3, 1, 1],
|
| 1010 |
+
&air_stone(),
|
| 1011 |
+
&pack(&[1, 1, 1], 2),
|
| 1012 |
+
&[(1, 0, 0, "minecraft:chest")],
|
| 1013 |
+
)
|
| 1014 |
+
});
|
| 1015 |
+
let g = parse(&data, 10).unwrap();
|
| 1016 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0), (2, 0, 0)]);
|
| 1017 |
+
let with_nbt = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 1018 |
+
assert_eq!(positions(&g[&with_nbt]), vec![(1, 0, 0)]);
|
| 1019 |
+
}
|
| 1020 |
+
|
| 1021 |
+
#[test]
|
| 1022 |
+
fn tile_entity_on_air_or_outside_is_ignored() {
|
| 1023 |
+
let data = litematic(|o| {
|
| 1024 |
+
region_te(
|
| 1025 |
+
o,
|
| 1026 |
+
"r",
|
| 1027 |
+
[0, 0, 0],
|
| 1028 |
+
[2, 1, 1],
|
| 1029 |
+
&air_stone(),
|
| 1030 |
+
&pack(&[0, 1], 2),
|
| 1031 |
+
&[(0, 0, 0, "minecraft:chest"), (5, 0, 0, "minecraft:chest"), (-1, 0, 0, "x")],
|
| 1032 |
+
)
|
| 1033 |
+
});
|
| 1034 |
+
let g = parse(&data, 10).unwrap();
|
| 1035 |
+
assert_eq!(g.len(), 1);
|
| 1036 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(1, 0, 0)]);
|
| 1037 |
+
}
|
| 1038 |
+
|
| 1039 |
+
#[test]
|
| 1040 |
+
fn tile_entities_same_nbt_share_group() {
|
| 1041 |
+
let data = litematic(|o| {
|
| 1042 |
+
region_te(
|
| 1043 |
+
o,
|
| 1044 |
+
"r",
|
| 1045 |
+
[0, 0, 0],
|
| 1046 |
+
[2, 1, 1],
|
| 1047 |
+
&air_stone(),
|
| 1048 |
+
&pack(&[1, 1], 2),
|
| 1049 |
+
&[(0, 0, 0, "minecraft:chest"), (1, 0, 0, "minecraft:chest")],
|
| 1050 |
+
)
|
| 1051 |
+
});
|
| 1052 |
+
let g = parse(&data, 10).unwrap();
|
| 1053 |
+
assert_eq!(g.len(), 1);
|
| 1054 |
+
let k = ("stone".to_string(), r#"{"Lock":"minecraft:chest"}"#.to_string());
|
| 1055 |
+
assert_eq!(positions(&g[&k]), vec![(0, 0, 0), (1, 0, 0)]);
|
| 1056 |
+
}
|
| 1057 |
+
|
| 1058 |
+
// ---- SNBT ----
|
| 1059 |
+
#[test]
|
| 1060 |
+
fn dict_json_values_are_snbt_text() {
|
| 1061 |
+
let mut inner: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1062 |
+
inner.insert("Count".into(), Tag::Byte(1));
|
| 1063 |
+
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1064 |
+
m.insert("id".into(), Tag::String("minecraft:chest".into()));
|
| 1065 |
+
m.insert("x".into(), Tag::Int(1));
|
| 1066 |
+
m.insert("Lock".into(), Tag::String("a \"b\"".into()));
|
| 1067 |
+
m.insert("components".into(), Tag::Compound(BTreeMap::new()));
|
| 1068 |
+
m.insert("Empty".into(), Tag::List(vec![]));
|
| 1069 |
+
m.insert("Items".into(), Tag::List(vec![Tag::Compound(inner)]));
|
| 1070 |
+
let v: serde_json::Value =
|
| 1071 |
+
serde_json::from_str(&compound_dict_json(&m, &["x", "id"])).unwrap();
|
| 1072 |
+
assert_eq!(
|
| 1073 |
+
v,
|
| 1074 |
+
serde_json::json!({ "Items": "[{Count:1b}]", "Lock": "a \"b\"" })
|
| 1075 |
+
);
|
| 1076 |
+
}
|
| 1077 |
+
|
| 1078 |
+
#[test]
|
| 1079 |
+
fn snbt_scalars_and_quoting() {
|
| 1080 |
+
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1081 |
+
m.insert("id".into(), Tag::String("a\"b\\c".into()));
|
| 1082 |
+
m.insert("Count".into(), Tag::Byte(3));
|
| 1083 |
+
m.insert("a b".into(), Tag::Short(7));
|
| 1084 |
+
m.insert("l".into(), Tag::Long(5));
|
| 1085 |
+
m.insert("d".into(), Tag::Double(1.5));
|
| 1086 |
+
m.insert("f".into(), Tag::Float(2.0));
|
| 1087 |
+
assert_eq!(
|
| 1088 |
+
compound_snbt(&m, &[]),
|
| 1089 |
+
r#"{Count:3b,"a b":7s,d:1.5d,f:2f,id:"a\"b\\c",l:5L}"#
|
| 1090 |
+
);
|
| 1091 |
+
assert_eq!(compound_snbt(&m, &["id", "Count", "a b", "d", "f"]), "{l:5L}");
|
| 1092 |
+
}
|
| 1093 |
+
|
| 1094 |
+
#[test]
|
| 1095 |
+
fn snbt_lists_and_arrays() {
|
| 1096 |
+
let mut m: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1097 |
+
m.insert("list".into(), Tag::List(vec![Tag::Int(1), Tag::Int(2)]));
|
| 1098 |
+
m.insert("ints".into(), Tag::IntArray(&[0, 0, 0, 1, 0, 0, 0, 2]));
|
| 1099 |
+
m.insert("bytes".into(), Tag::ByteArray(&[1, 255]));
|
| 1100 |
+
m.insert("longs".into(), Tag::LongArray(&[0, 0, 0, 0, 0, 0, 0, 9]));
|
| 1101 |
+
let mut inner: BTreeMap<String, Tag> = BTreeMap::new();
|
| 1102 |
+
inner.insert("k".into(), Tag::Int(1));
|
| 1103 |
+
m.insert("c".into(), Tag::List(vec![Tag::Compound(inner)]));
|
| 1104 |
+
assert_eq!(
|
| 1105 |
+
compound_snbt(&m, &[]),
|
| 1106 |
+
"{bytes:[B;1b,-1b],c:[{k:1}],ints:[I;1,2],list:[1,2],longs:[L;9L]}"
|
| 1107 |
+
);
|
| 1108 |
+
}
|
| 1109 |
+
|
| 1110 |
+
// ---- ошибки и лимиты ----
|
| 1111 |
+
#[test]
|
| 1112 |
+
fn not_litematic_without_regions() {
|
| 1113 |
+
let mut data = Vec::new();
|
| 1114 |
+
named(&mut data, 10, "");
|
| 1115 |
+
int_named(&mut data, "Version", 6);
|
| 1116 |
+
data.push(0);
|
| 1117 |
+
assert!(matches!(parse(&data, 10), Err(NbtError::NotLitematic(_))));
|
| 1118 |
+
}
|
| 1119 |
+
|
| 1120 |
+
#[test]
|
| 1121 |
+
fn garbage_is_malformed() {
|
| 1122 |
+
assert!(matches!(parse(&[1, 2, 3], 10), Err(NbtError::Malformed(_))));
|
| 1123 |
+
assert!(matches!(parse(&[], 10), Err(NbtError::Malformed(_))));
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
#[test]
|
| 1127 |
+
fn truncated_is_malformed() {
|
| 1128 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 2], &air_stone(), &pack(&[0, 1, 1, 0], 2)));
|
| 1129 |
+
let cut = &data[..data.len() - 5];
|
| 1130 |
+
assert!(matches!(parse(cut, 10), Err(NbtError::Malformed(_))));
|
| 1131 |
+
}
|
| 1132 |
+
|
| 1133 |
+
#[test]
|
| 1134 |
+
fn index_outside_palette() {
|
| 1135 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[3], 2)));
|
| 1136 |
+
assert!(matches!(parse(&data, 10), Err(NbtError::Malformed(_))));
|
| 1137 |
+
}
|
| 1138 |
+
|
| 1139 |
+
#[test]
|
| 1140 |
+
fn states_too_short() {
|
| 1141 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [4, 4, 4], &air_stone(), &pack(&[1], 2)));
|
| 1142 |
+
assert!(matches!(parse(&data, 100), Err(NbtError::Malformed(_))));
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
#[test]
|
| 1146 |
+
fn block_limit() {
|
| 1147 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 1148 |
+
assert!(matches!(parse(&data, 1), Err(NbtError::TooManyBlocks(1))));
|
| 1149 |
+
assert!(parse(&data, 2).is_ok());
|
| 1150 |
+
}
|
| 1151 |
+
|
| 1152 |
+
#[test]
|
| 1153 |
+
fn cancel_flag_stops_parsing() {
|
| 1154 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [2, 1, 1], &air_stone(), &pack(&[1, 1], 2)));
|
| 1155 |
+
let cancel = AtomicBool::new(true);
|
| 1156 |
+
assert_eq!(parse_litematic(&data, 10, [0, 0, 0], &cancel), Err(NbtError::Cancelled));
|
| 1157 |
+
}
|
| 1158 |
+
|
| 1159 |
+
#[test]
|
| 1160 |
+
fn gz_roundtrip() {
|
| 1161 |
+
let data = litematic(|o| region(o, "r", [0, 0, 0], [1, 1, 1], &air_stone(), &pack(&[1], 2)));
|
| 1162 |
+
let g = parse_litematic_gz(&gzip(&data), &Limits::default(), [0, 0, 0], &AtomicBool::new(false)).unwrap();
|
| 1163 |
+
assert_eq!(positions(&g[&key("stone")]), vec![(0, 0, 0)]);
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
#[test]
|
| 1167 |
+
fn gunzip_limit_and_errors() {
|
| 1168 |
+
let gz = gzip(&vec![7u8; 1000]);
|
| 1169 |
+
assert_eq!(gunzip(&gz, 1000).unwrap().len(), 1000);
|
| 1170 |
+
assert!(matches!(gunzip(&gz, 999), Err(NbtError::TooLarge(999))));
|
| 1171 |
+
assert!(matches!(gunzip(b"<html>", 10), Err(NbtError::NotLitematic(_))));
|
| 1172 |
+
assert!(matches!(gunzip(&[], 10), Err(NbtError::NotLitematic(_))));
|
| 1173 |
+
let mut broken = gz.clone();
|
| 1174 |
+
broken.truncate(broken.len() / 2);
|
| 1175 |
+
assert!(gunzip(&broken, 1000).is_err());
|
| 1176 |
+
}
|
| 1177 |
+
|
| 1178 |
+
#[test]
|
| 1179 |
+
fn bits_for_palette_sizes() {
|
| 1180 |
+
// 2 бита минимум; 5 записей → 3 бита; 17 записей → 5 бит
|
| 1181 |
+
let bits = |n: usize| u64::from((usize::BITS - (n - 1).leading_zeros()).max(2));
|
| 1182 |
+
assert_eq!(bits(1), 2);
|
| 1183 |
+
assert_eq!(bits(4), 2);
|
| 1184 |
+
assert_eq!(bits(5), 3);
|
| 1185 |
+
assert_eq!(bits(16), 4);
|
| 1186 |
+
assert_eq!(bits(17), 5);
|
| 1187 |
+
}
|
| 1188 |
+
}
|
store.rs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Хранилище спарсенных схематик (в памяти процесса).
|
| 2 |
+
|
| 3 |
+
use std::collections::HashMap;
|
| 4 |
+
use std::sync::{Arc, RwLock};
|
| 5 |
+
|
| 6 |
+
use uuid::Uuid;
|
| 7 |
+
|
| 8 |
+
use crate::encoder::{self, EncodeError, Groups};
|
| 9 |
+
|
| 10 |
+
#[derive(Debug)]
|
| 11 |
+
pub struct Schematic {
|
| 12 |
+
/// Число уникальных блоков.
|
| 13 |
+
pub unique_blocks: usize,
|
| 14 |
+
/// Число уникальных NBT-записей (без «нет NBT»).
|
| 15 |
+
pub unique_nbt: usize,
|
| 16 |
+
/// Список блоков, нарезанный так, что JSON каждой части ≤ 24 000 символов.
|
| 17 |
+
pub block_parts: Vec<Vec<String>>,
|
| 18 |
+
/// Список NBT, нарезанный так же.
|
| 19 |
+
pub nbt_parts: Vec<Vec<String>>,
|
| 20 |
+
/// Весь текст схематики (ячейки по 28 символов).
|
| 21 |
+
pub text: String,
|
| 22 |
+
/// Конец каждой части текста (смещение в байтах).
|
| 23 |
+
pub part_ends: Vec<usize>,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
impl Schematic {
|
| 27 |
+
pub fn build(groups: &Groups) -> Result<Self, EncodeError> {
|
| 28 |
+
let e = encoder::encode(groups)?;
|
| 29 |
+
let block_parts = encoder::split_list(&e.blocks, encoder::DICT_PART_JSON_MAX)?;
|
| 30 |
+
let nbt_parts = encoder::split_nbt_list(&e.nbt, encoder::DICT_PART_JSON_MAX)?;
|
| 31 |
+
Ok(Schematic {
|
| 32 |
+
unique_blocks: e.blocks.len(),
|
| 33 |
+
unique_nbt: e.nbt.len(),
|
| 34 |
+
block_parts,
|
| 35 |
+
nbt_parts,
|
| 36 |
+
text: e.text,
|
| 37 |
+
part_ends: e.part_ends,
|
| 38 |
+
})
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
#[derive(Clone, Default)]
|
| 43 |
+
pub struct Store {
|
| 44 |
+
inner: Arc<RwLock<HashMap<Uuid, Arc<Schematic>>>>,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
impl Store {
|
| 48 |
+
pub fn insert(&self, schematic: Schematic) -> Uuid {
|
| 49 |
+
let id = Uuid::new_v4();
|
| 50 |
+
self.inner
|
| 51 |
+
.write()
|
| 52 |
+
.unwrap_or_else(|e| e.into_inner())
|
| 53 |
+
.insert(id, Arc::new(schematic));
|
| 54 |
+
id
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
pub fn get(&self, id: &Uuid) -> Option<Arc<Schematic>> {
|
| 58 |
+
self.inner
|
| 59 |
+
.read()
|
| 60 |
+
.unwrap_or_else(|e| e.into_inner())
|
| 61 |
+
.get(id)
|
| 62 |
+
.cloned()
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
#[cfg(test)]
|
| 67 |
+
mod tests {
|
| 68 |
+
use super::*;
|
| 69 |
+
|
| 70 |
+
fn sample() -> Schematic {
|
| 71 |
+
let mut cells = Vec::new();
|
| 72 |
+
encoder::push_position(&mut cells, 0, 0, 0).unwrap();
|
| 73 |
+
let mut groups = Groups::new();
|
| 74 |
+
groups.insert(("minecraft:stone".to_string(), String::new()), cells);
|
| 75 |
+
Schematic::build(&groups).unwrap()
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
#[test]
|
| 79 |
+
fn insert_and_get() {
|
| 80 |
+
let store = Store::default();
|
| 81 |
+
let id = store.insert(sample());
|
| 82 |
+
let got = store.get(&id).expect("должна найтись");
|
| 83 |
+
assert_eq!(got.unique_blocks, 1);
|
| 84 |
+
assert_eq!(got.unique_nbt, 0);
|
| 85 |
+
assert_eq!(got.part_ends.len(), 1);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
#[test]
|
| 89 |
+
fn missing_uuid() {
|
| 90 |
+
let store = Store::default();
|
| 91 |
+
assert!(store.get(&Uuid::new_v4()).is_none());
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
#[test]
|
| 95 |
+
fn ids_are_unique() {
|
| 96 |
+
let store = Store::default();
|
| 97 |
+
assert_ne!(store.insert(sample()), store.insert(sample()));
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
#[test]
|
| 101 |
+
fn build_empty() {
|
| 102 |
+
let s = Schematic::build(&Groups::new()).unwrap();
|
| 103 |
+
assert_eq!(s.unique_blocks, 0);
|
| 104 |
+
assert!(s.block_parts.is_empty());
|
| 105 |
+
assert!(s.nbt_parts.is_empty());
|
| 106 |
+
assert!(s.text.is_empty());
|
| 107 |
+
assert!(s.part_ends.is_empty());
|
| 108 |
+
}
|
| 109 |
+
}
|