spring-nbt-library 3.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. spring_nbt_library-3.0.1/.gitignore +37 -0
  2. spring_nbt_library-3.0.1/LICENSE +21 -0
  3. spring_nbt_library-3.0.1/PKG-INFO +47 -0
  4. spring_nbt_library-3.0.1/README.md +34 -0
  5. spring_nbt_library-3.0.1/pyproject.toml +27 -0
  6. spring_nbt_library-3.0.1/src/spring_nbt_library/__init__.py +24 -0
  7. spring_nbt_library-3.0.1/src/spring_nbt_library/anvil/__init__.py +24 -0
  8. spring_nbt_library-3.0.1/src/spring_nbt_library/anvil/folder.py +216 -0
  9. spring_nbt_library-3.0.1/src/spring_nbt_library/anvil/lz4.py +188 -0
  10. spring_nbt_library-3.0.1/src/spring_nbt_library/anvil/region.py +817 -0
  11. spring_nbt_library-3.0.1/src/spring_nbt_library/conformance.py +544 -0
  12. spring_nbt_library-3.0.1/src/spring_nbt_library/errors.py +78 -0
  13. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/__init__.py +74 -0
  14. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/_recursion.py +55 -0
  15. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/canonical.py +159 -0
  16. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/io.py +724 -0
  17. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/mutf8.py +172 -0
  18. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/snbt.py +900 -0
  19. spring_nbt_library-3.0.1/src/spring_nbt_library/nbt/tag.py +968 -0
  20. spring_nbt_library-3.0.1/src/spring_nbt_library/world/__init__.py +41 -0
  21. spring_nbt_library-3.0.1/src/spring_nbt_library/world/_chunk_format.py +191 -0
  22. spring_nbt_library-3.0.1/src/spring_nbt_library/world/_world_layout.py +231 -0
  23. spring_nbt_library-3.0.1/src/spring_nbt_library/world/bit_storage.py +203 -0
  24. spring_nbt_library-3.0.1/src/spring_nbt_library/world/block_pos.py +147 -0
  25. spring_nbt_library-3.0.1/src/spring_nbt_library/world/block_state.py +289 -0
  26. spring_nbt_library-3.0.1/src/spring_nbt_library/world/chunk.py +927 -0
  27. spring_nbt_library-3.0.1/src/spring_nbt_library/world/minecraft_world.py +613 -0
  28. spring_nbt_library-3.0.1/src/spring_nbt_library/world/paletted_container.py +332 -0
  29. spring_nbt_library-3.0.1/tests/test_anvil.py +548 -0
  30. spring_nbt_library-3.0.1/tests/test_block_pos.py +63 -0
  31. spring_nbt_library-3.0.1/tests/test_nbt.py +805 -0
  32. spring_nbt_library-3.0.1/tests/test_world.py +2018 -0
