summaryrefslogtreecommitdiffstats
path: root/src/WorldStorage/FastNBT.cpp
blob: df93e21e47532eba1e7bb0437b0d9b85262663c3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690

// FastNBT.cpp

// Implements the fast NBT parser and writer

#include "Globals.h"
#include "FastNBT.h"





// The number of NBT tags that are reserved when an NBT parsing is started.
// You can override this by using a cmdline define
#ifndef NBT_RESERVE_SIZE
	#define NBT_RESERVE_SIZE 200
#endif  // NBT_RESERVE_SIZE

#ifdef _MSC_VER
	// Dodge a C4127 (conditional expression is constant) for this specific macro usage
	#define PROPAGATE_ERROR(X) do { auto Err = (X); if (Err != eNBTParseError::npSuccess) return Err; } while ((false, false))
#else
	#define PROPAGATE_ERROR(X) do { auto Err = (X); if (Err != eNBTParseError::npSuccess) return Err; } while (false)
#endif



////////////////////////////////////////////////////////////////////////////////
// cNBTParseErrorCategory:

namespace
{

class cNBTParseErrorCategory final :
	public std::error_category
{
	cNBTParseErrorCategory() = default;
public:
	/** Category name */
	virtual const char * name() const noexcept override
	{
		return "NBT parse error";
	}

	/** Maps a parse error code to an error message */
	virtual AString message(int a_Condition) const override;

	/** Returns the canonical error category instance. */
	static const cNBTParseErrorCategory & Get() noexcept
	{
		static cNBTParseErrorCategory Category;
		return Category;
	}
};





AString cNBTParseErrorCategory::message(int a_Condition) const
{
	switch (static_cast<eNBTParseError>(a_Condition))
	{
		case eNBTParseError::npSuccess:
		{
			return "Parsing succeded";
		}
		case eNBTParseError::npNeedBytes:
		{
			return "Expected more data";
		}
		case eNBTParseError::npNoTopLevelCompound:
		{
			return "No top level compound tag";
		}
		case eNBTParseError::npStringMissingLength:
		{
			return "Expected a string length but had insufficient data";
		}
		case eNBTParseError::npStringInvalidLength:
		{
			return "String length invalid";
		}
		case eNBTParseError::npCompoundImbalancedTag:
		{
			return "Compound tag was unmatched at end of file";
		}
		case eNBTParseError::npListMissingType:
		{
			return "Expected a list type but had insuffiecient data";
		}
		case eNBTParseError::npListMissingLength:
		{
			return "Expected a list length but had insufficient data";
		}
		case eNBTParseError::npListInvalidLength:
		{
			return "List length invalid";
		}
		case eNBTParseError::npSimpleMissing:
		{
			return "Expected a numeric type but had insufficient data";
		}
		case eNBTParseError::npArrayMissingLength:
		{
			return "Expected an array length but had insufficient data";
		}
		case eNBTParseError::npArrayInvalidLength:
		{
			return "Array length invalid";
		}
		case eNBTParseError::npUnknownTag:
		{
			return "Unknown tag";
		}
	}
	UNREACHABLE("Unsupported nbt parse error");
}

}  // namespace (anonymous)





std::error_code make_error_code(eNBTParseError a_Err) noexcept
{
	return { static_cast<int>(a_Err), cNBTParseErrorCategory::Get() };
}





////////////////////////////////////////////////////////////////////////////////
// cParsedNBT:

#define NEEDBYTES(N, ERR) \
	do { \
		if (m_Data.size() - m_Pos < static_cast<size_t>(N)) \
		{ \
			return ERR; \
		} \
	} while (false)





cParsedNBT::cParsedNBT(const ContiguousByteBufferView a_Data) :
	m_Data(a_Data),
	m_Pos(0)
{
	m_Error = Parse();
}





