Skip to content

Releases

v2.1.0

Choose a tag to compare

@mstefarov mstefarov released this 10 Sep 01:47

fNbt 2.1 adds support for SNBT (stringified NBT), the text form of NBT that Minecraft Java uses in commands, data packs, and .snbt files. It also relaxes constraints on duplicate tag names and empty lists to improve compatibility.

SNBT

NbtTag.ParseSnbt reads a value and NbtTag.ToSnbt writes one to a string:

NbtTag tag = NbtTag.ParseSnbt("{Name:\"Steve\",Health:20.0f}");
string compact = tag.ToSnbt(); // {Name:"Steve",Health:20.0f}
string indented = tag.ToSnbt(new SnbtOptions { WriteLayout = SnbtLayout.Indented });

Choose Compact (the default), Spaced, or Indented layout. Parsing returns an unnamed tag of any type. Errors throw SnbtParseException, derived from NbtFormatException, with the index, line, and column.

To read one SNBT value from a longer string, such as a command line, pass a starting index to ParseSnbt. It stops after that value and reports how many characters it consumed:

string command = "data merge block 0 64 0 {Lock:\"key\"} extra";
int at = command.IndexOf('{');
NbtTag value = NbtTag.ParseSnbt(command, at, out int consumed);   // {Lock:"key"}, consumed 12

What parses

The parser accepts older and modern Minecraft Java syntax, plus forms used by common NBT tools:

  • Hex and binary integers (0x1F, 0b1010), digit separators (1_000), signedness suffixes (255ub, -1sb), and the bool() and uuid() operations.
  • Older numeric forms: tokens with leading zeros (007) and out-of-range integers (300b) read as strings; overflowing floats read as infinities.
  • Quoted strings with modern escapes such as \n and \u00e9. Named Unicode escapes (\N{name}) are unsupported.
  • Non-finite numbers (NaNf, Infinityd), quoted empty keys, true and false, and byte literals in either signed or unsigned range (255b and -1b parse the same).
  • Lists of mixed types, stored using the compound wrappers described below.

What writes

Every layout uses the same output conventions:

  • String values use double quotes, with quotes and backslashes escaped. Keys use quotes when needed.
  • Compounds keep insertion order.
  • Numbers use Java's spelling and suffixes (1.0E10d, 4.9E-324d).
  • Bytes print signed (a Value of 255 prints as -1b). The new NbtByte.SignedValue property exposes that signed view.

Non-finite numbers and empty keys print too. fNbt reads them back as the same values; Minecraft does not.

Lists of mixed types

Minecraft Java 1.21.5 introduced mixed SNBT lists. Converted to regular NBT they become lists of compounds, wrapping any non-compound values under an empty key. Use NbtList.CreateMixed to build lists in this form, or UnwrapMixed to read through it:

NbtList line = NbtList.CreateMixed(
    new NbtString("Hello "),
    new NbtCompound { new NbtString("text", "world") });
string snbt = line.ToSnbt(); // ["Hello ",{text:"world"}]
NbtTag[] parts = ((NbtList)NbtTag.ParseSnbt(snbt)).UnwrapMixed(); // NbtString, NbtCompound

Performance

Benchmarks against 2.0.0 show about 2x faster metadata comparisons, 1.25x faster metadata cloning and Bedrock palette writes to exact buffers, and faster array reads on .NET 8 and .NET Framework 4.8.

Upgrading from 2.0