@@ -0,0 +1,37 @@
1
+ # --- OS ---
2
+ .DS_Store
3
+
4
+ # --- Rust ---
5
+ /rust/target/
6
+ **/*.rs.bk
7
+
8
+ # --- C# / .NET ---
9
+ /csharp/**/bin/
10
+ /csharp/**/obj/
11
+ *.user
12
+
13
+ # --- Java / Maven ---
14
+ /java/target/
15
+ /java/.mvn/wrapper/maven-wrapper.jar
16
+
17
+ # --- TypeScript / Node ---
18
+ node_modules/
19
+ /typescript/dist/
20
+ # npm packが作る配布用のtarball
21
+ /typescript/*.tgz
22
+
23
+ # --- Python ---
24
+ __pycache__/
25
+ *.py[cod]
26
+ /python/build/
27
+ /python/dist/
28
+ /python/*.egg-info/
29
+ /python/.pytest_cache/
30
+ .pytest_cache/
31
+ .venv/
32
+
33
+ # --- 適合性テストの実行結果(生成物) ---
34
+ /spec/out/
35
+
36
+ # --- リリース用に組み立てた成果物 ---
37
+ /artifacts/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ScriptArts
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.5
2
+ Name: spring-nbt-library
3
+ Version: 3.0.1
4
+ Summary: Minecraft Java EditionのNBT / Anvilワールドデータを読み書きするライブラリ
5
+ Project-URL: Repository, https://github.com/scriptarts/SpringNBTLibrary
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: anvil,mca,minecraft,nbt
9
+ Requires-Python: >=3.10
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=8.0; extra == 'dev'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # SpringNBTLibrary(Python版)
15
+
16
+ Minecraft Java版1.13以降のワールド・NBTファイルを読み書きするライブラリです。
17
+ Python 3.10以上で動きます。依存パッケージはありません。
18
+
19
+ 1.13から26.3までのワールドを、読んだときの形式のまま読み書きします。
20
+ これより新しいバージョンでも、形式が変わらない限りそのまま扱えます。
21
+
22
+ C# / Java / TypeScript / Python / Rust版があり、どれも同じ仕様書から作っています。
23
+ 同じ入力からは同じ結果が出ます([対応言語の一覧](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/README.md#対応言語))。
24
+ 結果が揃っているかは[適合性テスト](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/spec/90-conformance.md)で毎回確かめています。
25
+
26
+ ## 導入
27
+
28
+ PyPIから入れます。
29
+
30
+ ```bash
31
+ pip install spring-nbt-library
32
+ ```
33
+
34
+ [Releases](https://github.com/ScriptArts/SpringNBTLibrary/releases)から落としたwheelを、`pip install`で入れることもできます。
35
+
36
+ ## 使い方
37
+
38
+ - [はじめに(Python)](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/getting-started/python.md): まずここから
39
+ - [ガイド](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/guide/01-nbt.md): 目的別の使い方
40
+ - [API対応表](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/api/overview.md): 他言語版との対応
41
+ - [機能一覧](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/features.md): 何ができて何ができないか
42
+
43
+ 説明は[`docs/`](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/README.md)にまとめてあります。
44
+
45
+ ## ライセンス
46
+
47
+ MIT License — Copyright (c) 2026 ScriptArts
@@ -0,0 +1,34 @@
1
+ # SpringNBTLibrary(Python版)
2
+
3
+ Minecraft Java版1.13以降のワールド・NBTファイルを読み書きするライブラリです。
4
+ Python 3.10以上で動きます。依存パッケージはありません。
5
+
6
+ 1.13から26.3までのワールドを、読んだときの形式のまま読み書きします。
7
+ これより新しいバージョンでも、形式が変わらない限りそのまま扱えます。
8
+
9
+ C# / Java / TypeScript / Python / Rust版があり、どれも同じ仕様書から作っています。
10
+ 同じ入力からは同じ結果が出ます([対応言語の一覧](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/README.md#対応言語))。
11
+ 結果が揃っているかは[適合性テスト](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/spec/90-conformance.md)で毎回確かめています。
12
+
13
+ ## 導入
14
+
15
+ PyPIから入れます。
16
+
17
+ ```bash
18
+ pip install spring-nbt-library
19
+ ```
20
+
21
+ [Releases](https://github.com/ScriptArts/SpringNBTLibrary/releases)から落としたwheelを、`pip install`で入れることもできます。
22
+
23
+ ## 使い方
24
+
25
+ - [はじめに(Python)](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/getting-started/python.md): まずここから
26
+ - [ガイド](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/guide/01-nbt.md): 目的別の使い方
27
+ - [API対応表](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/api/overview.md): 他言語版との対応
28
+ - [機能一覧](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/features.md): 何ができて何ができないか
29
+
30
+ 説明は[`docs/`](https://github.com/ScriptArts/SpringNBTLibrary/blob/v3.0.1/docs/README.md)にまとめてあります。
31
+
32
+ ## ライセンス
33
+
34
+ MIT License — Copyright (c) 2026 ScriptArts
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "spring-nbt-library"
7
+ version = "3.0.1"
8
+ description = "Minecraft Java EditionのNBT / Anvilワールドデータを読み書きするライブラリ"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ keywords = ["minecraft", "nbt", "anvil", "mca"]
14
+ dependencies = []
15
+
16
+ [project.optional-dependencies]
17
+ dev = ["pytest>=8.0"]
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/scriptarts/SpringNBTLibrary"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/spring_nbt_library"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
27
+ pythonpath = ["src"]
@@ -0,0 +1,24 @@
1
+ """SpringNBTLibraryは、Minecraft Java版のNBT / Anvilワールドデータを読み書きするライブラリ
2
+
3
+ 対象は1.13以降のワールド形式 (DataVersion 1519以降)
4
+ """
5
+
6
+ from .errors import ErrorCode, SpringNbtError
7
+
8
+ #: このライブラリが扱えるワールド形式の下限となるDataVersion (1.13)
9
+ #:
10
+ #: 1.13でブロックの持ち方が数値のIDからパレットへ変わった
11
+ #: 1519は1.13の正式版のDataVersion
12
+ #: これ以降のチャンクは、読んだときの形式のまま読み書きできる
13
+ #: 1.16(DataVersion 2529)でビット詰めが値を64bitの境目でまたがない形に変わり、
14
+ #: 1.18(DataVersion 2844)でチャンクの本体が``Level``の外へ出て、
15
+ #: 26.3(DataVersion 5006)でパレットの要素の形が変わったが、どの形式も扱う
16
+ #: これより古いチャンクと、DataVersionの無いチャンク(1.9より前)は形式が違う
17
+ #: そうしたチャンクは、読み込み時は既定で警告を出し、書き戻しは既定でUNSUPPORTED_DATA_VERSIONにする
18
+ MIN_SUPPORTED_DATA_VERSION = 1519
19
+
20
+ #: 動作を確かめたMinecraft Java版のDataVersion (26.3)
21
+ TARGET_DATA_VERSION = 5023
22
+
23
+ __all__ = ["MIN_SUPPORTED_DATA_VERSION", "TARGET_DATA_VERSION",
24
+ "ErrorCode", "SpringNbtError"]
@@ -0,0 +1,24 @@
1
+ """Anvilのリージョンファイル(.mca)の読み書き
2
+ """
3
+
4
+ from .folder import RegionFolder
5
+ from .region import (
6
+ SECTOR_SIZE,
7
+ ChunkCompression,
8
+ ChunkPos,
9
+ RawChunk,
10
+ RegionFile,
11
+ RegionFileMode,
12
+ RegionPos,
13
+ )
14
+
15
+ __all__ = [
16
+ "SECTOR_SIZE",
17
+ "ChunkCompression",
18
+ "ChunkPos",
19
+ "RawChunk",
20
+ "RegionFile",
21
+ "RegionFileMode",
22
+ "RegionFolder",
23
+ "RegionPos",
24
+ ]
@@ -0,0 +1,216 @@
1
+ """リージョンファイルが並ぶディレクトリ1つ分
2
+
3
+ ``region/``、``entities/``、``poi/``のいずれかを表す
4
+ 開いたリージョンファイルはキャッシュし、:meth:`RegionFolder.close`でまとめて閉じる
5
+ チャンク座標からリージョンを解決するので、利用側はリージョンの存在を意識しなくてよい
6
+
7
+ :class:`RegionFile`はファイル全体をメモリへ載せるため、キャッシュには``max_cached_regions``件の上限がある
8
+ 上限を超えると、最も長く使われていないものから書き出して閉じる
9
+ 大きなワールドを端から走査してもメモリを使い切らない
10
+
11
+ このため:meth:`RegionFolder.region`が返した参照は、**別のリージョンへアクセスすると閉じられている場合がある**
12
+ 参照を保持せず、必要なたびに取得すること
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from collections import OrderedDict
19
+ from typing import Dict, List, Optional
20
+
21
+ from ..errors import ErrorCode, SpringNbtError
22
+ from ..nbt import NbtCompound
23
+ from .region import ChunkPos, RegionFile, RegionFileMode, RegionPos
24
+
25
+ __all__ = ["DEFAULT_MAX_CACHED_REGIONS", "RegionFolder"]
26
+
27
+ #: 同時に開いておくリージョンファイル数の既定の上限
28
+ #:
29
+ #: 1リージョンは最大255セクタ × 1024チャンク=理論上1GiBになりうる
30
+ #: 実データでは数MBから数十MB程度
31
+ #: 8件なら通常のワールドで数百MBに収まる
32
+ DEFAULT_MAX_CACHED_REGIONS = 8
33
+
34
+
35
+ class RegionFolder:
36
+ """リージョンフォルダ1つ分"""
37
+
38
+ def __init__(self, directory: str, mode: RegionFileMode,
39
+ max_cached_regions: int = DEFAULT_MAX_CACHED_REGIONS) -> None:
40
+ self.directory = directory
41
+ #: 同時に開いておくリージョンファイル数の上限
42
+ self.max_cached_regions = max_cached_regions
43
+ self._mode = mode
44
+ # 最近使った順を保つので、先頭がいちばん長く使っていないもの
45
+ self._cache: "OrderedDict[RegionPos, RegionFile]" = OrderedDict()
46
+ self._closed = False
47
+
48
+ @property
49
+ def cached_region_count(self) -> int:
50
+ """いま開いているリージョンファイル数"""
51
+ return len(self._cache)
52
+
53
+ @staticmethod
54
+ def open(directory: str,
55
+ mode: RegionFileMode = RegionFileMode.READ_ONLY,
56
+ max_cached_regions: int = DEFAULT_MAX_CACHED_REGIONS) -> "RegionFolder":
57
+ """リージョンフォルダを開く
58
+
59
+ :raises SpringNbtError: 読み取り専用でディレクトリが存在しない場合、または上限が1未満の場合
60
+ """
61
+ if max_cached_regions < 1:
62
+ raise SpringNbtError.invalid_argument(
63
+ "max_cached_regions は 1 以上でなければならない: %d" % max_cached_regions)
64
+
65
+ if not os.path.isdir(directory) and mode == RegionFileMode.READ_ONLY:
66
+ raise SpringNbtError(
67
+ ErrorCode.IO, "リージョンフォルダが存在しない: %s" % directory)
68
+
69
+ return RegionFolder(directory, mode, max_cached_regions)
70
+
71
+ def __enter__(self) -> "RegionFolder":
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
75
+ self.close()
76
+
77
+ def region_positions(self) -> List[RegionPos]:
78
+ """このフォルダに存在するリージョンの座標を返す"""
79
+ self._ensure_open()
80
+
81
+ if not os.path.isdir(self.directory):
82
+ return []
83
+
84
+ found = []
85
+
86
+ # r.X.Z.mcaとして解釈できるファイルだけを拾う
87
+ for name in os.listdir(self.directory):
88
+ position = RegionPos.from_file_name(name)
89
+
90
+ # r.X.Z.mcaとして解釈できるファイルだけを拾う
91
+ if position is not None:
92
+ found.append(position)
93
+
94
+ # 走査順がファイルシステム依存にならないよう、座標で並べる
95
+ found.sort(key=lambda position: (position.z, position.x))
96
+ return found
97
+
98
+ def region(self, region_x: int, region_z: int) -> Optional[RegionFile]:
99
+ """リージョンファイルを取得する
100
+ 読み取り専用で存在しなければNone
101
+ """
102
+ self._ensure_open()
103
+ position = RegionPos(region_x, region_z)
104
+ cached = self._cache.get(position)
105
+
106
+ if cached is not None:
107
+ # 使ったものを末尾へ移して、最近使った順を保つ
108
+ self._cache.move_to_end(position)
109
+ return cached
110
+
111
+ path = os.path.join(self.directory, position.file_name())
112
+
113
+ # 読み取り専用では、存在しないリージョンは「チャンクが無い」としてNoneを返す
114
+ if not os.path.exists(path) and self._mode == RegionFileMode.READ_ONLY:
115
+ return None
116
+
117
+ # 開く前に空きを作る
118
+ # 開いてからだと一瞬だけ上限を超える
119
+ self._evict_until_below_limit()
120
+
121
+ opened = RegionFile.open(path, self._mode)
122
+ self._cache[position] = opened
123
+ return opened
124
+
125
+ def _evict_until_below_limit(self) -> None:
126
+ """新しく1件開けるよう、上限を下回るまで古いものを閉じる"""
127
+ # 上限に達している間、いちばん長く使っていないものから閉じる
128
+ while len(self._cache) >= self.max_cached_regions:
129
+ _, oldest = self._cache.popitem(last=False)
130
+ # 閉じる前に必ず書き出す
131
+ # 捨てると変更が失われる
132
+ oldest.close()
133
+
134
+ def has_chunk(self, chunk_x: int, chunk_z: int) -> bool:
135
+ """チャンクが存在するか"""
136
+ file = self._region_for(chunk_x, chunk_z)
137
+
138
+ if file is None:
139
+ return False
140
+
141
+ return file.has_chunk(chunk_x, chunk_z)
142
+
143
+ def read_chunk(self, chunk_x: int, chunk_z: int) -> Optional[NbtCompound]:
144
+ """チャンクをNBTとして読む
145
+ 存在しなければNone
146
+ """
147
+ file = self._region_for(chunk_x, chunk_z)
148
+
149
+ if file is None:
150
+ return None
151
+
152
+ return file.read_chunk(chunk_x, chunk_z)
153
+
154
+ def write_chunk(self, chunk_x: int, chunk_z: int, tag: NbtCompound) -> None:
155
+ """チャンクをNBTとして書き込む"""
156
+ file = self._region_for(chunk_x, chunk_z)
157
+
158
+ if file is None:
159
+ raise SpringNbtError.invalid_argument(
160
+ "読み取り専用のフォルダには書き込めない: %s" % self.directory)
161
+
162
+ file.write_chunk(chunk_x, chunk_z, tag)
163
+
164
+ def delete_chunk(self, chunk_x: int, chunk_z: int) -> bool:
165
+ """チャンクを削除する
166
+ 削除できたらTrue
167
+ """
168
+ file = self._region_for(chunk_x, chunk_z)
169
+
170
+ if file is None:
171
+ return False
172
+
173
+ return file.delete_chunk(chunk_x, chunk_z)
174
+
175
+ def chunk_positions(self) -> List[ChunkPos]:
176
+ """このフォルダに存在する全チャンクの座標を返す"""
177
+ result = []
178
+
179
+ # リージョンごとに、その中のチャンクを順に集める
180
+ for position in self.region_positions():
181
+ file = self.region(position.x, position.z)
182
+
183
+ if file is None:
184
+ continue
185
+
186
+ result.extend(file.chunk_positions())
187
+
188
+ return result
189
+
190
+ def flush(self) -> None:
191
+ """開いている全リージョンの変更を書き出す"""
192
+ self._ensure_open()
193
+
194
+ # 開いているリージョンをすべて書き出す
195
+ for file in self._cache.values():
196
+ file.flush()
197
+
198
+ def close(self) -> None:
199
+ """開いている全リージョンを閉じる"""
200
+ if self._closed:
201
+ return
202
+
203
+ # 開いているリージョンをすべて閉じる
204
+ for file in self._cache.values():
205
+ file.close()
206
+
207
+ self._cache.clear()
208
+ self._closed = True
209
+
210
+ def _region_for(self, chunk_x: int, chunk_z: int) -> Optional[RegionFile]:
211
+ position = ChunkPos(chunk_x, chunk_z).region()
212
+ return self.region(position.x, position.z)
213
+
214
+ def _ensure_open(self) -> None:
215
+ if self._closed:
216
+ raise SpringNbtError.invalid_argument("既に閉じられたリージョンフォルダ")
@@ -0,0 +1,188 @@
1
+ """圧縮方式ID 4(LZ4)のチャンクを展開する
2
+
3
+ 素のLZ4ブロックでもLZ4フレーム形式でもなく、独自ヘッダを持つブロックの連結である
4
+
5
+ 書き込みには対応しない
6
+ NBTとして書き戻すときは既定でZlibになり、生バイトのまま書き戻すとLZ4のまま残る
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import struct
12
+
13
+ from ..errors import SpringNbtError
14
+
15
+ __all__ = ["decompress_lz4"]
16
+
17
+ #: ブロックの先頭に必ず置かれる8バイト
18
+ MAGIC = b"LZ4Block"
19
+
20
+ #: ブロックヘッダの長さ
21
+ HEADER_LENGTH = 21
22
+
23
+ #: トークン上位4ビット: 本体が無圧縮
24
+ METHOD_STORED = 0x10
25
+
26
+ #: トークン上位4ビット: 本体がLZ4圧縮
27
+ METHOD_COMPRESSED = 0x20
28
+
29
+ #: マッチの最小長
30
+ MIN_MATCH = 4
31
+
32
+
33
+ def decompress_lz4(payload: bytes) -> bytes:
34
+ """LZ4Blockの連結を展開する
35
+
36
+ :raises SpringNbtError: 形式に反する入力の場合(MALFORMED_DATA)
37
+ """
38
+ blocks = []
39
+ position = 0
40
+
41
+ # 入力を使い切るまでブロックを読み続ける
42
+ while position < len(payload):
43
+ data, position = _decompress_block(payload, position)
44
+ blocks.append(data)
45
+
46
+ return b"".join(blocks)
47
+
48
+
49
+ def _decompress_block(payload: bytes, position: int):
50
+ """ブロックを1つ展開し、中身と次のブロックの開始位置を返す"""
51
+ if position + HEADER_LENGTH > len(payload):
52
+ raise SpringNbtError.malformed(
53
+ "LZ4: ブロックヘッダが足りない(%d バイト)" % (len(payload) - position))
54
+
55
+ # マジックが違えばそもそもLZ4Blockではない
56
+ if payload[position:position + len(MAGIC)] != MAGIC:
57
+ raise SpringNbtError.malformed("LZ4: ブロックが LZ4Block で始まっていない")
58
+
59
+ method = payload[position + 8] & 0xF0
60
+ compressed_length = struct.unpack_from("<i", payload, position + 9)[0]
61
+ original_length = struct.unpack_from("<i", payload, position + 13)[0]
62
+ body = position + HEADER_LENGTH
63
+
64
+ _validate_lengths(compressed_length, original_length)
65
+
66
+ if body + compressed_length > len(payload):
67
+ raise SpringNbtError.malformed("LZ4: ブロック本体が入力からはみ出している")
68
+
69
+ if method == METHOD_STORED:
70
+ # 無圧縮なら2つの長さは一致していなければならない
71
+ if compressed_length != original_length:
72
+ raise SpringNbtError.malformed(
73
+ "LZ4: 無圧縮ブロックの長さが食い違う(%d と %d)"
74
+ % (compressed_length, original_length))
75
+
76
+ return payload[body:body + compressed_length], body + compressed_length
77
+
78
+ # 圧縮されているなら素のLZ4ブロックとして展開する
79
+ if method == METHOD_COMPRESSED:
80
+ data = _decompress_raw_block(
81
+ payload[body:body + compressed_length], original_length)
82
+ return data, body + compressed_length
83
+
84
+ raise SpringNbtError.malformed("LZ4: 未知の圧縮方式 0x%02X" % method)
85
+
86
+
87
+ def _validate_lengths(compressed_length: int, original_length: int) -> None:
88
+ """ヘッダに書かれた2つの長さが妥当か調べる"""
89
+ if compressed_length < 0 or original_length < 0:
90
+ raise SpringNbtError.malformed("LZ4: ブロックの長さが負値")
91
+
92
+ # 片方だけが0になることはない
93
+ if (compressed_length == 0) != (original_length == 0):
94
+ raise SpringNbtError.malformed("LZ4: ブロックの長さが片方だけ 0")
95
+
96
+
97
+ def _decompress_raw_block(source: bytes, original_length: int) -> bytes:
98
+ """素のLZ4ブロックを展開する"""
99
+ output = bytearray(original_length)
100
+ position = 0
101
+ written = 0
102
+
103
+ # シーケンスを順に読む
104
+ while position < len(source):
105
+ token = source[position]
106
+ position += 1
107
+
108
+ literal_length = token >> 4
109
+
110
+ # 15なら追加バイトで長さが続く
111
+ if literal_length == 15:
112
+ extra, position = _read_length(source, position)
113
+ literal_length += extra
114
+
115
+ written, position = _copy_literals(
116
+ source, position, output, written, literal_length)
117
+
118
+ # リテラルを出し切って入力が尽きたら、そこで終わり
119
+ if position >= len(source):
120
+ break
121
+
122
+ if position + 2 > len(source):
123
+ raise SpringNbtError.malformed("LZ4: オフセットが入力からはみ出している")
124
+
125
+ offset = source[position] | (source[position + 1] << 8)
126
+ position += 2
127
+
128
+ if offset == 0 or offset > written:
129
+ raise SpringNbtError.malformed("LZ4: マッチのオフセットが不正: %d" % offset)
130
+
131
+ match_length = (token & 0x0F) + MIN_MATCH
132
+
133
+ # 下位4ビットが15なら追加バイトで長さが続く
134
+ if (token & 0x0F) == 15:
135
+ extra, position = _read_length(source, position)
136
+ match_length += extra
137
+
138
+ written = _copy_match(output, written, offset, match_length)
139
+
140
+ if written != original_length:
141
+ raise SpringNbtError.malformed(
142
+ "LZ4: 展開後の長さが合わない(%d と %d)" % (written, original_length))
143
+
144
+ return bytes(output)
145
+
146
+
147
+ def _read_length(source: bytes, position: int):
148
+ """255が続く形式の追加長さを読む"""
149
+ total = 0
150
+
151
+ # 255未満のバイトが出るまで足し続ける
152
+ while True:
153
+ if position >= len(source):
154
+ raise SpringNbtError.malformed("LZ4: 長さの追加バイトが途中で切れた")
155
+
156
+ value = source[position]
157
+ position += 1
158
+ total += value
159
+
160
+ if value != 255:
161
+ return total, position
162
+
163
+
164
+ def _copy_literals(source: bytes, position: int, output: bytearray,
165
+ written: int, length: int):
166
+ """リテラルをそのまま出力へ写す"""
167
+ if position + length > len(source):
168
+ raise SpringNbtError.malformed("LZ4: リテラルが入力からはみ出している")
169
+
170
+ if written + length > len(output):
171
+ raise SpringNbtError.malformed("LZ4: 展開後の長さを超えた")
172
+
173
+ output[written:written + length] = source[position:position + length]
174
+ return written + length, position + length
175
+
176
+
177
+ def _copy_match(output: bytearray, written: int, offset: int, length: int) -> int:
178
+ """出力済みのバイト列からマッチを写す"""
179
+ if written + length > len(output):
180
+ raise SpringNbtError.malformed("LZ4: 展開後の長さを超えた")
181
+
182
+ start = written - offset
183
+
184
+ # コピー元と先は重なりうるので1バイトずつ写す
185
+ for index in range(length):
186
+ output[written + index] = output[start + index]
187
+
188
+ return written + length