From 59b38baa3d3aa9c603e891c2d28c34604a0d1e0a Mon Sep 17 00:00:00 2001 From: ForeverZer0 Date: Wed, 25 Aug 2021 05:05:13 -0400 Subject: [PATCH] Implemented ICloneable interface for tags --- SharpNBT/Tags/Tag.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/SharpNBT/Tags/Tag.cs b/SharpNBT/Tags/Tag.cs index eef2443..0a61ca5 100644 --- a/SharpNBT/Tags/Tag.cs +++ b/SharpNBT/Tags/Tag.cs @@ -14,7 +14,7 @@ namespace SharpNBT /// Abstract base class that all NBT tags inherit from. /// [PublicAPI][Serializable] - public abstract class Tag : IEquatable, ISerializable + public abstract class Tag : IEquatable, ISerializable, ICloneable { private static IEnumerable GetKnownTypes() { @@ -153,7 +153,25 @@ namespace SharpNBT // ReSharper restore NonReadonlyMemberInGetHashCode } } - + + /// Creates a new object that is a copy of the current instance. + /// A new object that is a copy of this instance. + public object Clone() + { + // Serialize then deserialize to make a deep-copy + using var stream = new MemoryStream(); + + // Might as well not worry about swapping bits, just use native endian + var opts = BitConverter.IsLittleEndian ? FormatOptions.LittleEndian : FormatOptions.BigEndian; + using var writer = new TagWriter(stream, opts, true); + using var reader = new TagReader(stream, opts, true); + + writer.WriteTag(this); + stream.Seek(0, SeekOrigin.Begin); + + return reader.ReadTag(!(Parent is ListTag)); + } + /// /// Required constructor for ISerializable implementation. ///