~ruther/NosSmooth.Local

ref: ce0260d5b61a99ecbbd13177283632c4a7a2e28c NosSmooth.Local/src/Core/NosSmooth.LocalBinding/Objects/NostaleStringA.cs -rw-r--r-- 2.1 KiB
ce0260d5 — František Boháček feat: update to managed and raw client 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
//  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;

/// <summary>
/// Represents nostale string object.
/// </summary>
public class NostaleStringA : IDisposable
{
    private readonly IMemory _memory;
    private nuint _pointer;

    /// <summary>
    /// Create an instance of <see cref="NostaleStringA"/>.
    /// </summary>
    /// <param name="memory">The memory to allocate the string on.</param>
    /// <param name="data">The string contents.</param>
    /// <returns>A nostale string.</returns>
    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;
    }

    /// <summary>
    /// Finalizes an instance of the <see cref="NostaleStringA"/> class.
    /// </summary>
    ~NostaleStringA()
    {
        Free();
    }

    /// <summary>
    /// Gets whether the string is still allocated.
    /// </summary>
    public bool Allocated => _pointer != nuint.Zero;

    /// <summary>
    /// Get the pointer to the string.
    /// </summary>
    /// <returns>A pointer to the string to pass to NosTale.</returns>
    public nuint Get()
    {
        return _pointer + 0x08;
    }

    /// <summary>
    /// Free the memory allocated by the string.
    /// </summary>
    public void Free()
    {
        if (Allocated)
        {
            _memory.Free(_pointer);
            _pointer = nuint.Zero;
        }
    }

    /// <inheritdoc />
    public void Dispose()
    {
        Free();
    }
}
Do not follow this link