Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sanitize text pasted into hex text boxes #3684

Merged
merged 9 commits into from
Jun 3, 2024
2 changes: 1 addition & 1 deletion src/BizHawk.Client.EmuHawk/CustomControls/HexTextBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ protected override void OnPaste(PasteEventArgs e)
{
if (e.ContainsText)
{
string text = e.Text.Trim().RemovePrefix("0x").RemovePrefix('$');
string text = e.Text.CleanHex();
if (text.IsHex())
{
PasteWithMaxLength(text);
Expand Down
2 changes: 1 addition & 1 deletion src/BizHawk.Client.EmuHawk/tools/Watch/WatchValueBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ protected override void OnPaste(PasteEventArgs e)
{
if (Type == WatchDisplayType.Hex && e.ContainsText)
{
string text = e.Text.Trim().RemovePrefix("0x").RemovePrefix('$');
string text = e.Text.CleanHex();
if (text.IsHex())
{
PasteWithMaxLength(text);
Expand Down
6 changes: 6 additions & 0 deletions src/BizHawk.Common/Extensions/NumericStringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

namespace BizHawk.Common.StringExtensions
{
Expand Down Expand Up @@ -33,6 +34,11 @@ public static class NumericStringExtensions
/// </returns>
public static string OnlyHex(this string? raw) => string.IsNullOrWhiteSpace(raw) ? string.Empty : string.Concat(raw.Where(IsHex)).ToUpperInvariant();

/// <returns>
/// A copy of <paramref name="raw"/> after removing <c>0x</c>/<c>$</c> prefixes and all whitespace.
/// </returns>
public static string CleanHex(this string? raw) => raw is null ? string.Empty : Regex.Replace(raw, @"^\s*(0x|\$)|\s+?", "");
YoshiRulz marked this conversation as resolved.
Show resolved Hide resolved

#if NET7_0_OR_GREATER
public static ushort ParseU16FromHex(ReadOnlySpan<char> str)
=> ushort.Parse(str, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
Expand Down