eNBTParseError cParsedNBT::Parse(void)
{
	if (m_Data.size() < 3)
	{
		// Data too short
		return eNBTParseError::npNeedBytes;
	}
	if (m_Data[0] != std::byte(TAG_Compound))
	{
		// The top-level tag must be a Compound
		return eNBTParseError::npNoTopLevelCompound;
	}

	m_Tags.reserve(NBT_RESERVE_SIZE);

	m_Tags.emplace_back(TAG_Compound, -1);

	m_Pos = 1;

	PROPAGATE_ERROR(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength));
	return ReadCompound();
}





eNBTParseError cParsedNBT::ReadString(size_t & a_StringStart, size_t & a_StringLen)
{
	NEEDBYTES(2, eNBTParseError::npStringMissingLength);
	a_StringStart = m_Pos + 2;
	a_StringLen = static_cast<size_t>(GetBEShort(m_Data.data() + m_Pos));
	NEEDBYTES(2 + a_StringLen, eNBTParseError::npStringInvalidLength);
	m_Pos += 2 + a_StringLen;
	return eNBTParseError::npSuccess;
}





eNBTParseError cParsedNBT::ReadCompound(void)
{
	ASSERT(m_Tags.size() > 0);

	// Reads the latest tag as a compound
	size_t ParentIdx = m_Tags.size() - 1;
	int PrevSibling = -1;
	for (;;)
	{
		NEEDBYTES(1, eNBTParseError::npCompoundImbalancedTag);
		const auto TagTypeNum = m_Data[m_Pos];
		if ((TagTypeNum < std::byte(TAG_Min)) || (TagTypeNum > std::byte(TAG_Max)))
		{
			return eNBTParseError::npUnknownTag;
		}
		eTagType TagType = static_cast<eTagType>(TagTypeNum);
		m_Pos++;
		if (TagType == TAG_End)
		{
			break;
		}
		m_Tags.emplace_back(TagType, static_cast<int>(ParentIdx), PrevSibling);
		if (PrevSibling >= 0)
		{
			m_Tags[static_cast<size_t>(PrevSibling)].m_NextSibling = static_cast<int>(m_Tags.size()) - 1;
		}
		else
		{
			m_Tags[ParentIdx].m_FirstChild = static_cast<int>(m_Tags.size()) - 1;
		}
		PrevSibling = static_cast<int>(m_Tags.size()) - 1;
		PROPAGATE_ERROR(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength));
		PROPAGATE_ERROR(ReadTag());
	}  // while (true)
	m_Tags[ParentIdx].m_LastChild = PrevSibling;
	return eNBTParseError::npSuccess;
}





eNBTParseError cParsedNBT::ReadList(eTagType a_ChildrenType)
{
	// Reads the latest tag as a list of items of type a_ChildrenType

	// Read the count:
	NEEDBYTES(4, eNBTParseError::npListMissingLength);
	int Count = GetBEInt(m_Data.data() + m_Pos);
	m_Pos += 4;
	auto MinChildSize = GetMinTagSize(a_ChildrenType);
	if ((Count < 0) || (Count > static_cast<int>((m_Data.size() - m_Pos) / MinChildSize)))
	{
		return eNBTParseError::npListInvalidLength;
	}

	// Read items:
	ASSERT(m_Tags.size() > 0);
	size_t ParentIdx = m_Tags.size() - 1;
	int PrevSibling = -1;
	for (int i = 0; i < Count; i++)
	{
		m_Tags.emplace_back(a_ChildrenType, static_cast<int>(ParentIdx), PrevSibling);
		if (PrevSibling >= 0)
		{
			m_Tags[static_cast<size_t>(PrevSibling)].m_NextSibling = static_cast<int>(m_Tags.size()) - 1;
		}
		else
		{
			m_Tags[ParentIdx].m_FirstChild = static_cast<int>(m_Tags.size()) - 1;
		}
		PrevSibling = static_cast<int>(m_Tags.size()) - 1;
		PROPAGATE_ERROR(ReadTag());
	}  // for (i)
	m_Tags[ParentIdx].m_LastChild = PrevSibling;
	return eNBTParseError::npSuccess;
}





