//
// NostaleStringA.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using Reloaded.Memory.Sources;
namespace NosSmooth.LocalBinding.Objects;
///
/// Represents nostale string object.
///
public class NostaleStringA : IDisposable
{
private readonly IMemory _memory;
private nuint _pointer;
///
/// Create an instance of .
///
/// The memory to allocate the string on.
/// The string contents.
/// A nostale string.
public static NostaleStringA Create(IMemory memory, string data)
{
var bytes = Encoding.ASCII.GetBytes(data);
var allocated = memory.Allocate(bytes.Length + 1 + 8);
memory.SafeWrite(allocated, 1);
memory.SafeWrite(allocated + 4, data.Length);
memory.SafeWriteRaw(allocated + 8, bytes);
memory.SafeWrite(allocated + 8 + (nuint)data.Length, 0);
return new NostaleStringA(memory, allocated);
}
private NostaleStringA(IMemory memory, nuint pointer)
{
_memory = memory;
_pointer = pointer;
}
///
/// Finalizes an instance of the class.
///
~NostaleStringA()
{
Free();
}
///
/// Gets whether the string is still allocated.
///
public bool Allocated => _pointer != nuint.Zero;
///
/// Get the pointer to the string.
///
/// A pointer to the string to pass to NosTale.
public nuint Get()
{
return _pointer + 0x08;
}
///
/// Free the memory allocated by the string.
///
public void Free()
{
if (Allocated)
{
_memory.Free(_pointer);
_pointer = nuint.Zero;
}
}
///
public void Dispose()
{
Free();
}
}