Most fNbt 2.0 code compiles unchanged. A few behavior changes to keep in mind:

  • Empty lists with Unknown or End element type accept their first tag and adopt its type. Untyped empty lists now save with TAG_End as their element type; explicitly typed lists retain their constraint.
  • NbtComparer ignores empty lists' element type (but still compares their names).
  • Loading a compound with repeated names keeps the last value in the first tag's position. ValidateOnRead rejects duplicate members when materializing the compound. Skipped members and NbtReader's streaming traversal do not track duplicates.
  • NbtReader enum conversions throw OverflowException when the value does not fit the enum's underlying type. ReadListAsArray<T> also checks MaxAllocation using the result element's (T's) size.
  • NbtOptions.MaxAllocation setter now rejects zero and negative values, instead of throwing later when the options are first used.

API Reference

fNbt 2.1 API reference

Full API diff
 abstract class NbtTag {
+    static NbtTag ParseSnbt(string text);
+    static NbtTag ParseSnbt(string text, int index, out int charsConsumed);
+    string ToSnbt();
+    string ToSnbt(SnbtOptions options);
 }

 sealed class NbtList {
+    static NbtList CreateMixed(params NbtTag[] elements);
+    NbtTag[] UnwrapMixed();
 }

 sealed class NbtByte {
+    sbyte SignedValue { get; set; }
 }

+enum SnbtLayout {
+    Compact,
+    Spaced,
+    Indented
+}

+sealed class SnbtOptions {
+    SnbtOptions();
+    static SnbtLayout DefaultWriteLayout { get; set; }
+    SnbtLayout WriteLayout { get; set; }
+}

+[Serializable]
+sealed class SnbtParseException : NbtFormatException {
+    int Index { get; }
+    int Line { get; }
+    int Column { get; }
+}

v2.0.0

Choose a tag to compare

@mstefarov mstefarov released this 04 Sep 06:53

fNbt 2.0 adds seven NBT flavors to expand compatibility with the broader Minecraft ecosystem, introduces NbtCodec for raw and embedded NBT, improves performance, fixes many small bugs, and is more robust against bad inputs. This release has a few minor breaking changes, so see "Upgrading from 1.x" below.

NBT flavors

NbtFlavor defines the byte order, tag types, string limits, and root format for each supported encoding:

Flavor Byte order Highest tag type String limit Used by
Java (default) big-endian TAG_Long_Array 65,535 bytes Minecraft Java 1.12 and later; reads every older Java file
JavaAnvil big-endian TAG_Int_Array 65,535 bytes Java 1.2.1 through 1.11
JavaLegacy big-endian TAG_Compound 65,535 bytes Indev through Java 1.1
JavaNetwork big-endian TAG_Long_Array 65,535 bytes Java protocol 764 (1.20.2) and later; unnamed root of any type
Bedrock little-endian TAG_Int_Array 32,767 bytes Bedrock level.dat, .mcstructure, LevelDB values
BedrockNetwork little-endian, varints TAG_Int_Array unbounded Bedrock network protocol, 0.16 and later
ClassiCube big-endian TAG_Compound 256 bytes ClassicWorld (.cw) maps, as the ClassiCube client loads them

Pass a flavor to NbtFile, NbtReader, NbtWriter, or NbtCodec, or set NbtOptions.DefaultFlavor at startup. A flavor describes an encoding rather than a product or file extension.

JavaNetwork has no root name, so only NbtCodec accepts it. BedrockNetwork uses zigzag varints for TAG_Int, TAG_Long, and container lengths, unsigned varints for string lengths, and fixed-width little-endian encoding for everything else.

The Java and ClassiCube flavors now write modified UTF-8 like Minecraft Java. Every flavor reads both modified and standard UTF-8, and malformed string bytes throw NbtFormatException.

NbtOptions and validation

NbtOptions holds the flavor, ValidateOnWrite, ValidateOnRead, and MaxAllocation. Write validation is on by default and rejects unsupported tags or over-limit strings before an operation writes any bytes. Read validation is off by default, so any parsable NBT document loads. Turn on ValidateOnRead to parse less generously, rejecting documents that the selected flavor cannot represent. MaxAllocation is an optional limit on any single allocation a declared length requests, useful when parsing untrusted input.

NbtOptions.DefaultMaxAllocation = 64 * 1024 * 1024;
var options = new NbtOptions(NbtFlavor.Bedrock) { ValidateOnWrite = false };
new NbtFile(root, options).SaveToFile("structure.nbt", NbtCompression.None);

Every setting has a process-wide default on NbtOptions (DefaultFlavor, DefaultValidateOnRead, DefaultValidateOnWrite, DefaultMaxAllocation). Set them at startup.

NbtCodec

If you work with packet payloads, Bedrock LevelDB values, or blobs embedded in other formats, then NbtFile is an awkward fit. It wants a named compound root, it wants the whole stream, and it cannot say where the document ended. NbtCodec is the new API for you:

  • Reads stop exactly at the end of one document and report the bytes consumed, leaving trailing data in place.
  • JavaNetwork's unnamed roots of any type are supported, including the lone TAG_End byte.
  • ReadConcatenatedTags and WriteConcatenatedTags handle back-to-back documents, such as a LevelDB value holding several roots, reusing one reader or writer for the whole sequence.
  • Input is a Stream, a byte array segment, or a ReadOnlySpan<byte> (.NET 8+).
  • Output is a Stream, a new exactly-sized byte array, or an IBufferWriter<byte> (.NET 8+).
NbtCodec codec = NbtCodec.For(NbtFlavor.JavaNetwork);   // shared instance, default options
NbtTag root = codec.ReadTag(stream);
byte[] bytes = codec.WriteTag(root);

Codecs are immutable and thread-safe. Construct one with NbtOptions, or use NbtCodec.For(flavor) with the current defaults.

Performance

A lot of work went into making 2.0 more efficient on real Minecraft data: parsing many small tags, skipping the data you did not ask for, and writing documents back out. These benchmarks compare 2.0 with fNbt 1.1.1 on .NET 8.

Reading

Faster Memory
Load a small map (GZip) same 26% less
Parse the metadata subtree (9,300 small tags) 1.2x 44% less
Parse 2,000 compounds with repeated tag names 1.5x 51% less
Skip the metadata subtree with a selector 1.1x 99.5% less

Writing

Faster Memory
Write the metadata subtree to an exact-size buffer 1.5x same
SaveToBuffer, small map, uncompressed 1.35x same
SaveToBuffer, medium map, ZLib 1.2x 73% less
NbtFile.SaveToStream, 1,000 small tags 1.1x 15% less

Editing and comparing

Faster Memory
Deep clone the metadata subtree 1.5x 31% less
Look up a nested tag 1.5x none
Add 1,000 tags to one compound 1.3x 33% less
Compare equal 128 KB arrays with NbtComparer 4x to 30x none

Other Changes

  • NbtCompound now enumerates, prints, and saves children in insertion order.
  • Compressed loads now verify checksums on .NET Standard 2.0 and non-seekable streams too.
  • NbtWriter tries to reject format violations before changing the stream. A failure that results in a partial write now puts the writer in an error state (reported by IsInErrorState).
  • NbtWriter.WriteIntArray and WriteLongArray now write the correct elements when offset is non-zero.
  • NbtReader fixes cover bulk reads from a list element, stale cached values, ReadAsTag after a cached read, and offsets past 2 GiB. Use LongTagStartOffset property if your files are huge.
  • NbtReader.ReadValueAs<T> now converts numeric and string values, as ReadListAsArray<T> already did. For example, a TAG_Int can be read as a long, double, string, or enum (by value). A TAG_String can be read as a number or enum (by name). Enum support is new to both methods.
  • Negative list and array lengths load as empty, and empty lists may declare any element type.
  • All recursive operations enforce the same 512-level depth limit.

Upgrading from 1.x

Most 1.x code compiles and behaves as before. Check these differences:

  • The bool constructors of NbtReader and NbtWriter and the bool ReadRootTagName overloads are obsolete, but still work by choosing a Flavor (true is Java, false is Bedrock).
  • NbtFile.BigEndian and NbtFile.BigEndianByDefault are now read-only and obsolete. NbtFile.Flavor is fixed at construction. To re-save under another flavor, create a new NbtFile over the same RootTag.
  • Little-endian writes now use the Bedrock flavor and reject TAG_Long_Array and strings over 32,767 bytes. Set ValidateOnWrite = false to allow the old output.
  • Malformed strings throw NbtFormatException on load instead of decoding to U+FFFD, and corrupt compressed data throws InvalidDataException where 1.x sometimes loaded it.
  • Compounds use insertion order, including after removals, and negative lengths load as empty.
  • A compressed load from a seekable stream leaves it at the stream's end, and its byte count includes everything read. Uncompressed loads and NbtCodec stop at the document boundary.
  • NbtWriter throws after a write fails during output; check IsInErrorState.
  • AssemblyVersion is now 2.0.0.0 and remains there for 2.x.
  • Releases now contain the NuGet package only; the single-file amalgamation is gone.

API Reference

https://fcraft.net/fnbt/v2.0.0/

Full API diff

New APIs:

 sealed class NbtFile {
+    NbtFile(NbtFlavor flavor);
+    NbtFile(NbtOptions options);
+    NbtFile(NbtCompound rootTag, NbtFlavor flavor);
+    NbtFile(NbtCompound rootTag, NbtOptions options);
+    NbtFlavor Flavor { get; }
+    static string ReadRootTagName(string fileName, NbtCompression compression, NbtFlavor flavor);
+    static string ReadRootTagName(Stream stream, NbtCompression compression, NbtFlavor flavor);
 }

 class NbtReader {
+    NbtReader(Stream stream, NbtFlavor flavor);
+    NbtReader(Stream stream, NbtOptions options);
+    NbtFlavor Flavor { get; }
+    long LongTagStartOffset { get; }
 }

 sealed class NbtWriter {
+    NbtWriter(Stream stream, string rootTagName, NbtFlavor flavor);
+    NbtWriter(Stream stream, string rootTagName, NbtOptions options);
+    NbtFlavor Flavor { get; }
+    bool IsInErrorState { get; }
 }

+sealed class NbtFlavor {
+    static NbtFlavor Java { get; }
+    static NbtFlavor JavaAnvil { get; }
+    static NbtFlavor JavaLegacy { get; }
+    static NbtFlavor JavaNetwork { get; }
+    static NbtFlavor Bedrock { get; }
+    static NbtFlavor BedrockNetwork { get; }
+    static NbtFlavor ClassiCube { get; }
+    string Name { get; }
+    bool BigEndian { get; }
+    bool UsesVarInts { get; }
+    bool UsesModifiedUtf8 { get; }
+    bool HasRootName { get; }
+    bool AllowsNonCompoundRoot { get; }
+    NbtTagType MaxTagType { get; }
+    int MaxStringBytes { get; }
+    override string ToString();
+}

+sealed class NbtOptions {
+    NbtOptions();
+    NbtOptions(NbtFlavor flavor);
+    static NbtFlavor DefaultFlavor { get; set; }
+    static bool DefaultValidateOnRead { get; set; }
+    static bool DefaultValidateOnWrite { get; set; }
+    static long DefaultMaxAllocation { get; set; }
+    NbtFlavor Flavor { get; set; }
+    bool ValidateOnRead { get; set; }
+    bool ValidateOnWrite { get; set; }
+    long MaxAllocation { get; set; }
+}

+sealed class NbtCodec {
+    NbtCodec(NbtFlavor flavor);
+    NbtCodec(NbtOptions options);
+    static NbtCodec For(NbtFlavor flavor);
+    NbtFlavor F...
Read more

v1.1.1

Choose a tag to compare

@mstefarov mstefarov released this 26 Aug 20:21

This is a bugfix and hardening release, mostly affecting how fNbt handles bad inputs and accidental misuse.

  • Every code path now rejects tags nested more than 512 levels deep, matching Minecraft's own limit, instead of crashing the process with an uncatchable stack overflow.
  • Fixed several ways a corrupt document could quietly load wrong: 32-bit overflow in list/array skip math, skipped lists of TAG_Long_Array consuming zero bytes, and huge declared lengths allocating before validation (#24). Malformed files now fail with helpful exceptions.
  • String length prefixes now parse as unsigned, matching Minecraft Java. Strings of 32,768 to 65,535 bytes load correctly, and trying to write anything longer throws instead of corrupting output.
  • NbtWriter.BeginList now accepts TAG_End as an empty list's element type, matching Minecraft Java and Bedrock (#12).
  • NbtWriter.WriteByteArray(Stream, ...) now throws on an undersized source instead of spinning in a read loop forever.
  • Fixed parent-tracking bugs that could cause problems when moving tags between containers: cloned NbtList children came out detached, indexer setters kept the displaced tag's Parent, Insert skipped some of Add's guards, and it was possible to accidentally create a reference cycle. Also, AddRange and the collection constructors now validate the whole batch before changing any tags' parents.
  • NbtReader's ReadListAsArray now validates up front. Reading corrupt data now toggles its error state instead of making it desync.
  • Fixed valid ZLib streams getting rejected with InvalidDataException if they did not start with exactly 0x78.
  • Improved a few exception messages and API docs.

API Reference

https://fcraft.net/fnbt/v1.1.1/

v1.1.0

Choose a tag to compare

@mstefarov mstefarov released this 24 Aug 01:05

Feature: Targeting .NET 8+

fNbt v1.1.0 adds a .NET 8 target alongside .NET Standard 2.0. If you can target .NET 8+, do! Just by upgrading from .NET Framework to a modern runtime you will see a major speed-up. For example, here are the relative speed-ups for a mid-sized CW map (higher is better):

v1.0 + net48 v1.0 + net8 v1.1 + net48 v1.1 + net8
Save, GZip 1.0x 6.1x 1.0x 6.1x
Save, ZLib 1.0x 1.9x 1.5x 4.6x
Load, GZip 1.0x 1.4x 1.0x 1.4x
Parse metadata
(9,300 tags)
1.0x 1.9x 1.0x 1.9x
Deep clone 1.0x 1.5x 1.1x 1.9x

Feature: NbtComparer

Use NbtComparer.Instance to compare two tags or entire trees by structure and value. It implements IEqualityComparer<NbtTag> so you can use it to put tags in a HashSet, use them as Dictionary keys, or run LINQ's Distinct and Except over them. Equality covers type, name, and value all the way down, with compounds treated as unordered and lists as ordered.

Note that NbtTag still doesn't override Equals, GetHashCode, or ==, so tags compare by reference unless you pass the comparer explicitly.

Other Changes

  • Performance improvements in ZLib compression (2.5x faster), SaveToBuffer (up to 5x less memory allocation), and NbtCompound/NbtList creation (up to 25% less memory allocation).
  • Fixed ReadRootTagName decompressing more of a file than it needs. Its bufferSize parameter turned out to be useless and is now ignored.
  • When targeting .NET 8+, ZLib-compressed files now have their checksums validated.
  • Fix missing Intellisense/XML documentation for the NuGet package.

API Reference

https://fcraft.net/fnbt/v1.1.0/

v1.0.0

Choose a tag to compare

@mstefarov mstefarov released this 03 Jul 08:52

Features

  • Library now targets .NET Standard 2.0 instead of .NET Framework, which allows fNbt to be used in more types of projects (e.g. .NET 8 or UWP).
  • Support TAG_Long_Array.

Other Changes

  • Fix some edge-cases related to reading corrupted NBT files.
  • Switch from JetBrains' annotations to .NET's built-in annotations.

API Reference

https://fcraft.net/fnbt/v1.0.0/

v0.6.4

Choose a tag to compare

@mstefarov mstefarov released this 06 Jul 07:37

This is a maintenance release, considered stable and production-ready.

Changes

  • Fixed a case where NbtBinaryReader.ReadString read too many bytes (#26).
  • Fixed NbtList.Contains(null) throwing exception instead of returning false.
  • Reduced NbtBinaryReader's maximum chunk size to 4 MB. This reduced peak
    memory use when reading huge files without affecting performance.

API Reference

See https://www.fcraft.net/fnbt/v0.6.3/ (no API changes since last release)

Download

v0.6.3

Choose a tag to compare

@mstefarov mstefarov released this 12 Apr 12:27

This is a maintenance release, considered stable and production-ready. Note when downloading source code: fNbt.Serialization project is a work-in-progress, and is not part of this release.

Changes

  • Empty _NbtList_s with TagType "End" are now allowed. See #12

API Reference

See https://www.fcraft.net/fnbt/v0.6.3/

Download

  • Compiled binary: fNbt_v0.6.3.zip [40 KiB]
  • Amalgamation (single merged source file): fNbt_v0.6.3_Annotated.cs [240 KiB]

    (using JetBrains.Annotations for ReSharper)
  • Amalgamation, without annotations: fNbt_v0.6.3.cs [235 KiB]
  • SHA1 sums for the files:
    66ab908708678272a58d9e71f1615f68caba79d7  fNbt_v0.6.3_Annotated.cs
    2a2cd74bee0bab765d9647e0cc048927248d0142  fNbt_v0.6.3.cs
    c743b4e8af649af75d7ab097dfec2bc897a70689  fNbt_v0.6.3.zip
  • Source files, archived: use GitHub's buttons below.

v0.6.2

Choose a tag to compare

@mstefarov mstefarov released this 17 Nov 14:22

This is a maintenance release, considered stable and production-ready. Note when downloading source code: fNbt.Serialization project is a work-in-progress, and is not part of this release.

Changes

  • NbtTags now implement ICloneable and provide copy constructors.
  • fNbt is now compatible with /checked compiler option.
  • Fixed an OverflowException in .NET 4.0+ when writing arrays of size 1 GiB (or larger) to a BufferedStream.
  • Fixed a few edge cases in NbtReader when reading corrupt files.
  • Minor optimizations and documentation fixes.

API Reference

See http://www.fcraft.net/fnbt/v0.6.2/

Download

  • Compiled binary: fNbt_v0.6.2.zip [39 KiB]
  • Amalgamation (single merged source file): fNbt_v0.6.2_Annotated.cs [235 KiB]

    (using JetBrains.Annotations for ReSharper)
  • Amalgamation, without annotations: fNbt_v0.6.2.cs [232 KiB]
  • SHA1 sums for the files:
    77f291e0738e0bae6718a71cc2e8f8ca2b2e0f54  fNbt_v0.6.2_Annotated.cs
    2aa56a68f0b8343dfebd54b2bfe1f1b6319a3e98  fNbt_v0.6.2.cs
    82b1cfcf114a3d5411f105e68e328fd5d75e34dd  fNbt_v0.6.2.zip
  • Source files, archived: use GitHub's buttons below.

v0.6.1

Choose a tag to compare

@mstefarov mstefarov released this 19 Jul 23:25

This is a maintenance release, considered stable and production-ready. Note when downloading source code: fNbt.Serialization project is a work-in-progress, and is not part of this release.

Changes

  • NbtReader now supports non-seekable streams.
  • Fixed issues loading from/saving to non-seekable steams in NbtFile.
  • NbtFile.LoadFromStream/SaveToStream now accurately report bytes read/written for NBT data over 2 GiB in size.
  • API change:
    • All NbtFile loading/saving methods now return long instead of int.

API Reference

See http://www.fcraft.net/fnbt/v0.6.1/

Download

  • Compiled binary: fNbt_v0.6.1.zip [38 KiB]
  • Amalgamation (single merged source file): fNbt_v0.6.1_Annotated.cs [226 KiB]

    (using JetBrains.Annotations for ReSharper)
  • Amalgamation, without annotations: fNbt_v0.6.1.cs [223 KiB]
  • SHA1 sums for the files:
    207e628aa2b446a11a22d14b9d191e8c38e28794  fNbt_v0.6.1_Annotated.cs
    95f6a7743fa65f7adf86ff53a2a6b6536adebe33  fNbt_v0.6.1.cs
    5d0fa33590c8cef55e826885b7eb45710e41a506  fNbt_v0.6.1.zip
  • Source files, archived: use GitHub's buttons below.