Skip to content

Using specific overload of MessagePackSerializer.Serialize<T> within custom formatter produces invalid message-pack bytes #2244

@pupsette

Description

@pupsette

Bug description

When implementing the Serialize method of a custom formatter, using the overload MessagePackSerializer.Serialize<T>(T object) (without an existing MessagePackWriter) produces invalid message-pack bytes. Trying to deserialize these will fail.

Repro steps

using MessagePack;
using MessagePack.Formatters;
using NUnit.Framework;

namespace CID.CSIS.Application.Tests;

[MessagePackObject]
public class TestClass
{
    [Key(0)]
    [MessagePackFormatter(typeof(TestPropertyFormatter))]
    public int Property { get; set; }
}

public class TestPropertyFormatter : IMessagePackFormatter<int>
{
    public void Serialize(ref MessagePackWriter writer, int value, MessagePackSerializerOptions options)
    {
        //works: MessagePackSerializer.Serialize(ref writer, value, options);
        writer.WriteRaw(MessagePackSerializer.Serialize(value, options));
    }

    public int Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
    {
        return MessagePackSerializer.Deserialize<int>(ref reader, options);
    }
}

[TestFixture]
public class MessagePackRecursiveSerializationTests
{
    [Test]
    public void NestedSerializer()
    {
        var obj = new TestClass { Property = 15 };
        byte[] serialized = MessagePackSerializer.Serialize(obj);
        MessagePackSerializer.Deserialize<TestClass>(serialized);
    }
}

Expected behavior

Serialized message-pack bytes should be [145, 15].

Actual behavior

Deserialization fails with Unexpected msgpack code 15 (positive fixint) encountered.
Serialized message-pack bytes are [15, 15]

  • Version used: 3.1.4
  • Runtime: .NET 8

Additional context

I think it's related to buffer management when serializing. I tested slightly modified versions of the example to make sure that WriteRaw is not the problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions