NHSE/NHSE.Core/Structures/Villager/IVillagerOrigin.cs
Kurt db54e5ae1c Fix identity swap when using span slices
Closes #684

Defensively allocate a copy so that the replacement does not overwrite the original sequence A=>B then continue doing B=>B swaps.
Wasn't a problem before since properties fetched byte[] (allocated separate slice); changing to span introduced this regression -- now fixed.
2026-01-17 16:14:09 -06:00

53 lines
1.7 KiB
C#

using System;
namespace NHSE.Core;
public interface IVillagerOrigin
{
string PlayerName { get; }
string TownName { get; }
Span<byte> GetTownIdentity();
Span<byte> GetPlayerIdentity();
}
public static class VillagerOriginExtensions
{
public static bool IsOriginatedFrom(this IVillagerOrigin visit, IVillagerOrigin host)
{
return visit.IsSameTown(host) && visit.IsSamePlayer(host);
}
public static bool IsSameTown(this IVillagerOrigin visit, IVillagerOrigin host)
{
var hostTown = host.GetTownIdentity();
var visitTown = visit.GetTownIdentity();
return hostTown.SequenceEqual(visitTown);
}
public static bool IsSamePlayer(this IVillagerOrigin visit, IVillagerOrigin host)
{
var hostPlayer = host.GetPlayerIdentity();
var visitPlayer = visit.GetPlayerIdentity();
return hostPlayer.SequenceEqual(visitPlayer);
}
public static void ChangeOrigins(this IVillagerOrigin visit, IVillagerOrigin host, Span<byte> visitData)
{
visit.ChangeToHostTown(host, visitData);
visit.ChangeToHostPlayer(host, visitData);
}
private static void ChangeToHostTown(this IVillagerOrigin visit, IVillagerOrigin host, Span<byte> visitData)
{
var hostTown = host.GetTownIdentity();
var visitTown = visit.GetTownIdentity().ToArray();
visitData.ReplaceOccurrences(visitTown, hostTown);
}
private static void ChangeToHostPlayer(this IVillagerOrigin visit, IVillagerOrigin host, Span<byte> visitData)
{
var hostPlayer = host.GetPlayerIdentity();
var visitPlayer = visit.GetPlayerIdentity().ToArray();
visitData.ReplaceOccurrences(visitPlayer, hostPlayer);
}
}