#define CASE_SIMPLE_TAG(TAGTYPE, LEN) \
	case TAG_##TAGTYPE: \
	{ \
		NEEDBYTES(LEN, eNBTParseError::npSimpleMissing); \
		Tag.m_DataStart = m_Pos; \
		Tag.m_DataLength = LEN; \
		m_Pos += LEN; \
		return eNBTParseError::npSuccess; \
	}

eNBTParseError cParsedNBT::ReadTag(void)
{
	cFastNBTTag & Tag = m_Tags.back();
	switch (Tag.m_Type)
	{
		CASE_SIMPLE_TAG(Byte,   1)
		CASE_SIMPLE_TAG(Short,  2)
		CASE_SIMPLE_TAG(Int,    4)
		CASE_SIMPLE_TAG(Long,   8)
		CASE_SIMPLE_TAG(Float,  4)
		CASE_SIMPLE_TAG(Double, 8)

		case TAG_String:
		{
			return ReadString(Tag.m_DataStart, Tag.m_DataLength);
		}

		case TAG_ByteArray:
		{
			NEEDBYTES(4, eNBTParseError::npArrayMissingLength);
			int len = GetBEInt(m_Data.data() + m_Pos);
			m_Pos += 4;
			if (len < 0)
			{
				// Invalid length
				return eNBTParseError::npArrayInvalidLength;
			}
			NEEDBYTES(len, eNBTParseError::npArrayInvalidLength);
			Tag.m_DataLength = static_cast<size_t>(len);
			Tag.m_DataStart = m_Pos;
			m_Pos += static_cast<size_t>(len);
			return eNBTParseError::npSuccess;
		}

		case TAG_List:
		{
			NEEDBYTES(1, eNBTParseError::npListMissingType);
			eTagType ItemType = static_cast<eTagType>(m_Data[m_Pos]);
			m_Pos++;
			PROPAGATE_ERROR(ReadList(ItemType));
			return eNBTParseError::npSuccess;
		}

		case TAG_Compound:
		{
			PROPAGATE_ERROR(ReadCompound());
			return eNBTParseError::npSuccess;
		}

		case TAG_IntArray:
		{
			NEEDBYTES(4, eNBTParseError::npArrayMissingLength);
			int len = GetBEInt(m_Data.data() + m_Pos);
			m_Pos += 4;
			if (len < 0)
			{
				// Invalid length
				return eNBTParseError::npArrayInvalidLength;
			}
			len *= 4;
			NEEDBYTES(len, eNBTParseError::npArrayInvalidLength);
			Tag.m_DataLength = static_cast<size_t>(len);
			Tag.m_DataStart = m_Pos;
			m_Pos += static_cast<size_t>(len);
			return eNBTParseError::npSuccess;
		}

		case TAG_Min:
		{
			return eNBTParseError::npUnknownTag;
		}
	}  // switch (iType)
	UNREACHABLE("Unsupported nbt tag type");
}

#undef CASE_SIMPLE_TAG





int cParsedNBT::FindChildByName(int a_Tag, const char * a_Name, size_t a_NameLength) const
{
	if (a_Tag < 0)
	{
		return -1;
	}
	if (m_Tags[static_cast<size_t>(a_Tag)].m_Type != TAG_Compound)
	{
		return -1;
	}

	if (a_NameLength == 0)
	{
		a_NameLength = strlen(a_Name);
	}
	for (int Child = m_Tags[static_cast<size_t>(a_Tag)].m_FirstChild; Child != -1; Child = m_Tags[static_cast<size_t>(Child)].m_NextSibling)
	{
		if (
			(m_Tags[static_cast<size_t>(Child)].m_NameLength == a_NameLength) &&
			(memcmp(m_Data.data() + m_Tags[static_cast<size_t>(Child)].m_NameStart, a_Name, a_NameLength) == 0)
		)
		{
			return Child;
		}
	}  // for Child - children of a_Tag
	return -1;
}





