mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
23 changed files with 768360 additions and 0 deletions
|
|
@ -0,0 +1,16 @@
|
|||
namespace Brutal.Localization.FixedBuffers;
|
||||
|
||||
public static class LengthHint
|
||||
{
|
||||
/// <summary>
|
||||
/// Pass this to <see cref="IFixedBufferWriter<T>.GetSpan" /> or <see cref="IFixedBufferWriter<T>.TryGetSpan" />
|
||||
/// to request the largest available span size the writer can return.
|
||||
/// </summary>
|
||||
public static readonly ElementCount MaxLengthHint = int.MinValue + 1;
|
||||
|
||||
/// <summary>
|
||||
/// Pass this to <see cref="IFixedBufferWriter<T>.GetSpan" /> or <see cref="IFixedBufferWriter<T>.TryGetSpan" />
|
||||
/// to request any span size greater than or equal to one.
|
||||
/// </summary>
|
||||
public static readonly ElementCount NonZeroLengthHint = int.MinValue;
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
namespace Brutal.Localization.FixedBuffers;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for types that provide fixed writable buffers.
|
||||
/// A fixed buffer must not be movable by the GC. For example a stackalloc'd buffer
|
||||
/// or an array you have manually fixed.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the elements stored in the buffer.</typeparam>
|
||||
public interface IFixedBufferWriter<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// Tells the buffer writer that a number of elements have been written and the buffer writer
|
||||
/// should advance its write position.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements that were written.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if count moves the write position past the end of the writer's maximum position, or
|
||||
/// if count is negative. </exception>
|
||||
public void Advance(ElementCount count);
|
||||
|
||||
/// <summary>
|
||||
/// Get a Span that can hold at least a specified number of elements.
|
||||
/// </summary>
|
||||
/// <param name="lengthHint">One of either:
|
||||
/// <list>
|
||||
/// <item>LengthHint.NonZeroLengthHint: Request a non-empty Span of unspecified length.</item>
|
||||
/// <item>LengthHint.MaxLengthHint: Request the largest Span possible.</item>
|
||||
/// <item>Otherwise, a specific Span length to return.</item>
|
||||
/// </list></param>
|
||||
/// <returns>A Span of the requested length or greater. Must never return an empty Span but can throw if the request cannot be fulfilled.</returns>
|
||||
public Span<T> GetSpan(ElementCount lengthHint);
|
||||
|
||||
/// <summary>
|
||||
/// Try to get a Span that can hold at least a specified number of elements, returning whether it succeeded or not.
|
||||
/// </summary>
|
||||
/// <param name="lengthHint"> <inheritdoc cref="IFixedBufferWriter{T}.GetSpan(ElementCount)" /></param>
|
||||
/// <param name="spanOut">When this method returns, if successful, contains a Span of the requested length or greater . If not successful will contain the largest Span that could have been returned.</param>
|
||||
/// <returns>true if a Span of the requested length or greater is returned. Otherwise, false.</returns>
|
||||
public bool TryGetSpan(ElementCount lengthHint, out Span<T> spanOut);
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
using System.Diagnostics;
|
||||
using Brutal.Attributes;
|
||||
|
||||
namespace Brutal.Localization.FixedBuffers;
|
||||
|
||||
/// <summary>
|
||||
/// An IFixedBufferWriter that will wrap around and reuse its storage if the length requested for a Span is greater than
|
||||
/// the remaining storage but less than or equal to its capacity. If you ask for lengths that fit within it's remaining
|
||||
/// storage it will return part or all of it's remaining storage depending on the length hint. However, if you ask for
|
||||
/// <see cref="LengthHint.MaxLengthHint" /> or a specific size that's larger than the remaining storage, it can give you up
|
||||
/// to its Capacity by wrapping around. Using <see cref="LengthHint.MaxLengthHint" /> with a <see cref="RingBufferWriter<T>" /> essentially gives you a writer that will automatically
|
||||
/// reuse its storage each time you call GetSpan or TryGetSpan.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The element type stored in the RingBufferWriter.</typeparam>
|
||||
/// <remarks>Instantiating a default instance of <see cref="RingBufferWriter<T>" /> is an error due to no specification
|
||||
/// of the underlying buffer. Calls to <see cref="GetSpan" /> or <see cref="TryGetSpan" /> will throw <see cref="InvalidOperationException" /> in this case.</remarks>
|
||||
public ref struct RingBufferWriter<T> : IFixedBufferWriter<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a RingBufferWriter from a Span.
|
||||
/// </summary>
|
||||
/// <param name="span">The <see cref="System.Span<T>" /> to use as the underlying storage.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if span is empty.</exception>
|
||||
public RingBufferWriter(Span<T> span)
|
||||
{
|
||||
if (span.IsEmpty)
|
||||
throw new ArgumentException("Span must not be empty", nameof(span));
|
||||
|
||||
_span = span;
|
||||
_pos = 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFixedBufferWriter{T}.Advance"/>
|
||||
public void Advance(ElementCount count)
|
||||
{
|
||||
if (count < 0 || (count > 0 && count > RemainingLength))
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(count),
|
||||
$"Advance count out of range. Valid values are 0-{RemainingLength}"
|
||||
);
|
||||
_pos += count;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFixedBufferWriter{T}.GetSpan"/>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if requested length is zero. This limitation may be removed at a later date.</exception>
|
||||
/// <remarks>Instantiating a default instance of <see cref="RingBufferWriter<T>" /> is an error due to no specification
|
||||
/// of the underlying buffer. Calls to <see cref="GetSpan" /> or <see cref="TryGetSpan" /> will throw <see cref="InvalidOperationException" /> in this case.</remarks>
|
||||
public Span<T> GetSpan(ElementCount lengthHint)
|
||||
{
|
||||
if (lengthHint == 0)
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(lengthHint),
|
||||
"Cannot request a zero length span."
|
||||
);
|
||||
|
||||
if (!TryGetSpan(lengthHint, out var spanOut))
|
||||
throw new ArgumentException(
|
||||
$"Out of buffer. requested:{lengthHint} available:{spanOut.Length}",
|
||||
nameof(lengthHint)
|
||||
);
|
||||
return spanOut;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFixedBufferWriter{T}.TryGetSpan"/>
|
||||
/// <remarks>Instantiating a default instance of <see cref="RingBufferWriter<T>" /> is an error due to no specification
|
||||
/// of the underlying buffer. Calls to <see cref="GetSpan" /> or <see cref="TryGetSpan" /> will throw <see cref="InvalidOperationException" /> in this case.</remarks>
|
||||
public bool TryGetSpan(ElementCount lengthHint, out Span<T> spanOut)
|
||||
{
|
||||
ThrowIfNoCapacity();
|
||||
|
||||
var returnLength = lengthHint;
|
||||
if (lengthHint == LengthHint.NonZeroLengthHint)
|
||||
returnLength = RemainingLength != 0 ? RemainingLength : Capacity;
|
||||
else if (lengthHint == LengthHint.MaxLengthHint || lengthHint > Capacity)
|
||||
returnLength = Capacity;
|
||||
else if (lengthHint < 0)
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(lengthHint),
|
||||
"lengthHint cannot be negative."
|
||||
);
|
||||
|
||||
Debug.Assert(returnLength <= Capacity);
|
||||
|
||||
if (returnLength > RemainingLength)
|
||||
Reset();
|
||||
|
||||
spanOut = RemainingSpan;
|
||||
return lengthHint == LengthHint.NonZeroLengthHint
|
||||
|| lengthHint == LengthHint.MaxLengthHint
|
||||
|| spanOut.Length >= lengthHint;
|
||||
}
|
||||
|
||||
private void ThrowIfNoCapacity()
|
||||
{
|
||||
if (Capacity < 1)
|
||||
throw new InvalidOperationException(
|
||||
$"Invalid Capacity (0). Did you create a default instance of this writer without a Span?"
|
||||
);
|
||||
}
|
||||
|
||||
private Span<T> RemainingSpan => _span.Slice(_pos, RemainingLength);
|
||||
|
||||
private void Reset() => _pos = 0;
|
||||
|
||||
private int RemainingLength => _span.Length - _pos;
|
||||
private int Capacity => _span.Length;
|
||||
private int _pos;
|
||||
private readonly Span<T> _span;
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.Localization.FixedBuffers;
|
||||
|
||||
public static class TryWriteInterpolatedStringHandlerExtensions
|
||||
{
|
||||
extension(MemoryExtensions.TryWriteInterpolatedStringHandler handler)
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the number of elements currently written to a TryWriteInterpolatedStringHandler.
|
||||
/// </summary>
|
||||
/// <returns>The number of elements written.</returns>
|
||||
public int ElementsWritten()
|
||||
{
|
||||
var shouldBeTrue = MemoryExtensions.TryWrite([], ref handler, out var elementsWritten);
|
||||
Debug.Assert(shouldBeTrue, "TryWrite with empty collection should always succeed.");
|
||||
|
||||
return elementsWritten;
|
||||
}
|
||||
}
|
||||
}
|
||||
24
brutal.localization/Brutal.Localization/DefaultOptions.cs
Normal file
24
brutal.localization/Brutal.Localization/DefaultOptions.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// The default values used by various parts of Brutal.Localization.
|
||||
/// </summary>
|
||||
public static partial class DefaultOptions
|
||||
{
|
||||
private const string RegexExpression = @"([{]_*\p{Lu}[\p{Lu}\p{Ll}_\d]*[}])";
|
||||
|
||||
/// <summary>
|
||||
/// The Regex pattern to use to match replacement variables in localizable strings. If you wish to use a different pattern
|
||||
/// set this field before creating <see cref="LString" /> instances.
|
||||
/// </summary>
|
||||
[GeneratedRegex(RegexExpression, RegexOptions.IgnoreCase, "en-US")]
|
||||
public static partial Regex ReplacementPattern();
|
||||
|
||||
/// <summary>
|
||||
/// The initial span length that any of the <see cref="LString.Format{TWriter}(TWriter)" /> methods will request from the <see cref="FixedBuffers.IFixedBufferWriter<T>" />.
|
||||
/// For more information on how this value is used see <see cref="LString.Format{TWriter}(TWriter)" />.
|
||||
/// </summary>
|
||||
public static readonly ElementCount FormatInitialSpanLength = 256;
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
THIRD-PARTY LICENSE NOTICES
|
||||
RocketWerkz.Brutal.Localization
|
||||
|
||||
This package redistributes the third-party component listed below. It is reproduced
|
||||
with the license that governs it.
|
||||
|
||||
|
||||
==============================================================================
|
||||
ResX.NET
|
||||
==============================================================================
|
||||
|
||||
Name ResX.NET, by winscripter
|
||||
Version 1.0.0, the version upstream states for itself. Upstream publishes
|
||||
no tagged release.
|
||||
Upstream https://github.com/winscripter/resx-net
|
||||
SPDX MIT
|
||||
Shipped as C# source compiled into Brutal.Localization.dll, as the types in the
|
||||
Brutal.Localization.ResX namespace
|
||||
|
||||
The code has been modified: it was moved into the namespace above, and has since
|
||||
received bug fixes.
|
||||
|
||||
Separately, this package writes the ResX 2.0 schema header into the .resx files it
|
||||
produces. That header is part of the ResX file format and originates with it.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 winscripter
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
72
brutal.localization/Brutal.Localization/LString.Format.cs
Normal file
72
brutal.localization/Brutal.Localization/LString.Format.cs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
public partial class LString
|
||||
{
|
||||
/// <summary>
|
||||
/// Takes a single argument and formats it into the buffer of a DefaultInterpolatedStringHandler
|
||||
/// </summary>
|
||||
/// <param name="arg">The object to format.</param>
|
||||
/// <param name="replaceableIndex">The index of the replaceable the argument is for.</param>
|
||||
/// <param name="h">The interpolated string handler to use for formatting.</param>
|
||||
/// <typeparam name="T">The type of arg.</typeparam>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the replacement type of the argument is not handled.</exception>
|
||||
private bool TryFormatReplacement<T>(
|
||||
T arg,
|
||||
int replaceableIndex,
|
||||
ref MemoryExtensions.TryWriteInterpolatedStringHandler h
|
||||
)
|
||||
{
|
||||
var localizedSpan = _localizedString.AsSpan();
|
||||
var replacementsSpan = CollectionsMarshal.AsSpan(_replacements);
|
||||
ref var replacement = ref replacementsSpan[replaceableIndex];
|
||||
|
||||
var success = true;
|
||||
if (replacement.HasPrecedingLiteral)
|
||||
success &= h.AppendFormatted(
|
||||
localizedSpan[
|
||||
replacement.LiteralRange.Start.Value..replacement.LiteralRange.End.Value
|
||||
]
|
||||
);
|
||||
|
||||
return success & h.AppendFormatted(arg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes a single argument and formats it into the buffer of a DefaultInterpolatedStringHandler
|
||||
/// </summary>
|
||||
/// <param name="arg">The object to format.</param>
|
||||
/// <param name="replaceableIndex">The index of the replaceable the argument is for.</param>
|
||||
/// <param name="h">The interpolated string handler to use for formatting.</param>
|
||||
/// <typeparam name="T">The type of arg.</typeparam>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the replacement type of the argument is not handled.</exception>
|
||||
private void FormatReplacement<T>(
|
||||
in T arg,
|
||||
int replaceableIndex,
|
||||
ref DefaultInterpolatedStringHandler h
|
||||
)
|
||||
{
|
||||
var localizedSpan = _localizedString.AsSpan();
|
||||
var replacementsSpan = CollectionsMarshal.AsSpan(_replacements);
|
||||
ref var replacement = ref replacementsSpan[replaceableIndex];
|
||||
|
||||
if (replacement.HasPrecedingLiteral)
|
||||
h.AppendFormatted(
|
||||
localizedSpan[
|
||||
replacement.LiteralRange.Start.Value..replacement.LiteralRange.End.Value
|
||||
]
|
||||
);
|
||||
|
||||
h.AppendFormatted(arg);
|
||||
}
|
||||
|
||||
private void ValidateReplacementCount(int numberOfPassedArguments)
|
||||
{
|
||||
if (_replacements.Count != numberOfPassedArguments)
|
||||
throw new ArgumentException(
|
||||
$"Incorrect number of replacement values passed to LString {Id}. expected:{_replacements.Count} passed:{numberOfPassedArguments}"
|
||||
);
|
||||
}
|
||||
}
|
||||
3117
brutal.localization/Brutal.Localization/LString.Format.gen.cs
Normal file
3117
brutal.localization/Brutal.Localization/LString.Format.gen.cs
Normal file
File diff suppressed because it is too large
Load diff
209
brutal.localization/Brutal.Localization/LString.cs
Normal file
209
brutal.localization/Brutal.Localization/LString.cs
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// A class that represents a localizable string.
|
||||
/// </summary>
|
||||
public partial class LString
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a localizable string from a template string. The format of the template will depend on the Regex assigned
|
||||
/// to ReplacementPattern.
|
||||
/// Upon creation the LString is NOT localized. Therefore, calling any of the
|
||||
/// <see cref="Format"/> methods before it has been localized will return the templateString.
|
||||
/// </summary>
|
||||
/// <param name="id">An immutable, unique id that identifies this LString.</param>
|
||||
/// <param name="templateString">The string to use as a template for the localized string. Can be empty.</param>
|
||||
/// <param name="replacementPattern">The Regex to use to match replacement variables. If null, uses <see cref="DefaultOptions.ReplacementPattern" /></param>
|
||||
public LString(LStringId id, string templateString, Regex? replacementPattern = null)
|
||||
{
|
||||
Id = id;
|
||||
_replacements = new List<Replacement>(MaxReplacementCount);
|
||||
_templateString = templateString;
|
||||
_replacementPattern = replacementPattern ?? DefaultOptions.ReplacementPattern();
|
||||
_localizedString = templateString;
|
||||
BuildReplacements(true);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="LString(LStringId,string,System.Text.RegularExpressions.Regex?)"/>
|
||||
/// <exception cref="ArgumentException">Thrown if id is null or empty.</exception>
|
||||
public LString(string id, string templateString, Regex? replacementPattern = null)
|
||||
: this(LStringId.From(id), templateString, replacementPattern) { }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the unique id of the LString.
|
||||
/// </summary>
|
||||
public LStringId Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the string used as the template string when creating this instance
|
||||
/// of LString.
|
||||
/// </summary>
|
||||
public string Template => _templateString;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current localized string for this LString or returns Template if this LString has not been localized yet.
|
||||
/// </summary>
|
||||
public string Localized => _localizedString;
|
||||
|
||||
/// <summary>
|
||||
/// Localizes the LString with specified content.
|
||||
/// localizedString is validated to ensure it meets the criteria of the template string.
|
||||
/// e.g., it must have the same number and names of replacement variables.
|
||||
/// </summary>
|
||||
/// <param name="localizedString">The localized version of the template string</param>
|
||||
/// <exception cref="ArgumentException">Thrown if localizedString does not have the correct number and names of replacement variables.</exception>
|
||||
/// <exception cref="ArgumentNullException">Thrown if localizedString is null.</exception>
|
||||
public void Localize(string localizedString)
|
||||
{
|
||||
Update(localizedString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the localized version of the string, thereby returning it
|
||||
/// to its template string.
|
||||
/// </summary>
|
||||
public void RemoveLocalization()
|
||||
{
|
||||
Update(_templateString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Regex used by this LString to match replacement variables.
|
||||
/// </summary>
|
||||
public Regex ReplacementPattern => _replacementPattern;
|
||||
|
||||
#region Private
|
||||
|
||||
[MemberNotNull(nameof(_localizedString))]
|
||||
private void Update(string localizedString)
|
||||
{
|
||||
_localizedString =
|
||||
localizedString ?? throw new ArgumentNullException(nameof(localizedString));
|
||||
BuildReplacements(false);
|
||||
}
|
||||
|
||||
private void BuildReplacements(bool isInitialBuild)
|
||||
{
|
||||
_literalCharCount = 0;
|
||||
_endLiteralStart = 0;
|
||||
var matches = _replacementPattern.EnumerateMatches(_localizedString);
|
||||
var nextPossibleLiteralStart = 0;
|
||||
ushort replacementCount = 0;
|
||||
foreach (var match in matches)
|
||||
{
|
||||
if (!isInitialBuild && replacementCount >= _replacements.Count)
|
||||
throw IncorrectReplacementCountException(Template, _localizedString);
|
||||
|
||||
var matchPos = match.Index;
|
||||
var templateReplacementIndex = isInitialBuild
|
||||
? replacementCount
|
||||
: GetTemplateStringReplacementIndex(
|
||||
_localizedString.AsSpan()[matchPos..(matchPos + match.Length)]
|
||||
);
|
||||
|
||||
_literalCharCount += matchPos - nextPossibleLiteralStart;
|
||||
var replacementRange = new Range(matchPos, matchPos + match.Length);
|
||||
var literalRange =
|
||||
matchPos > nextPossibleLiteralStart
|
||||
? new Range(nextPossibleLiteralStart, matchPos)
|
||||
: default;
|
||||
|
||||
if (isInitialBuild)
|
||||
_replacements.Add(
|
||||
new Replacement()
|
||||
{
|
||||
TemplateRange = replacementRange,
|
||||
LiteralRange = literalRange,
|
||||
TemplateReplacementIndex = templateReplacementIndex,
|
||||
}
|
||||
);
|
||||
else
|
||||
_replacements[replacementCount] = _replacements[replacementCount] with
|
||||
{
|
||||
LiteralRange = literalRange,
|
||||
TemplateReplacementIndex = templateReplacementIndex,
|
||||
};
|
||||
|
||||
nextPossibleLiteralStart = replacementRange.End.Value;
|
||||
++replacementCount;
|
||||
}
|
||||
|
||||
if (!isInitialBuild && replacementCount != _replacements.Count)
|
||||
throw IncorrectReplacementCountException(Template, _localizedString);
|
||||
|
||||
_endLiteralStart =
|
||||
nextPossibleLiteralStart == 0 ? _localizedString.Length : nextPossibleLiteralStart;
|
||||
}
|
||||
|
||||
private ushort GetTemplateStringReplacementIndex(ReadOnlySpan<char> replacementText)
|
||||
{
|
||||
for (
|
||||
ushort existingReplacementIndex = 0;
|
||||
existingReplacementIndex < _replacements.Count;
|
||||
++existingReplacementIndex
|
||||
)
|
||||
{
|
||||
var templateReplacement = Template.AsSpan()[
|
||||
_replacements[existingReplacementIndex].TemplateRange
|
||||
];
|
||||
if (templateReplacement.SequenceEqual(replacementText))
|
||||
return existingReplacementIndex;
|
||||
}
|
||||
throw UnknownReplacementVariableException(Template, replacementText);
|
||||
}
|
||||
|
||||
private static ArgumentException UnknownReplacementVariableException(
|
||||
string template,
|
||||
ReadOnlySpan<char> replacementText
|
||||
)
|
||||
{
|
||||
return new ArgumentException(
|
||||
$"Unknown replacement variable: {replacementText}. Did not exist in LString {template}"
|
||||
);
|
||||
}
|
||||
|
||||
private static Exception IncorrectReplacementCountException(
|
||||
string template,
|
||||
string localizedString
|
||||
)
|
||||
{
|
||||
return new ArgumentException(
|
||||
$"Incorrect replacement count for localized string {localizedString}. Template was {template}"
|
||||
);
|
||||
}
|
||||
|
||||
private readonly struct Replacement
|
||||
{
|
||||
/// <summary>
|
||||
/// Original Range within the template string of this Replacement. Retrieve the template string with
|
||||
/// the <see cref="Template"/> property.
|
||||
/// </summary>
|
||||
public required Range TemplateRange { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The index of the replacement inside the original Template string.
|
||||
/// </summary>
|
||||
public required ushort TemplateReplacementIndex { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this replacement has a preceding literal.
|
||||
/// </summary>
|
||||
public bool HasPrecedingLiteral => LiteralRange.End.Value > LiteralRange.Start.Value;
|
||||
public required Range LiteralRange { get; init; } // The range of any literal preceding this Replacement
|
||||
}
|
||||
|
||||
private readonly string _templateString; // The original template string
|
||||
private string _localizedString; // localized template string
|
||||
|
||||
private readonly List<Replacement> _replacements;
|
||||
private int _endLiteralStart; // if _endLiteralStart < length of _localizedString, there's a literal past the last replacement (Or _localizedString only a literal)
|
||||
private int _literalCharCount; // How many literal characters in the localized string? The interpolated string handlers need this.
|
||||
|
||||
private readonly Regex _replacementPattern;
|
||||
#endregion
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Global options used by LString.
|
||||
/// </summary>
|
||||
public static class LStringGlobalOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// The initial span length that any of the <see cref="LString.Format{TWriter}(TWriter)" /> methods will request from the <see cref="FixedBuffers.IFixedBufferWriter<T>" />.
|
||||
/// For more information on how this value is used see <see cref="LString.Format{TWriter}(TWriter)" />.
|
||||
/// </summary>
|
||||
///
|
||||
public static ElementCount FormatInitialSpanLength { get; set; } =
|
||||
DefaultOptions.FormatInitialSpanLength;
|
||||
}
|
||||
54
brutal.localization/Brutal.Localization/LStringId.cs
Normal file
54
brutal.localization/Brutal.Localization/LStringId.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Strongly typed id for a LString created from a string or ReadOnlySpan{char}.
|
||||
/// LStringId objects are case-sensitive.
|
||||
/// The strings or ReadOnlySpans passed to the constructor cannot be null or empty.
|
||||
/// </summary>
|
||||
public readonly record struct LStringId
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper to create a LStringId from a string.
|
||||
/// </summary>
|
||||
/// <param name="id">The case-sensitive string version of the id.</param>
|
||||
/// <returns>The created LStringId.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if id is null or empty.</exception>
|
||||
public static LStringId From(string id)
|
||||
{
|
||||
return new LStringId(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a LStringId from a ReadOnlySpan.
|
||||
/// </summary>
|
||||
/// <remarks>NOTE: LStringId objects are case-insensitive.</remarks>
|
||||
/// <param name="id">The ReadOnlySpan of chars of the LStringId to create.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if the ReadOnlySpan is empty.</exception>
|
||||
public LStringId(ReadOnlySpan<char> id)
|
||||
{
|
||||
if (id.IsEmpty)
|
||||
throw new ArgumentException($"Invalid LStringId '{id}'", nameof(id));
|
||||
|
||||
_value = id.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a LStringId from a string.
|
||||
/// </summary>
|
||||
/// <param name="id">The case-sensitive string to use for the LStringId.</param>
|
||||
/// <exception cref="ArgumentException">Thrown if id is null or empty.</exception>
|
||||
public LStringId(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
throw new ArgumentException($"Invalid LStringId '{id}'");
|
||||
|
||||
_value = id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The string value of the LStringId.
|
||||
/// </summary>
|
||||
public override string ToString() => _value;
|
||||
|
||||
private readonly string _value;
|
||||
}
|
||||
96
brutal.localization/Brutal.Localization/LStrings.cs
Normal file
96
brutal.localization/Brutal.Localization/LStrings.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// LStrings is a convenience static wrapper around a singleton-like instance of LocalizedStrings.
|
||||
/// For use if you don't like typing LocalizedStrings.Shared.Method().
|
||||
/// Investigation showed that this redirection does not introduce extra jumps and returns.
|
||||
/// </summary>
|
||||
// TODO:AKB - Add analyser to check all methods from LocalizedStrings are in here as well. I did add a UnitTest to check for signatures which is a start.
|
||||
public static class LStrings
|
||||
{
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.SetLocalizedStringProvider"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.SetLocalizedStringProvider"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetLocalizedStringProvider(
|
||||
LocalizedStrings.GetLocalizedStringDelegate stringProvider
|
||||
) => Shared.SetLocalizedStringProvider(stringProvider);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the delegate that is currently providing localized versions of LString instances.
|
||||
/// </summary>
|
||||
/// <returns>The <see cref="LocalizedStrings.GetLocalizedStringDelegate"/> or null if one is not set.</returns>
|
||||
public static LocalizedStrings.GetLocalizedStringDelegate? LocalizedStringProvider =>
|
||||
Shared.LocalizedStringProvider;
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.RemoveLocalizedStringProvider"/>
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void RemoveLocalizedStringProvider() => Shared.RemoveLocalizedStringProvider();
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Create(string, string)"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Create(string, string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static LString Create(string id, string templateString) =>
|
||||
Shared.Create(LStringId.From(id), templateString);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Create(LStringId, string)"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Create(LStringId, string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static LString Create(LStringId id, string templateString) =>
|
||||
Shared.Create(id, templateString);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.GetOrCreate(LStringId, string)"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.GetOrCreate(LStringId, string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static LString GetOrCreate(LStringId id, string templateString) =>
|
||||
Shared.GetOrCreate(id, templateString);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.GetOrCreate(string, string)"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.GetOrCreate(string, string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static LString GetOrCreate(string id, string templateString) =>
|
||||
Shared.GetOrCreate(LStringId.From(id), templateString);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Remove"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.Remove"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool Remove(LStringId id) => Shared.Remove(id);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.RemoveAll"/>
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void RemoveAll() => Shared.RemoveAll();
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.TryGet"/>
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.TryGet"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool TryGet(LStringId id, [NotNullWhen(true)] out LString? localizedString) =>
|
||||
Shared.TryGet(id, out localizedString);
|
||||
|
||||
/// <summary>
|
||||
/// <inheritdoc cref="LocalizedStrings.LStringInstances"/>
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<LStringId, LString> LStringInstances =>
|
||||
Shared.LStringInstances;
|
||||
|
||||
private static readonly LocalizedStrings Shared = new(LStringsOptions.ReplacementPattern);
|
||||
}
|
||||
16
brutal.localization/Brutal.Localization/LStringsOptions.cs
Normal file
16
brutal.localization/Brutal.Localization/LStringsOptions.cs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Options used by the static wrapper, <see cref="LStrings"/>. Set these options before the first instance of an <see cref="LString"/> is
|
||||
/// created through with <see cref="LStrings"/>.
|
||||
/// </summary>
|
||||
public static class LStringsOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// The Regex pattern to use to match replacement variables in localizable strings. If you wish to use a different pattern
|
||||
/// set this field before creating <see cref="LString" /> instances.
|
||||
/// </summary>
|
||||
public static Regex ReplacementPattern = DefaultOptions.ReplacementPattern();
|
||||
}
|
||||
216
brutal.localization/Brutal.Localization/LocalizedStrings.cs
Normal file
216
brutal.localization/Brutal.Localization/LocalizedStrings.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.RegularExpressions;
|
||||
using Brutal.Logging;
|
||||
|
||||
namespace Brutal.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Class for managing localization of strings via LString instances. You can create multiple instances of
|
||||
/// LocalizedStrings and each will act without interfering with any other instances.
|
||||
/// Typically, however, you will use a single static instance which can be used simply by calling the static
|
||||
/// methods in LStrings. The LStrings methods all simply redirect to a shared instance of LocalizedStrings.
|
||||
/// </summary>
|
||||
public class LocalizedStrings
|
||||
{
|
||||
/// <summary>
|
||||
/// A delegate that takes a <see cref="LString" /> and return a localized version of that LString's template string.
|
||||
/// In typical use, this delegate acts as a language provider.
|
||||
/// Your implementation of <see cref="GetLocalizedStringDelegate"/> must set localizedTemplateString to a non-null
|
||||
/// string if you return true (Indicating that a string was found).
|
||||
/// </summary>
|
||||
/// <param name="lString">The LString whose localized string has been requested.</param>
|
||||
/// <param name="localizedTemplateString">The out variable that is set if this method returns true.</param>
|
||||
/// <returns>true if the delegate found and returned a string. Otherwise, false.</returns>
|
||||
public delegate bool GetLocalizedStringDelegate(
|
||||
LString lString,
|
||||
[NotNullWhen(true)] out string? localizedTemplateString
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new instance of LocalizedStrings. Each instance is its own string localization environment.
|
||||
/// </summary>
|
||||
/// <param name="replacementPattern">The Regex to use to match replacement variables in LStrings created by this LocalizedStrings instance. If null, uses <see cref="DefaultOptions.ReplacementPattern" /></param>
|
||||
public LocalizedStrings(Regex? replacementPattern = null)
|
||||
{
|
||||
_lStringProvider = null;
|
||||
_stringInstances = new();
|
||||
_replacementPattern = replacementPattern ?? DefaultOptions.ReplacementPattern();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the GetLocalizedStringDelegate that the Brutal localization system will use to look up localized strings. This function
|
||||
/// will also localize all existing LString instances with the new provider.
|
||||
/// <para />
|
||||
/// </summary>
|
||||
/// <param name="stringProvider">A <see cref="GetLocalizedStringDelegate" /> that the localization system will use to look up strings.</param>
|
||||
public void SetLocalizedStringProvider(GetLocalizedStringDelegate stringProvider)
|
||||
{
|
||||
if (stringProvider is null)
|
||||
throw new ArgumentNullException(nameof(stringProvider), @"Null stringProvider");
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_lStringProvider = stringProvider;
|
||||
foreach (var (key, lString) in _stringInstances)
|
||||
{
|
||||
if (!_lStringProvider(lString, out var localizedString))
|
||||
{
|
||||
lString.RemoveLocalization();
|
||||
continue;
|
||||
}
|
||||
|
||||
lString.Localize(localizedString);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the delegate that is currently providing localized versions of LString instances.
|
||||
/// </summary>
|
||||
/// <returns>The <see cref="GetLocalizedStringDelegate"/> or null if one is not set.</returns>
|
||||
public GetLocalizedStringDelegate? LocalizedStringProvider => _lStringProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Removes the provider of localized strings. After calling <see cref="RemoveLocalizedStringProvider" />
|
||||
/// LString instances will return their template string from calls to Format.
|
||||
/// </summary>
|
||||
public void RemoveLocalizedStringProvider()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_lStringProvider = null;
|
||||
foreach (var (_, lString) in _stringInstances)
|
||||
lString.RemoveLocalization();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instantiates a new, unique LString instance with a template string. If there is a string provider
|
||||
/// currently set, the LString will also be localized to the current language.
|
||||
/// </summary>
|
||||
/// <param name="id">A string representing a unique <see cref="LStringId" /> of the LString to create.</param>
|
||||
/// <param name="templateString">The string that defines the non-localized string contents</param>
|
||||
/// <returns>The newly created LString.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if a LString with the same id already exists.</exception>
|
||||
/// <exception cref="ArgumentNullException">Thrown if templateString is null.</exception>
|
||||
public LString Create(string id, string templateString)
|
||||
{
|
||||
return Create(LStringId.From(id), templateString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instantiates a new, unique LString instance with a template string. If there is a GetLocalizedStringDelegate
|
||||
/// currently set, the LString will also be localized to the current language with a language string with the same id.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique <see cref="LStringId" /> of the LString to create.</param>
|
||||
/// <param name="templateString">The string that defines the non-localized string contents</param>
|
||||
/// <returns>The newly created LString.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if a LString with the same id already exists.</exception>
|
||||
/// <exception cref="ArgumentNullException">Thrown if templateString is null.</exception>
|
||||
public LString Create(LStringId id, string templateString)
|
||||
{
|
||||
if (templateString is null)
|
||||
throw new ArgumentNullException(nameof(templateString), @"Null template string");
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
var lString = new LString(id, templateString, _replacementPattern);
|
||||
if (!_stringInstances.TryAdd(lString.Id, lString))
|
||||
throw new ArgumentException($"Duplicate LString with id {id}");
|
||||
|
||||
if (!HasStringProvider)
|
||||
return lString;
|
||||
|
||||
if (!_lStringProvider!(lString, out var localizedString))
|
||||
{
|
||||
DefaultCategory.Log.Debug($"Missing string with id {lString.Id}");
|
||||
return lString;
|
||||
}
|
||||
|
||||
lString.Localize(localizedString);
|
||||
return lString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to get a LString with the given id. If it doesn't exist, it will be created and returned.
|
||||
/// </summary>
|
||||
/// <param name="id">The <see cref="LStringId" /> of the LString to find or create.</param>
|
||||
/// <param name="templateString">The templateString to use for the new LString if a new LString is created.</param>
|
||||
/// <returns>The LString instance found or created.</returns>
|
||||
public LString GetOrCreate(LStringId id, string templateString)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (TryGet(id, out var localizedString))
|
||||
return localizedString;
|
||||
|
||||
return Create(id, templateString);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="GetOrCreate(LStringId, string)"/>
|
||||
public LString GetOrCreate(string id, string templateString)
|
||||
{
|
||||
return GetOrCreate(LStringId.From(id), templateString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a LString from the set of localized strings.
|
||||
/// </summary>
|
||||
/// <param name="id">The identifier of the LString to remove.</param>
|
||||
/// <returns>true if the LString was successfully removed; otherwise, false.</returns>
|
||||
public bool Remove(LStringId id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _stringInstances.Remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes all LString instances.
|
||||
/// </summary>
|
||||
public void RemoveAll()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_stringInstances.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempt to get a LString with the given id and returns whether it was found.
|
||||
/// </summary>
|
||||
/// <param name="id">The <see cref="LStringId" /> of the LString to get.</param>
|
||||
/// <param name="localizedString">The LString that is set, if found. Otherwise undefined.</param>
|
||||
/// <returns>True if the LStringId was found. Otherwise, false.</returns>
|
||||
public bool TryGet(LStringId id, [NotNullWhen(true)] out LString? localizedString)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _stringInstances.TryGetValue(id, out localizedString);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an IReadOnlyDictionary of all LString instances created through Brutal.Localization.
|
||||
/// Instances of LString created manually (via new()) are not included in here.
|
||||
/// <para />
|
||||
/// <remarks>This is a lightweight call and does not copy the set of strings. However, the returned reference
|
||||
/// is NOT thread-safe. If the underlying collection is modified (e.g., with calls to Create methods of <see cref="LStrings" />) then the underlying collection
|
||||
/// will be modified and will generate errors if you are iterating the collection at the time.</remarks>
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<LStringId, LString> LStringInstances =>
|
||||
_stringInstances.AsReadOnly();
|
||||
|
||||
#region Private
|
||||
private bool HasStringProvider => _lStringProvider is not null;
|
||||
|
||||
private GetLocalizedStringDelegate? _lStringProvider;
|
||||
private readonly Dictionary<LStringId, LString> _stringInstances;
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Regex _replacementPattern;
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
namespace Brutal.Localization.ResX
|
||||
{
|
||||
/// <summary>
|
||||
/// Thrown when the root tag of the ResX file is not <root>.
|
||||
/// </summary>
|
||||
public class ResXBadRootTagException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
|
||||
/// </summary>
|
||||
public ResXBadRootTagException() { }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Exception message</param>
|
||||
public ResXBadRootTagException(string message)
|
||||
: base(message) { }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Exception messsage</param>
|
||||
/// <param name="innerException">Inner exception (if any.)</param>
|
||||
public ResXBadRootTagException(string message, Exception innerException)
|
||||
: base(message, innerException) { }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Brutal.Localization.ResX
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts ResX files to other formats.
|
||||
/// </summary>
|
||||
public static class ResXConvert
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_indentedWriter = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
};
|
||||
private static readonly JsonWriterOptions s_unsafeEncoder = new()
|
||||
{
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
private static readonly JsonWriterOptions s_defaultEncoder = new()
|
||||
{
|
||||
Encoder = JavaScriptEncoder.Default,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Converts the ResX file to JSON.
|
||||
/// </summary>
|
||||
/// <param name="resx">Input ResX file.</param>
|
||||
/// <param name="unsafeEncoder">Set to true if ResX file may contain characters other than English.</param>
|
||||
/// <param name="prettify">Set to true if you don't want the output JSON file to be minified.</param>
|
||||
/// <returns>JSON representation of the ResX file.</returns>
|
||||
public static string ToJson(ResXFile resx, bool unsafeEncoder = true, bool prettify = false)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using var writer = new Utf8JsonWriter(
|
||||
stream,
|
||||
unsafeEncoder ? s_unsafeEncoder : s_defaultEncoder
|
||||
);
|
||||
|
||||
writer.WriteStartArray();
|
||||
|
||||
foreach (var data in resx.DataDictionary.Values)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
|
||||
writer.WriteString("name"u8, data.Name);
|
||||
writer.WriteString("value"u8, data.Value);
|
||||
writer.WriteString("comment"u8, data.Comment);
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
writer.Flush();
|
||||
return JsonPrettify(Encoding.UTF8.GetString(stream.ToArray()), prettify);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the ResX file to JSON, asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="resx">Input ResX file.</param>
|
||||
/// <param name="unsafeEncoder">Set to true if ResX file may contain characters other than English.</param>
|
||||
/// <param name="prettify">Set to true if you don't want the output JSON file to be minified.</param>
|
||||
/// <returns>JSON representation of the ResX file.</returns>
|
||||
public static async Task<string> ToJsonAsync(
|
||||
ResXFile resx,
|
||||
bool unsafeEncoder = true,
|
||||
bool prettify = false
|
||||
)
|
||||
{
|
||||
await using var stream = new MemoryStream();
|
||||
await using var writer = new Utf8JsonWriter(
|
||||
stream,
|
||||
unsafeEncoder ? s_unsafeEncoder : s_defaultEncoder
|
||||
);
|
||||
|
||||
writer.WriteStartArray();
|
||||
|
||||
foreach (var data in resx.DataDictionary.Values)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
|
||||
writer.WriteString("name"u8, data.Name);
|
||||
writer.WriteString("value"u8, data.Value);
|
||||
writer.WriteString("comment"u8, data.Comment);
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
await writer.FlushAsync();
|
||||
return JsonPrettify(Encoding.UTF8.GetString(stream.ToArray()), prettify);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the ResX file to Markdown.
|
||||
/// </summary>
|
||||
/// <param name="resx">Input ResX file.</param>
|
||||
/// <returns>A Markdown representation of the ResX document.</returns>
|
||||
public static string ToMarkdown(ResXFile resx)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("# Converted result from a ResX file");
|
||||
builder.AppendLine("*Auto-generated by ResXNET v1.0.0*");
|
||||
|
||||
foreach (var data in resx.DataDictionary.Values)
|
||||
{
|
||||
builder.AppendLine($"### {data.Name}");
|
||||
builder.AppendLine(
|
||||
$"*Value*: **{data.Value}**; *comment*: **{data.Comment ?? "null"}**"
|
||||
);
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the ResX file to C#.
|
||||
/// </summary>
|
||||
/// <param name="resx">Input ResX file to process.</param>
|
||||
/// <returns>C# representation of all data fields of the ResX file.</returns>
|
||||
public static string ToCSharp(ResXFile resx)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("internal class Class1");
|
||||
builder.AppendLine("{");
|
||||
foreach (var data in resx.DataDictionary.Values)
|
||||
{
|
||||
if (data.Comment != null)
|
||||
{
|
||||
builder.AppendLine(" /// <summary>");
|
||||
builder.AppendLine($" /// {data.Comment}");
|
||||
builder.AppendLine(" /// </summary>");
|
||||
}
|
||||
string name = new(
|
||||
Capitalize(data.Name)
|
||||
.Where(ch =>
|
||||
(
|
||||
!char.IsWhiteSpace(ch)
|
||||
&& !char.IsPunctuation(ch)
|
||||
&& !char.IsControl(ch)
|
||||
)
|
||||
|| ch == '_'
|
||||
)
|
||||
.ToArray()
|
||||
);
|
||||
|
||||
builder.AppendLine($" public string {Capitalize(name)} = \"{data.Value}\";");
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
// source:
|
||||
// https://stackoverflow.com/a/4405876/21072788
|
||||
// CC BY-SA 4.0
|
||||
private static string Capitalize(this string input) =>
|
||||
input switch
|
||||
{
|
||||
null => throw new ArgumentNullException(nameof(input)),
|
||||
"" => throw new ArgumentException(
|
||||
$"{nameof(input)} cannot be empty",
|
||||
nameof(input)
|
||||
),
|
||||
_ => string.Concat(input[0].ToString().ToUpper(), input.AsSpan(1)),
|
||||
};
|
||||
|
||||
// source: https://stackoverflow.com/a/67928315/21072788
|
||||
// CC BY-SA 4.0
|
||||
private static string JsonPrettify(this string json, bool reallyPrettify = true)
|
||||
{
|
||||
if (!reallyPrettify)
|
||||
{
|
||||
return json;
|
||||
}
|
||||
|
||||
using var jDoc = JsonDocument.Parse(json);
|
||||
return JsonSerializer.Serialize(jDoc, s_indentedWriter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
namespace Brutal.Localization.ResX;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single <data> tag in a text ResX file.
|
||||
/// </summary>
|
||||
/// <param name="Name">Name of the data.</param>
|
||||
/// <param name="Value">Value of the data.</param>
|
||||
/// <param name="Comment">Optional comment to go along with the data.</param>
|
||||
public record ResXData(string Name, string Value, string? Comment);
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
// NOTE: RootHeader is a multi-line verbatim literal, so its compiled value embeds the
|
||||
// source file's line endings. It must stay LF to match the public API baseline -
|
||||
// enforced by .gitattributes (*.cs text eol=lf).
|
||||
namespace Brutal.Localization.ResX
|
||||
{
|
||||
public partial class ResXFile
|
||||
{
|
||||
/// <summary>
|
||||
/// The header of the <root> tag.
|
||||
/// </summary>
|
||||
public const string RootHeader =
|
||||
@"<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name=""resmimetype"">text/microsoft-resx</resheader>
|
||||
<resheader name=""version"">2.0</resheader>
|
||||
<resheader name=""reader"">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name=""writer"">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name=""Name1""><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name=""Color1"" type=""System.Drawing.Color, System.Drawing"">Blue</data>
|
||||
<data name=""Bitmap1"" mimetype=""application/x-microsoft.net.object.binary.base64"">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name=""Icon1"" type=""System.Drawing.Icon, System.Drawing"" mimetype=""application/x-microsoft.net.object.bytearray.base64"">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of ""resheader"" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
|
||||
<xsd:import namespace=""http://www.w3.org/XML/1998/namespace"" />
|
||||
<xsd:element name=""root"" msdata:IsDataSet=""true"">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs=""unbounded"">
|
||||
<xsd:element name=""metadata"">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name=""name"" use=""required"" type=""xsd:string"" />
|
||||
<xsd:attribute name=""type"" type=""xsd:string"" />
|
||||
<xsd:attribute name=""mimetype"" type=""xsd:string"" />
|
||||
<xsd:attribute ref=""xml:space"" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name=""assembly"">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name=""alias"" type=""xsd:string"" />
|
||||
<xsd:attribute name=""name"" type=""xsd:string"" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name=""data"">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
|
||||
<xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name=""name"" type=""xsd:string"" use=""required"" msdata:Ordinal=""1"" />
|
||||
<xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" />
|
||||
<xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" />
|
||||
<xsd:attribute ref=""xml:space"" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name=""resheader"">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name=""name"" type=""xsd:string"" use=""required"" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name=""resmimetype"">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name=""version"">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name=""reader"">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name=""writer"">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,184 @@
|
|||
using System.Text;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Brutal.Localization.ResX
|
||||
{
|
||||
// The ResX reading and writing code is taken from a github project. It should be thought of as
|
||||
// a temporary solution to reading and writing ResX files that support strings only.
|
||||
// https://github.com/winscripter/resx-net
|
||||
// The source code is under the MIT License. See the file ResX.Net.LICENSE under the Resources.ResX.NET folder.
|
||||
|
||||
/// <summary>
|
||||
/// Parses and builds a ResX file. This class cannot be inherited.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The code for ResX reading and writing is provided by github project https://github.com/winscripter/resx-net under
|
||||
/// the following license.
|
||||
///
|
||||
/// MIT License
|
||||
///
|
||||
/// Copyright (c) 2024 winscripter
|
||||
///
|
||||
/// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
/// of this software and associated documentation files (the "Software"), to deal
|
||||
/// in the Software without restriction, including without limitation the rights
|
||||
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
/// copies of the Software, and to permit persons to whom the Software is
|
||||
/// furnished to do so, subject to the following conditions:
|
||||
///
|
||||
/// The above copyright notice and this permission notice shall be included in all
|
||||
/// copies or substantial portions of the Software.
|
||||
///
|
||||
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
/// SOFTWARE.
|
||||
/// </remarks>
|
||||
public sealed partial class ResXFile
|
||||
{
|
||||
/// <summary>
|
||||
/// A list of descendant ResX data tags.
|
||||
/// </summary>
|
||||
/// inside an IResourceWriter etc.
|
||||
public Dictionary<string, ResXData> DataDictionary { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Create a ResXFile instance and populate it with data from an IEnumerable.
|
||||
/// </summary>
|
||||
/// <param name="dataList">IEnumerable<<see cref="ResXData"/>> to populate with.</param>
|
||||
public ResXFile(IEnumerable<ResXData> dataList)
|
||||
{
|
||||
DataDictionary = dataList.ToDictionary<ResXData, string>(item => item.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a ResXFile instance and populate it with data from Dictionary.
|
||||
/// </summary>
|
||||
/// <param name="dataList">Dictionary<string, <see cref="ResXData"/>> to populate with.</param>
|
||||
public ResXFile(Dictionary<string, ResXData> dataList)
|
||||
{
|
||||
DataDictionary = dataList;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXFile"/> class.
|
||||
/// </summary>
|
||||
public ResXFile()
|
||||
: this(new List<ResXData>()) { }
|
||||
|
||||
/// <summary>
|
||||
/// Builds a ResX formatted string from the contents of the <see cref="ResXFile"/>.
|
||||
/// </summary>
|
||||
/// <returns>string content of ResX.</returns>
|
||||
public string Build()
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
|
||||
builder.AppendLine("<root>");
|
||||
|
||||
builder.AppendLine(
|
||||
string.Join(
|
||||
"\r\n",
|
||||
RootHeader
|
||||
.Split(["\r\n"], StringSplitOptions.None)
|
||||
.Select(line =>
|
||||
{
|
||||
var nestedBuilder = new StringBuilder();
|
||||
nestedBuilder.Append(" ");
|
||||
nestedBuilder.Append(line);
|
||||
return nestedBuilder.ToString();
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
foreach (var data in DataDictionary.Values)
|
||||
{
|
||||
var dataElement = new XElement(
|
||||
"data",
|
||||
new XAttribute("name", data.Name),
|
||||
new XAttribute(XNamespace.Xml + "space", "preserve"),
|
||||
new XElement("value", data.Value)
|
||||
);
|
||||
if (data.Comment is not null)
|
||||
{
|
||||
dataElement.Add(new XElement("comment", data.Comment));
|
||||
}
|
||||
|
||||
builder.AppendLine(dataElement.ToString());
|
||||
}
|
||||
|
||||
builder.AppendLine("</root>");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the raw plain text of the ResX file into an enumerable of
|
||||
/// <see cref="ResXData"/>.
|
||||
/// </summary>
|
||||
/// <param name="rawText">Input plain text of the ResX file.</param>
|
||||
/// <returns>An enumerable of <see cref="ResXData"/>.</returns>
|
||||
/// <exception cref="XmlException">In this method, thrown when the root tag is missing.</exception>
|
||||
/// <exception cref="ResXBadRootTagException">In this method, thrown when the root tag name is not "root".</exception>
|
||||
/// <exception cref="ResXNoAttributeException">In this method, thrown when the data tag does not have the required attribute.</exception>
|
||||
/// <exception cref="ResXNoValueException">In this method, thrown when the data tag does not have a child <value> tag.</exception>
|
||||
public static Dictionary<string, ResXData> Parse(string rawText)
|
||||
{
|
||||
var rootTag =
|
||||
XDocument.Parse(rawText).Root ?? throw new XmlException("Root tag is missing");
|
||||
if (!rootTag.Name.LocalName.Equals("root", StringComparison.CurrentCultureIgnoreCase))
|
||||
{
|
||||
throw new ResXBadRootTagException(
|
||||
$"Root tag of the ResX file is \"{rootTag.Name.LocalName}\", but expected \"root\""
|
||||
);
|
||||
}
|
||||
|
||||
var resxData = new Dictionary<string, ResXData>();
|
||||
foreach (var descendant in rootTag.Elements())
|
||||
{
|
||||
if (
|
||||
!descendant.Name.LocalName.Equals(
|
||||
"data",
|
||||
StringComparison.CurrentCultureIgnoreCase
|
||||
)
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var nameAttribute =
|
||||
descendant.Attribute("name")?.Value
|
||||
?? throw new ResXNoAttributeException("No attribute named \"name\"");
|
||||
var value =
|
||||
descendant
|
||||
.Descendants()
|
||||
.FirstOrDefault(tag =>
|
||||
tag.Name.LocalName.Equals(
|
||||
"value",
|
||||
StringComparison.CurrentCultureIgnoreCase
|
||||
)
|
||||
)
|
||||
?.Value
|
||||
?? throw new ResXNoValueException(
|
||||
"Data does not have descendant element of type \"value\""
|
||||
);
|
||||
var comment = descendant
|
||||
.Descendants()
|
||||
.FirstOrDefault(tag =>
|
||||
tag.Name.LocalName.Equals(
|
||||
"comment",
|
||||
StringComparison.CurrentCultureIgnoreCase
|
||||
)
|
||||
)
|
||||
?.Value;
|
||||
|
||||
resxData.Add(nameAttribute, new ResXData(nameAttribute, value, comment));
|
||||
}
|
||||
|
||||
return resxData;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
namespace Brutal.Localization.ResX
|
||||
{
|
||||
/// <summary>
|
||||
/// Thrown when a ResX <data> tag has no crucial attribute.
|
||||
/// </summary>
|
||||
public class ResXNoAttributeException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
|
||||
/// </summary>
|
||||
public ResXNoAttributeException() { }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Exception message.</param>
|
||||
public ResXNoAttributeException(string? message)
|
||||
: base(message) { }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Exception message.</param>
|
||||
/// <param name="innerException">Inner exception (if any.)</param>
|
||||
public ResXNoAttributeException(string? message, Exception? innerException)
|
||||
: base(message, innerException) { }
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue