### Example: using ToString() Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Creates a namespace, adds a LocresString, and prints the ToString() output, which starts with "Game:[...]". ```cs using LocresLib; var ns = new LocresNamespace(); ns.Name = "Game"; ns.Add(new LocresString("Retry", "Retry", 0xdeadbeef)); Console.WriteLine(ns.ToString()); // starts with "Game:[...]" ``` -------------------------------- ### Example usage of CityHash64_utf16_to_uint32 Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Example showing how to call the static method to get the version 3 pre-hash value for a string. The output is written to the console. ```csharp using LocresLib; uint h = LocresFile.CityHash64_utf16_to_uint32("Menu.Namespace"); Console.WriteLine(h); // version 3 pre-hash value ``` -------------------------------- ### Example: pre-sizing a namespace Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Shows how to create a namespace with a capacity of 2048 and set its Name property. ```cs using LocresLib; // pre-size a namespace expected to hold many keys var ns = new LocresNamespace(2048); ns.Name = "GUI"; ``` -------------------------------- ### UInt128 usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/UInt128.md Example of creating a UInt128 instance and accessing its properties and Equals method. ```csharp using LocresLib; var pair = new UInt128(1234u, 5678u); Console.WriteLine(pair.Low); // 1234 Console.WriteLine(pair.High); // 5678 Console.WriteLine(pair.Equals(new UInt128(1234u, 5678u))); // true ``` -------------------------------- ### Example: Load locres file and check version Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresVersion.md Shows how to load a locres file and check its version. The example reads a file named 'optimized_cityhash.locres', prints the version as an integer (expected 3), and demonstrates a version check against LocresVersion.Optimized. ```csharp using LocresLib; using System.IO; var locres = new LocresFile(); using (var file = File.OpenRead("optimized_cityhash.locres")) { locres.Load(file); } Console.WriteLine((int)locres.Version); // 3 if (locres.Version >= LocresVersion.Optimized) { // file has pre-hashes and refCounts } ``` -------------------------------- ### Exported template shape example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/PoConverter.md Example .pot file content showing the template output with empty msgstr, indicating no translation is set. ```pot msgctxt "Menu/Play" msgid "Play" msgstr "" ``` -------------------------------- ### Basic call example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/Crc.md Shows a basic call to Crc.StrCrc32 with the string "GUI" and prints the resulting hash to the console. ```cs using LocresLib; uint hash = Crc.StrCrc32("GUI"); Console.WriteLine(hash); ``` -------------------------------- ### Example: load a locres file Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Shows how to open a locres file and load it into a LocresFile instance, then print the version and total string count. ```cs using LocresLib; using System.IO; var locres = new LocresFile(); using (var file = File.OpenRead("en.locres")) { locres.Load(file); } Console.WriteLine($"Version: {locres.Version}, total strings: {locres.TotalCount}"); ``` -------------------------------- ### CLI pipeline usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CsvConverter.md Example of using CsvConverter through the CLI pipeline, including loading a locres file and exporting/importing CSV. ```cs using LocresLib; using UnrealLocres.Converter; var converter = new CsvConverter(); var locres = new LocresFile(); using (var file = File.OpenRead("en.locres")) { locres.Load(file); } converter.Export(locres, "en.csv"); // prints "Exported N strings to en.csv" converter.Import(locres, "translations.csv"); // applies Target column, prints stats ``` -------------------------------- ### Basic construction of LocresString Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Basic construction example. Creates a LocresString with a key, value, and a sample hash, then prints the key and value. ```cs using LocresLib; var entry = new LocresString("Play", "Play", 0x3A5CB0C1); Console.WriteLine($"{entry.Key} = {entry.Value}"); ``` -------------------------------- ### WriteUnrealString usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/IO.md Shows how to use WriteUnrealString with a MemoryStream and BinaryWriter. The example writes a Unicode string, an ASCII string, and a forced Unicode string, with comments indicating the expected prefix values. ```csharp using LocresLib.IO; using System.IO; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.WriteUnrealString("유니코드"); // UTF-16 path, prefix -5 bw.WriteUnrealString("AsCiI"); // ASCII path, prefix 6 bw.WriteUnrealString("ASCII forced", true); // forceUnicode: prefix -11 } ``` -------------------------------- ### PO singular entry mapping example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/PoConverter.md Example .po file content showing a singular entry with msgctxt, msgid, and msgstr. This maps to TranslationEntry(Key = "Menu/Play", Source = "Play", Target = "Jugar"). ```po msgctxt "Menu/Play" msgid "Play" msgstr "Jugar" ``` -------------------------------- ### Parse failure handling example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/PoConverter.md Example C# code that creates a PoConverter, loads a locres file, and attempts to import a broken.po file. Catches IOException and prints the error message. ```csharp using UnrealLocres.Converter; var converter = new PoConverter(); var locres = new LocresFile(); using (var file = File.OpenRead("en.locres")) { locres.Load(file); } try { converter.Import(locres, "broken.po"); } catch (IOException e) { // "Failed to parse PO file : ..." with parser diagnostics Console.WriteLine($"PO import failed: {e.Message}"); } ``` -------------------------------- ### CityHash32 usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Demonstrates calling all three overloads with the same input and printing the results. The output should show equal values for all three calls. ```csharp using LocresLib; uint h1 = CityHash.CityHash32("test"); uint h2 = CityHash.CityHash32("test", Encoding.ASCII); byte[] raw = Encoding.ASCII.GetBytes("test"); uint h3 = CityHash.CityHash32(raw); Console.WriteLine($"{h1} == {h2} == {h3}"); ``` -------------------------------- ### CityHash64WithSeeds usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Example of calling CityHash64WithSeeds with a string and two seeds. Requires the LocresLib namespace. ```csharp using LocresLib; ulong h = CityHash.CityHash64WithSeeds("data", 1, 2); ``` -------------------------------- ### CSV row layout example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CsvConverter.md Example CSV content showing the header row and two data rows with empty target columns. ```csv key,source,target Menu/Play,Play, Menu/Options,Options, ``` -------------------------------- ### Example: save (conversion between formats) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Loads a legacy .locres file and saves it as Optimized format. Requires a seekable, writable output stream; the input file must be readable. After Save, the output stream position is at the end of the written data. ```csharp using LocresLib; var locres = new LocresFile(); using (var file = File.OpenRead("legacy.locres")) { locres.Load(file); // Version == LocresVersion.Legacy } using (var file = File.Create("converted.locres")) { locres.Save(file, LocresVersion.Optimized); } ``` -------------------------------- ### ReadUnrealString usage example (test consumption) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/IO.md Example showing how to read two Unreal strings from a byte array using a BinaryReader. The first string is UTF-16 (length -5) and the second is ASCII (length 6). ```csharp using LocresLib.IO; using System.IO; var bytes = new byte[] { 0xFB, 0xFF, 0xFF, 0xFF, 0x20, 0xC7, 0xC8, 0xB2, 0x54, 0xCF, 0xDC, 0xB4, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x41, 0x73, 0x43, 0x69, 0x49 }; using (var ms = new MemoryStream(bytes)) using (var br = new BinaryReader(ms)) { Console.WriteLine(br.ReadUnrealString()); // "유니코드" (UTF-16, length -5) Console.WriteLine(br.ReadUnrealString()); // "AsCiI" (ASCII, length 6) } ``` -------------------------------- ### LocresLib sample usage Source: https://github.com/akintos/unreallocres/blob/master/README.md C# example showing how to use the LocresLib library to load, iterate, and save a locres file. It opens a file, loads it into a LocresFile, iterates over namespaces and string entries, and saves with the Optimized version. ```cs using LocresLib; var locres = new LocresFile(); using (var file = File.OpenRead(input)) { locres.Load(file); } foreach (var locresNamespace in locres) { foreach (var stringEntry in locresNamespace) { string key = stringEntry.Key; string val = stringEntry.Value; // work with stringEntry } } using (var file = File.Create(output)) { locres.Save(file, LocresVersion.Optimized); } ``` -------------------------------- ### CityHash64 usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Computes a 64-bit CityHash of the string "Hello" using Unicode encoding and prints the result. Requires the LocresLib namespace. ```csharp using LocresLib; ulong h = CityHash.CityHash64("Hello", Encoding.Unicode); Console.WriteLine(h); ``` -------------------------------- ### Property Name Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Gets or sets the namespace key string. Read/write. LocresFile.Load sets it from the file; LocresFile.Save writes the current value. ```APIDOC ## Property Name ### Description Gets or sets the namespace key string. Read/write. `LocresFile.Load` sets it from the file; `LocresFile.Save` writes the current value, so renaming it before save changes the on-disk namespace key. ### Signature ```cs public string Name { get; set; } ``` ### Type - **Name** (string) - The namespace key. ### Remarks This property is used by `LocresFile` to serialize the namespace. ``` -------------------------------- ### Property: Key Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Gets or sets the string key of the localization entry. Read/write; changing it before Save changes the on-disk key. ```APIDOC ## Property: Key ### Description Gets or sets the string key of the localization entry. This property is read/write. Changing it before calling Save will change the on-disk key. ### Type string ### Access Read/Write ### Example ```cs var entry = new LocresString("Play", "Play", 0x3A5CB0C1); entry.Key = "Start"; // changes the key ``` ``` -------------------------------- ### Implementing a custom converter (JsonConverter) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/BaseConverter.md Example of a sealed converter class deriving from BaseConverter, overriding ExportExtension, ImportExtension, Write, and Read. The Write method outputs JSON with key-source pairs; Read returns an empty list placeholder. ```csharp using LocresLib; using UnrealLocres.Converter; using System.IO; public sealed class JsonConverter : BaseConverter { public override string ExportExtension => "json"; public override string ImportExtension => "json"; protected override void Write(List data, TextWriter writer) { writer.Write("{\n"); foreach (var entry in data) writer.Write($" \"{entry.Key}\": \"{entry.Source}\",\n"); writer.Write("}\n"); } protected override List Read(TextReader reader) { // parse and return TranslationEntry list return new List(); } } ``` -------------------------------- ### Example: error handling for Load Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Demonstrates catching ArgumentException when loading a non-readable or non-seekable stream. The catch block prints the error message, which will be either "Stream must be readable." or "Stream must be seekable.". ```cs using LocresLib; var locres = new LocresFile(); try { var file = File.OpenRead("missing.locres"); // non-readable path locres.Load(file); } catch (ArgumentException e) { // "Stream must be readable." / "Stream must be seekable." Console.WriteLine($"Failed to load: {e.Message}"); } ``` -------------------------------- ### Seeded hash (chained calculation) example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/Crc.md Demonstrates using the seed parameter to continue a rolling CRC across chunks. The first call seeds with 0, and the second call uses the previous result as the seed. ```cs using LocresLib; // Continue a rolling CRC across chunks with the seed parameter uint rolling = Crc.StrCrc32("first", 0); rolling = Crc.StrCrc32("second", rolling); Console.WriteLine(rolling); ``` -------------------------------- ### Error handling for null values in LocresString Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Error handling example for null key or value. The constructor throws ArgumentNullException, which is caught and reported. ```cs using LocresLib; string key = GetKey(); // could be null string value = GetValue(); // could be null try { var entry = new LocresString(key, value, 0); } catch (ArgumentNullException e) { Console.WriteLine($"Missing key or value: {e.Message}"); return; } ``` -------------------------------- ### Property Name Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Gets or sets the namespace key. LocresFile.Load sets it from the file; LocresFile.Save writes the current value, so renaming before save changes the on-disk key. ```cs public string Name { get; set; } ``` -------------------------------- ### Property: Value Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Gets or sets the localized string value. Read/write; the import pipeline assigns translations by writing to this property. ```APIDOC ## Property: Value ### Description Gets or sets the localized string value. This property is read/write. The import pipeline (BaseConverter.Import) assigns translations by writing str.Value = tr.Target. ### Type string ### Access Read/Write ### Example ```cs var entry = new LocresString("Play", "Play", 0x3A5CB0C1); entry.Value = "Jouer"; // sets the localized value ``` ``` -------------------------------- ### Properties Low / High Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/UInt128.md Gets or sets the low and high 64-bit halves of the UInt128 value. ```APIDOC ## Properties Low / High ### Description Gets or sets the low and high 64-bit halves of the UInt128 value. ### Properties - **Low** (UInt64) - Read/write - Lower 64 bits. - **High** (UInt64) - Read/write - Upper 64 bits. ### Example ```cs var pair = new UInt128(1234u, 5678u); Console.WriteLine(pair.Low); // 1234 Console.WriteLine(pair.High); // 5678 ``` ``` -------------------------------- ### CityHash64WithSeed usage example Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Computes a seeded 64-bit CityHash of the string "payload" using a seed value of 0x9ae16a3b2f90404f. Requires the LocresLib namespace. ```csharp using LocresLib; ulong h = CityHash.CityHash64WithSeed("payload", 0x9ae16a3b2f90404f); ``` -------------------------------- ### Example: round-trip preserving the loaded version Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Loads a .locres file, saves it to a MemoryStream using the same version as the loaded file, then reloads the copy and prints the total entry count. The output stream position is at the end after Save; the round-trip preserves the original format. ```csharp using LocresLib; var locres = new LocresFile(); using (var file = File.OpenRead("input.locres")) { locres.Load(file); } using (var ms = new MemoryStream()) { locres.Save(ms, locres.Version); // same format as input using (var ms2 = new MemoryStream(ms.ToArray())) { var copy = new LocresFile(); copy.Load(ms2); Console.WriteLine(copy.TotalCount); } } ``` -------------------------------- ### Main method implementation Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/cli.md Entry point that registers PoConverter and CsvConverter, prints a version banner, parses arguments with CommandLineParser, and returns an exit code. Parse failures map to exit code 1. ```csharp static int Main(string[] args) { RegisterConverter(new PoConverter()); RegisterConverter(new CsvConverter()); var version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; Console.WriteLine($"UnrealLocres v{version}"); Console.WriteLine("https://github.com/akintos/UnrealLocres"); Console.WriteLine(""); var result = Parser.Default.ParseArguments(args) .MapResult( (ExportOptions opt) => ExportAndExit(opt), (ImportOptions opt) => ImportAndExit(opt), (MergeOptions opt) => MergeAndExit(opt), errs => 1); return result; } ``` -------------------------------- ### PoConverter class declaration with Read and Write methods Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/PoConverter.md Full class implementation showing the overridden ExportExtension, ImportExtension, Read, and Write methods. Read parses a .po file using POParser, converts each POSingularEntry to a TranslationEntry, and throws IOException on parse failure. Write creates a POCatalog with UTF-8 encoding, adds POSingularEntry objects with POKey from TranslationEntry data, and generates the output using POGenerator. ```csharp public sealed class PoConverter : BaseConverter { public override string ExportExtension => "pot"; public override string ImportExtension => "po"; protected override List Read(TextReader reader) { var list = new List(); var parser = new POParser(); POParseResult result = parser.Parse(reader); if (!result.Success) throw new IOException("Failed to parse PO file : " + result.Diagnostics.ToString()); var catalog = result.Catalog; foreach (var item in catalog) { var poentry = item as POSingularEntry; var trentry = new TranslationEntry(poentry.Key.ContextId, poentry.Key.Id, poentry.Translation); list.Add(trentry); } return list; } protected override void Write(List data, TextWriter writer) { var catalog = new POCatalog(); catalog.Encoding = "UTF-8"; foreach (var item in data) { var pokey = new POKey(item.Source, contextId: item.Key); catalog.Add(new POSingularEntry(pokey)); } var gen = new POGenerator(); gen.Generate(writer, catalog); } } ``` -------------------------------- ### UInt128(UInt64 low, UInt64 high) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/UInt128.md Constructor that initializes a new UInt128 instance with the specified low and high 64-bit halves. ```APIDOC ## Constructor UInt128(UInt64 low, UInt64 high) ### Description Initializes a new instance of the UInt128 class with the given low and high 64-bit halves. ### Method Constructor ### Parameters - **low** (UInt64) - Required - Low 64-bit half. - **high** (UInt64) - Required - High 64-bit half. ### Example ```cs var pair = new UInt128(1234u, 5678u); ``` ``` -------------------------------- ### Property: SourceStringHash Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Gets the read-only source string hash. Set once in the constructor and never mutated. Written back verbatim by LocresFile.Save. ```APIDOC ## Property: SourceStringHash ### Description Gets the read-only source string hash. This property is set once in the constructor and never mutated. LocresFile.Save writes it back verbatim; MergeAndExit copies it when merging entries from another file. ### Type uint ### Access Read-only ### Example ```cs var entry = new LocresString("Play", "Play", 0x3A5CB0C1); Console.WriteLine(entry.SourceStringHash); // outputs 0x3A5CB0C1 ``` ``` -------------------------------- ### Constructor LocresNamespace(int capacity) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Creates a namespace with an initial capacity passed to the List base constructor. ```cs public LocresNamespace(int capacity) : base(capacity) { } ``` -------------------------------- ### Enum declaration for LocresVersion Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresVersion.md Defines the LocresVersion enum with members Legacy, Compact, Optimized, and Optimized_CityHash64_UTF16. The enum is byte-backed with sequential values starting at 0. ```csharp /// /// Data versions for LocRes files. /// /// https://github.com/EpicGames/UnrealEngine/blob/master/Engine/Source/Runtime/Core/Public/Internationalization/TextLocalizationResourceVersion.h /// /// public enum LocresVersion : byte { /// /// Legacy format file - will be missing the magic number. /// Legacy = 0, /// /// Compact format file - strings are stored in a LUT to avoid duplication. /// Compact, /// /// Optimized format file - namespaces/keys are pre-hashed (CRC32), we know the number of elements up-front, and the number of references for each string in the LUT (to allow stealing). /// Optimized, /// /// Optimized format file - namespaces/keys are pre-hashed (CityHash64, UTF-16), we know the number of elements up-front, and the number of references for each string in the LUT (to allow stealing). /// Optimized_CityHash64_UTF16, } ``` -------------------------------- ### Constructor LocresNamespace() Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Creates an empty namespace with the default List capacity. ```cs public LocresNamespace() { } ``` -------------------------------- ### Constructor LocresNamespace() Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Creates an empty namespace with the default List capacity. ```APIDOC ## Constructor LocresNamespace() ### Description Creates an empty namespace with the default `List` capacity. ### Method Constructor ### Signature ```cs public LocresNamespace() { } ``` ### Parameters None. ### Returns A new `LocresNamespace` instance. ### Example ```cs var ns = new LocresNamespace(); ``` ``` -------------------------------- ### ImportOptions class for 'import' verb Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/types.md Defines the command-line options for the 'import' verb. Requires two positional arguments: the input locres file and the translation file. The translation format defaults to "csv" and can be set via -f/--format; the output path is optional and defaults to the input locres path with ".new" appended. ```csharp [Verb("import", HelpText = "Import translation data to locres file.")] class ImportOptions { [Value(0, HelpText = "Input locres file path", MetaName = "LocresInputPath", Required = true)] public string LocresInputPath { get; set; } [Value(1, HelpText = "Input translation file path", MetaName = "TranslationInputPath", Required = true)] public string TranslationInputPath { get; set; } [Option('f', "format", Default = "csv", HelpText = "Translation file input format [pot, csv]")] public string TranslationInputFormat { get; set; } [Option('o', HelpText = "Translated locres file output path, default is [INPUT PATH].new")] public string LocresOutputPath { get; set; } } ``` -------------------------------- ### Property BigEndian Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Gets or sets a boolean flag that controls byte-order swapping for raw 32-bit and 64-bit reads. When true, values are byte-swapped after BitConverter conversion. Must be consistent between writer and reader for deterministic hashing. ```APIDOC ## Property `BigEndian` ### Description Byte-order switch for the raw `Fetch32`/`Fetch64` reads. When `true`, `uint32`/`uint64` values are byte-swapped after `BitConverter.ToUInt32`/`ToUInt64`. Deterministic hashing requires the same setting on writer and reader. ### Property Signature ```cs public static bool BigEndian { get; set; } = false; ``` ### Property Type - **Type**: `bool` - **Default**: `false` ### Remarks - Set to `true` to enable big-endian byte swapping. - Must be consistent between writer and reader for deterministic hashing. ``` -------------------------------- ### Method ToString() Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Returns the namespace Name, a colon, and the List.ToString() rendering of the contained LocresString entries. ```cs public override string ToString() { return Name + ":" + base.ToString(); } ``` -------------------------------- ### Method ToString() Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Returns a string that represents the namespace name followed by a colon and the base List rendering of contained entries. ```APIDOC ## Method ToString() ### Description Returns a string that represents the namespace name followed by a colon and the base `List` rendering of contained entries. ### Signature ```cs public override string ToString() { return Name + ":" + base.ToString(); } ``` ### Parameters None. ### Returns - **string** - The namespace `Name`, a colon, then the `List.ToString()` rendering of the contained `LocresString` entries. ### Example ```cs using LocresLib; var ns = new LocresNamespace(); ns.Name = "Game"; ns.Add(new LocresString("Retry", "Retry", 0xdeadbeef)); Console.WriteLine(ns.ToString()); // starts with "Game:[...]" ``` ``` -------------------------------- ### ExportOptions class for 'export' verb Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/types.md Defines the command-line options for the 'export' verb. Requires an input locres file path as positional argument 0; the output format defaults to "csv" and can be set via -f/--format to "pot" or "csv". The output path is optional and defaults to the input file name with the selected extension. ```csharp [Verb("export", HelpText = "Export po file into other format.")] class ExportOptions { [Value(0, HelpText = "Input locres file path", MetaName = "InputPath", Required = true)] public string InputPath { get; set; } [Option('f', "format", Default = "csv", HelpText = "Output format [pot, csv]")] public string OutputFormat { get; set; } [Option('o', HelpText = "Output path including extension")] public string OutputPath { get; set; } } ``` -------------------------------- ### Constructor LocresNamespace(int capacity) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresNamespace.md Creates a namespace with a specified initial capacity for the underlying list. ```APIDOC ## Constructor LocresNamespace(int capacity) ### Description Creates a namespace with a specified initial capacity for the underlying list. ### Method Constructor ### Signature ```cs public LocresNamespace(int capacity) : base(capacity) { } ``` ### Parameters - **capacity** (int) - Required - Initial capacity passed to the `List` base constructor. ### Returns A new `LocresNamespace` instance with the given capacity. ### Example ```cs using LocresLib; // pre-size a namespace expected to hold many keys var ns = new LocresNamespace(2048); ns.Name = "GUI"; ``` ``` -------------------------------- ### ReadUnrealString implementation (BinaryReaderExtensions) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/IO.md Internal extension method that reads an int32 length prefix and decodes the payload as ASCII (positive length), UTF-16-LE (negative length), or returns an empty string for zero length. Trailing NUL characters are trimmed from the result. ```csharp internal static class BinaryReaderExtensions { internal static string ReadUnrealString(this BinaryReader reader) { int length = reader.ReadInt32(); string result; if (length > 0) { result = Encoding.ASCII.GetString(reader.ReadBytes(length)); } else if (length < 0) { result = Encoding.Unicode.GetString(reader.ReadBytes(length * -2)); } else // length == 0 { return string.Empty; } return result.TrimEnd('\0'); } } ``` -------------------------------- ### Import method signature Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/BaseConverter.md Public method that reads a translation file and applies translations to the provided LocresFile. It mutates the LocresString.Value of matched entries and prints progress and warnings. ```csharp public void Import(LocresFile locres, string inputPath) ``` -------------------------------- ### Abstract properties ExportExtension and ImportExtension Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/BaseConverter.md Declares the abstract properties that subclasses must implement. ExportExtension returns the file extension the converter writes (e.g., "csv" or "pot") and is also the registration key in the exporter registry. ImportExtension returns the file extension the converter reads (e.g., "csv" or "po") and is the key in the importer registry. ```csharp public abstract string ExportExtension { get; } public abstract string ImportExtension { get; } ``` -------------------------------- ### LocresString constructor Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Creates a new LocresString instance with the specified key, value, and source string hash. Throws ArgumentNullException if key or value is null. ```APIDOC ## Constructor: LocresString(string key, string value, uint sourceStringHash) ### Description Creates a new LocresString instance with the specified key, value, and source string hash. The key and value must not be null; otherwise, an ArgumentNullException is thrown. The sourceStringHash is stored verbatim and written back unchanged by LocresFile.Save. ### Parameters - **key** (string) - Required - The string key (e.g., message id). Must not be null. - **value** (string) - Required - The localized string value. Must not be null. - **sourceStringHash** (uint) - Required - Checksum of the source string, typically the Crc.StrCrc32 hash. Stored verbatim. ### Throws - **ArgumentNullException** - If key is null (thrown with nameof(key)). - **ArgumentNullException** - If value is null (thrown with nameof(value)). ### Example ```cs using LocresLib; var entry = new LocresString("Play", "Play", 0x3A5CB0C1); Console.WriteLine($"{entry.Key} = {entry.Value}"); ``` ### Example: Error handling ```cs using LocresLib; string key = GetKey(); // could be null string value = GetValue(); // could be null try { var entry = new LocresString(key, value, 0); } catch (ArgumentNullException e) { Console.WriteLine($"Missing key or value: {e.Message}"); return; } ``` ``` -------------------------------- ### Load(Stream) method implementation Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md The Load method validates the stream is seekable and readable, throwing ArgumentException otherwise. It clears existing data before parsing, and on success sets Version and populates the list. ```cs public void Load(Stream stream) { if (!stream.CanSeek) throw new ArgumentException("Stream must be seekable."); if (!stream.CanRead) throw new ArgumentException("Stream must be readable."); Clear(); ... } ``` -------------------------------- ### CityHash64WithSeed overload signatures Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Shows the three overloads of the CityHash64WithSeed method family. Overload 1 delegates to overload 2 with Encoding.Default; overload 2 encodes the string and delegates to overload 3; overload 3 folds the seed into the hash via CityHash64WithSeeds(s, K2, seed). ```csharp public static uint64 CityHash64WithSeed(string s, uint64 seed) public static uint64 CityHash64WithSeed(string s, uint64 seed, Encoding encoding) public static uint64 CityHash64WithSeed(byte[] s, uint64 seed) ``` -------------------------------- ### Export a locres to CSV Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/cli.md Shows the basic export command and an export with the -f pot and -o en.pot options to write a POT file. ```text UnrealLocres export en.locres UnrealLocres export en.locres -f pot -o en.pot ``` -------------------------------- ### Key property declaration Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Property declaration for Key. Read/write; changing it before Save changes the on-disk key. ```cs public string Key { get; set; } ``` -------------------------------- ### MergeOptions class for 'merge' verb Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/types.md Defines the command-line options for the 'merge' verb. Requires two positional arguments: the target locres file (to be translated) and the source locres file (with additional lines). The output path is optional and defaults to the target path with ".new" appended. ```csharp [Verb("merge", HelpText = "Merge two locres files into one.")] class MergeOptions { [Value(0, HelpText = "Merge target locres file path, the file you want to translate", MetaName = "TargetLocresPath", Required = true)] public string TargetLocresPath { get; set; } [Value(1, HelpText = "Merge source locres file path, the file that has additional lines", MetaName = "SourceLocresPath", Required = true)] public string SourceLocresPath { get; set; } [Option('o', HelpText = "Merged locres file output path, default is [TargetLocresPath].new")] public string LocresOutputPath { get; set; } } ``` -------------------------------- ### GetExporterExtensions and GetImporterExtensions signatures Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/cli.md Declares methods that return the registered extension keys as a List. With built-ins, exporters return ["csv","pot"] and importers ["csv","po"]. ```csharp public static List GetExporterExtensions() public static List GetImporterExtensions() ``` -------------------------------- ### Import command usage Source: https://github.com/akintos/unreallocres/blob/master/README.md Shows the command-line usage for the import subcommand. Use this to import a translation file (CSV or POT) into an original locres file and create a new translated locres file. The default output path is the input locres path with '.new' appended. ```text usage: UnrealLocres.exe import locres_file_path translation_file_path [-f {csv,pot}] [-o output_path] positional arguments: locres_file_path Input locres file path translation_file_path Input translation file path optional arguments: -f, --format {csv,pot} Translation file format (csv, pot) -o Output locres file path (default: {locres_file_path}.new) ``` -------------------------------- ### Load(Stream stream) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Loads a locres file from a seekable, readable stream. Detects the file format version, parses namespaces and string entries, and populates the LocresFile instance. Throws ArgumentException if the stream is not seekable or readable. ```APIDOC ## Load(Stream stream) ### Description Loads a locres file from a seekable, readable stream. Detects the file format version, parses namespaces and string entries, and populates the LocresFile instance. Throws ArgumentException if the stream is not seekable or readable. ### Method Load ### Signature public void Load(Stream stream) ### Parameters #### Parameters - **stream** (Stream) - Required - Seekable, readable stream positioned at the start of a locres file. ### Return Type void ### Remarks On success, `Version` is set to the detected format and the list is fully populated. The list is `Clear()`ed before parsing, so a failed or repeated load never accumulates namespaces. ### Format Detection and Read Rules - Reads 16 bytes and compares against `LOCRES_MAGIC` (`0x0E 0x14 0x74 0x75 0x67 0x4A 0x03 0xFC 0x4A 0x15 0x90 0x9D 0xC3 0x37 0x7F 0x1B`). On match, `Version = (LocresVersion)reader.ReadByte()`; otherwise `Version = LocresVersion.Legacy` and the stream position is reset to `0`. - `Version >= Compact`: reads a `long` `localizedStringArrayOffset`, seeks there, reads an `int32` string count and the string LUT. For `Version >= Optimized` each LUT entry also carries an `int32` refCount, which is read and discarded. The reader then seeks back to the resume point. - `Version >= Optimized`: a single `int32` (`entriesCount`) is read and discarded before the namespace count. - Per namespace: reads an optional `uint32` keyHash (Optimized+; discarded), the namespace key as an Unreal string, and an `int32` key count. Per entry: reads the optional `uint32` stringKeyHash (Optimized+; discarded), the string key, a `uint32` sourceStringHash, then either an `int32` LUT index (Compact+) or the full value string (Legacy). ### Throws | Error type | Condition | |------------|-----------| | `ArgumentException` | `stream.CanSeek` is `false` ("Stream must be seekable.") | | `ArgumentException` | `stream.CanRead` is `false` ("Stream must be readable.") | | (unchecked) | A corrupt Compact+ file whose LUT index is out of range causes an array-index failure on `localizedStringArray[stringIndex]` (`LocresLib/LocresFile.cs` line 114). | ### Example: load ```cs using LocresLib; using System.IO; var locres = new LocresFile(); using (var file = File.OpenRead("en.locres")) { locres.Load(file); } Console.WriteLine($"Version: {locres.Version}, total strings: {locres.TotalCount}"); ``` ### Example: error handling ```cs using LocresLib; var locres = new LocresFile(); try { var file = File.OpenRead("missing.locres"); // non-readable path locres.Load(file); } catch (ArgumentException e) { // "Stream must be readable." / "Stream must be seekable." Console.WriteLine($"Failed to load: {e.Message}"); } ``` ``` -------------------------------- ### LocresString constructor signature Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresString.md Constructor signature. Requires non-null key and value; sourceStringHash is stored verbatim and written back unchanged by LocresFile.Save. ```cs public LocresString(string key, string value, uint sourceStringHash) ``` -------------------------------- ### CityHash64 overload signatures Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CityHash.md Shows the three overloads of the CityHash64 method family. Overload 1 delegates to overload 2 with Encoding.Default; overload 2 encodes the string and delegates to overload 3; overload 3 is the core byte-array implementation. ```csharp public static uint64 CityHash64(string s) public static uint64 CityHash64(string s, Encoding encoding) public static uint64 CityHash64(byte[] s) ``` -------------------------------- ### BinaryWriterExtensions class definition Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/IO.md Defines the BinaryWriterExtensions static class with IsAsciiString and WriteUnrealString methods. WriteUnrealString appends a null terminator and writes an int32 length prefix, using ASCII when possible and UTF-16-LE otherwise. ```csharp public static class BinaryWriterExtensions { internal static bool IsAsciiString(string value) { for (int i = 0; i < value.Length; i++) if (value[i] > 127) return false; return true; } internal static void WriteUnrealString(this BinaryWriter writer, string value, bool forceUnicode = false) { value += "\x00"; if (!forceUnicode && IsAsciiString(value)) // ASCII { var data = Encoding.ASCII.GetBytes(value); writer.Write(data.Length); writer.Write(data); } else // UTF-16-LE { var data = Encoding.Unicode.GetBytes(value); writer.Write(value.Length * -1); writer.Write(data); } } } ``` -------------------------------- ### UInt128 constructor signature Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/UInt128.md The constructor signature for creating a UInt128 with low and high 64-bit halves. ```csharp public UInt128(UInt64 low, UInt64 high) ``` -------------------------------- ### Write method implementation Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/CsvConverter.md The Write method implementation that writes a header row and rows with an always-empty target column. ```cs protected override void Write(List data, TextWriter writer) { var rows = data.Select(x => new string[] { x.Key, x.Source, "" }); CsvWriter.Write(writer, new string[] { "key", "source", "target" }, rows); } ``` -------------------------------- ### UnrealLocres.exe import Source: https://github.com/akintos/unreallocres/blob/master/README.md Imports a translation file (CSV or POT) into an original locres file and creates a new translated locres file. The translation file format must match the specified format. ```APIDOC ## [IMPORT] UnrealLocres.exe import ### Description Imports a translation file (CSV or POT) into an original locres file and creates a new translated locres file. The translation file format must match the specified format. ### Method IMPORT ### Endpoint UnrealLocres.exe import locres_file_path translation_file_path [-f {csv,pot}] [-o output_path] ### Parameters #### Path Parameters - **locres_file_path** (string) - Required - Input locres file path - **translation_file_path** (string) - Required - Input translation file path #### Optional Arguments - **-f, --format** (string) - Optional - Translation file format (csv, pot) - **-o** (string) - Optional - Output locres file path (default: {locres_file_path}.new) ### Request Example ``` UnrealLocres.exe import C:\\path\\to\\original.locres C:\\path\\to\\translations.csv -f csv -o C:\\path\\to\\translated.locres ``` ### Response #### Success Response - **output_file** (file) - The newly created translated locres file #### Response Example ``` (No structured response body; the command writes the output file to disk.) ``` ``` -------------------------------- ### Import(LocresFile locres, string inputPath) Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/BaseConverter.md Imports translations from a file into the provided LocresFile, mutating it in place. It reads the file, applies matching translations, and reports progress and warnings. ```APIDOC ## Import(LocresFile locres, string inputPath) ### Description Imports translations from a file into the provided LocresFile, mutating it in place. It reads the file, applies matching translations, and reports progress and warnings. ### Method Import ### Signature ```cs public void Import(LocresFile locres, string inputPath) ``` ### Parameters - **locres** (`LocresFile`) - Required - Loaded resource file to translate in place (mutates `LocresString.Value`). - **inputPath** (`string`) - Required - Translation file to read with `File.OpenRead` + `StreamReader`. ### Return Type `void` ### Behavior 1. Calls the abstract `Read(reader)`, closing the file afterwards. 2. Screens out entries with an empty `Target` — only `translatedList` participates in matching. 3. Prints `Loaded {inputPath}` and `Translated {translated} / {total} ({translated/total:P})`. 4. Builds `dict` keyed by `TranslationEntry.Key`. For every `(namespace, string)` pair it looks up `ns.Name + "/" + str.Key`; on a hit with a non-empty target it writes `str.Value = tr.Target` and removes the key from `dict`. 5. Any leftover keys (translations that matched nothing) produce a `WARNING: {n} translations are not used. Please check translation key.` block, one `\t[{key}] \"{source}\"` line per leftover — source is truncated to 40 chars with `"..."` and has `\r` / `\n` escaped to `\\r` / `\\n`. 6. Prints `\nImported {translated - dict.Count} translations.` (matched counts are the translations actually applied). ``` -------------------------------- ### CityHash64_utf16_to_uint32 method implementation Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/LocresFile.md Static method that encodes a string to UTF-16-LE, computes CityHash64, and folds the 64-bit hash to a 32-bit uint using the UE4 TypeHash.h formula. Returns 0 for an empty string without hashing. Used for namespace/key pre-hashing in LocresVersion.Optimized_CityHash64_UTF16 files. ```csharp /// /// Encode string with UTF-16-LE, calculate CityHash64 and get uint32 hash of cityhash. ///
/// uint64 to uint32 hash function: https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Templates/TypeHash.h#L81 ///
public static uint CityHash64_utf16_to_uint32(string s) { if (s.Length == 0) return 0; byte[] b = Encoding.Unicode.GetBytes(s); ulong h = CityHash.CityHash64(b); uint r = (uint)h + ((uint)(h >> 32) * 23); return r; } ``` -------------------------------- ### GetExporter and GetImporter signatures Source: https://github.com/akintos/unreallocres/blob/master/_autodocs/api-reference/cli.md Declares methods that look up a converter by extension. Returns true and populates the out parameter on success, implemented via Dictionary.TryGetValue. ```csharp public static bool GetExporter(string extension, out BaseConverter exporter) public static bool GetImporter(string extension, out BaseConverter importer) ```