int cParsedNBT::FindTagByPath(int a_Tag, const AString & a_Path) const
{
	if (a_Tag < 0)
	{
		return -1;
	}
	size_t Begin = 0;
	size_t Length = a_Path.length();
	int Tag = a_Tag;
	for (size_t i = 0; i < Length; i++)
	{
		if (a_Path[i] != '\\')
		{
			continue;
		}
		Tag = FindChildByName(Tag, a_Path.c_str() + Begin, i - Begin);
		if (Tag < 0)
		{
			return -1;
		}
		Begin = i + 1;
	}  // for i - a_Path[]

	if (Begin < Length)
	{
		Tag = FindChildByName(Tag, a_Path.c_str() + Begin, Length - Begin);
	}
	return Tag;
}





size_t cParsedNBT::GetMinTagSize(eTagType a_TagType)
{
	switch (a_TagType)
	{
		case TAG_End:       return 1;
		case TAG_Byte:      return 1;
		case TAG_Short:     return 2;
		case TAG_Int:       return 4;
		case TAG_Long:      return 8;
		case TAG_Float:     return 4;
		case TAG_Double:    return 8;
		case TAG_String:    return 2;  // 2 bytes for the string length
		case TAG_ByteArray: return 4;  // 4 bytes for the count
		case TAG_List:      return 5;  // 1 byte list type + 4 bytes count
		case TAG_Compound:  return 1;  // Single TAG_End byte
		case TAG_IntArray:  return 4;  // 4 bytes for the count
	}
	UNREACHABLE("Unsupported nbt tag type");
}





////////////////////////////////////////////////////////////////////////////////
// cFastNBTWriter:

cFastNBTWriter::cFastNBTWriter(const AString & a_RootTagName) :
	m_CurrentStack(0)
{
	m_Stack[0].m_Type = TAG_Compound;
	m_Result.reserve(100 KiB);
	m_Result.push_back(std::byte(TAG_Compound));
	WriteString(a_RootTagName);
}





void cFastNBTWriter::BeginCompound(const AString & a_Name)
{
	if (m_CurrentStack >= MAX_STACK - 1)
	{
		ASSERT(!"Stack overflow");
		return;
	}

	TagCommon(a_Name, TAG_Compound);

	++m_CurrentStack;
	m_Stack[m_CurrentStack].m_Type = TAG_Compound;
}





void cFastNBTWriter::EndCompound(void)
{
	ASSERT(m_CurrentStack > 0);
	ASSERT(IsStackTopCompound());

	m_Result.push_back(std::byte(TAG_End));
	--m_CurrentStack;
}





void cFastNBTWriter::BeginList(const AString & a_Name, eTagType a_ChildrenType)
{
	if (m_CurrentStack >= MAX_STACK - 1)
	{
		ASSERT(!"Stack overflow");
		return;
	}

	TagCommon(a_Name, TAG_List);

	m_Result.push_back(std::byte(a_ChildrenType));
	m_Result.append(4, std::byte(0));

	++m_CurrentStack;
	m_Stack[m_CurrentStack].m_Type     = TAG_List;
	m_Stack[m_CurrentStack].m_Pos      = static_cast<int>(m_Result.size()) - 4;
	m_Stack[m_CurrentStack].m_Count    = 0;
	m_Stack[m_CurrentStack].m_ItemType = a_ChildrenType;
}





void cFastNBTWriter::EndList(void)
{
	ASSERT(m_CurrentStack > 0);
	ASSERT(m_Stack[m_CurrentStack].m_Type == TAG_List);

	// Update the list count:
	SetBEInt(m_Result.data() + m_Stack[m_CurrentStack].m_Pos, m_Stack[m_CurrentStack].m_Count);

	--m_CurrentStack;
}





void cFastNBTWriter::AddByte(const AString & a_Name, unsigned char a_Value)
{
	TagCommon(a_Name, TAG_Byte);
	m_Result.push_back(std::byte(a_Value));
}





void cFastNBTWriter::AddShort(const AString & a_Name, Int16 a_Value)
{
	TagCommon(a_Name, TAG_Short);
	UInt16 Value = htons(static_cast<UInt16>(a_Value));
	m_Result.append(reinterpret_cast<const std::byte *>(&Value), 2);
}





