Skip to content

Commit fdfd4c4

Browse files
authored
Use uint.TryFormat to fix TODO in IPAddressParser (#117300)
1 parent 541c68e commit fdfd4c4

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ static int FormatByte(uint number, Span<TChar> addressString)
194194
internal static int FormatIPv6Address<TChar>(ushort[] address, uint scopeId, Span<TChar> destination)
195195
where TChar : unmanaged, IBinaryInteger<TChar>
196196
{
197+
Debug.Assert(typeof(TChar) == typeof(byte) || typeof(TChar) == typeof(char));
197198
int pos = 0;
198199

199200
if (IPv6AddressHelper.ShouldHaveIpv4Embedded(address))
@@ -220,18 +221,13 @@ internal static int FormatIPv6Address<TChar>(ushort[] address, uint scopeId, Spa
220221
{
221222
destination[pos++] = TChar.CreateTruncating('%');
222223

223-
// TODO https://github.com/dotnet/runtime/issues/84527: Use UInt32 TryFormat for both char and byte once IUtf8SpanFormattable implementation exists
224-
Span<TChar> chars = stackalloc TChar[10];
225-
int bytesPos = 10;
226-
do
227-
{
228-
(scopeId, uint digit) = Math.DivRem(scopeId, 10);
229-
chars[--bytesPos] = TChar.CreateTruncating('0' + digit);
230-
}
231-
while (scopeId != 0);
232-
Span<TChar> used = chars.Slice(bytesPos);
233-
used.CopyTo(destination.Slice(pos));
234-
pos += used.Length;
224+
int bytesWritten;
225+
bool formatted = typeof(TChar) == typeof(byte) ?
226+
scopeId.TryFormat(MemoryMarshal.Cast<TChar, byte>(destination).Slice(pos), out bytesWritten) :
227+
scopeId.TryFormat(MemoryMarshal.Cast<TChar, char>(destination).Slice(pos), out bytesWritten);
228+
229+
Debug.Assert(formatted);
230+
pos += bytesWritten;
235231
}
236232

237233
return pos;

0 commit comments

Comments
 (0)