void cFastNBTWriter::AddInt(const AString & a_Name, Int32 a_Value)
{
	TagCommon(a_Name, TAG_Int);
	UInt32 Value = htonl(static_cast<UInt32>(a_Value));
	m_Result.append(reinterpret_cast<const std::byte *>(&Value), 4);
}





void cFastNBTWriter::AddLong(const AString & a_Name, Int64 a_Value)
{
	TagCommon(a_Name, TAG_Long);
	UInt64 Value = HostToNetwork8(&a_Value);
	m_Result.append(reinterpret_cast<const std::byte *>(&Value), 8);
}





void cFastNBTWriter::AddFloat(const AString & a_Name, float a_Value)
{
	TagCommon(a_Name, TAG_Float);
	UInt32 Value = HostToNetwork4(&a_Value);
	m_Result.append(reinterpret_cast<const std::byte *>(&Value), 4);
}





void cFastNBTWriter::AddDouble(const AString & a_Name, double a_Value)
{
	TagCommon(a_Name, TAG_Double);
	UInt64 Value = HostToNetwork8(&a_Value);
	m_Result.append(reinterpret_cast<const std::byte *>(&Value), 8);
}





void cFastNBTWriter::AddString(const AString & a_Name, const std::string_view a_Value)
{
	TagCommon(a_Name, TAG_String);
	const UInt16 Length = htons(static_cast<UInt16>(a_Value.size()));
	m_Result.append(reinterpret_cast<const std::byte *>(&Length), sizeof(Length));
	m_Result.append({ reinterpret_cast<const std::byte *>(a_Value.data()), a_Value.size() });
}





void cFastNBTWriter::AddByteArray(const AString & a_Name, const char * a_Value, size_t a_NumElements)
{
	TagCommon(a_Name, TAG_ByteArray);
	UInt32 len = htonl(static_cast<UInt32>(a_NumElements));
	m_Result.append(reinterpret_cast<const std::byte *>(&len), 4);
	m_Result.append(reinterpret_cast<const std::byte *>(a_Value), a_NumElements);
}





void cFastNBTWriter::AddByteArray(const AString & a_Name, size_t a_NumElements, unsigned char a_Value)
{
	TagCommon(a_Name, TAG_ByteArray);
	UInt32 len = htonl(static_cast<UInt32>(a_NumElements));
	m_Result.append(reinterpret_cast<const std::byte *>(&len), 4);
	m_Result.append(a_NumElements, std::byte(a_Value));
}





void cFastNBTWriter::AddIntArray(const AString & a_Name, const Int32 * a_Value, size_t a_NumElements)
{
	TagCommon(a_Name, TAG_IntArray);
	UInt32 len = htonl(static_cast<UInt32>(a_NumElements));
	size_t cap = m_Result.capacity();
	size_t size = m_Result.length();
	if ((cap - size) < (4 + a_NumElements * 4))
	{
		m_Result.reserve(size + 4 + (a_NumElements * 4));
	}
	m_Result.append(reinterpret_cast<const std::byte *>(&len), sizeof(len));
	for (size_t i = 0; i < a_NumElements; i++)
	{
		UInt32 Element = htonl(static_cast<UInt32>(a_Value[i]));
		m_Result.append(reinterpret_cast<const std::byte *>(&Element), sizeof(Element));
	}
}





void cFastNBTWriter::Finish(void)
{
	ASSERT(m_CurrentStack == 0);
	m_Result.push_back(std::byte(TAG_End));
}





void cFastNBTWriter::WriteString(const std::string_view a_Data)
{
	// TODO check size <= short max
	UInt16 Len = htons(static_cast<unsigned short>(a_Data.size()));
	m_Result.append(reinterpret_cast<const std::byte *>(&Len), sizeof(Len));
	m_Result.append(reinterpret_cast<const std::byte *>(a_Data.data()), a_Data.size());
}