diff --git a/tracer/src/Datadog.Trace/Agent/StatsAggregator.cs b/tracer/src/Datadog.Trace/Agent/StatsAggregator.cs index 58d59fa53acf..17fc7574a3f0 100644 --- a/tracer/src/Datadog.Trace/Agent/StatsAggregator.cs +++ b/tracer/src/Datadog.Trace/Agent/StatsAggregator.cs @@ -365,9 +365,7 @@ internal StatsAggregationKey BuildKey(Span span, List peerTagKeys, o /// The is a pre-encoded UTF-8 byte array (e.g. "tagKey:") and is /// hashed directly. Only the needs UTF-8 encoding at call time. /// -#if NETCOREAPP - [System.Runtime.CompilerServices.SkipLocalsInit] -#endif + [SkipLocalsInit] private static ulong HashTag(byte[] keyPrefix, string tagValue, FnvHash64.Version version, ulong? initialHash = null) { // Hash the pre-encoded key prefix (e.g. "peer.service:") directly — no encoding needed @@ -377,22 +375,35 @@ private static ulong HashTag(byte[] keyPrefix, string tagValue, FnvHash64.Versio // Now encode and hash just the tag value var maxByteCount = EncodingHelpers.Utf8NoBom.GetMaxByteCount(tagValue.Length); -#if NETCOREAPP const int maxStackLimit = 256; if (maxByteCount <= maxStackLimit) { Span buffer = stackalloc byte[maxStackLimit]; - var written = EncodingHelpers.Utf8NoBom.GetBytes(tagValue, buffer); + int written; +#if NETCOREAPP + written = EncodingHelpers.Utf8NoBom.GetBytes(tagValue, buffer); +#else + unsafe + { + var tagValueSpan = tagValue.AsSpan(); + fixed (char* tagValuePointer = tagValueSpan) + { + fixed (byte* bufferPointer = buffer) + { + written = EncodingHelpers.Utf8NoBom.GetBytes(tagValuePointer, tagValueSpan.Length, bufferPointer, buffer.Length); + } + } + } +#endif return FnvHash64.GenerateHash(buffer.Slice(0, written), version, hash); } -#endif var rented = ArrayPool.Shared.Rent(maxByteCount); try { var written = EncodingHelpers.Utf8NoBom.GetBytes(tagValue, charIndex: 0, charCount: tagValue.Length, rented, byteIndex: 0); - return FnvHash64.GenerateHash(rented, 0, written, version, hash); + return FnvHash64.GenerateHash(rented.AsSpan().Slice(0, written), version, hash); } finally { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/AWS/Shared/SpanPointers.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/AWS/Shared/SpanPointers.cs index ec5703063d65..b8f4ceb38f71 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/AWS/Shared/SpanPointers.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/AWS/Shared/SpanPointers.cs @@ -13,12 +13,6 @@ using Datadog.Trace.ClrProfiler.AutoInstrumentation.AWS.DynamoDb; using Datadog.Trace.Util; -#if NETCOREAPP3_1_OR_GREATER -using System.Buffers; -#else -using Datadog.Trace.VendoredMicrosoftCode.System.Buffers; -#endif - namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.AWS.Shared; /// diff --git a/tracer/src/Datadog.Trace/DataStreamsMonitoring/Hashes/HashHelper.cs b/tracer/src/Datadog.Trace/DataStreamsMonitoring/Hashes/HashHelper.cs index 7b5af8116ef1..7869b46ee002 100644 --- a/tracer/src/Datadog.Trace/DataStreamsMonitoring/Hashes/HashHelper.cs +++ b/tracer/src/Datadog.Trace/DataStreamsMonitoring/Hashes/HashHelper.cs @@ -61,24 +61,12 @@ public static NodeHash CalculateNodeHash(in NodeHashBase baseNodeHash, IEnumerab return new NodeHash(hash); } -#if NETCOREAPP3_1_OR_GREATER [System.Runtime.CompilerServices.SkipLocalsInit] -#endif public static PathwayHash CalculatePathwayHash(NodeHash nodeHash, PathwayHash parentHash) { -#if NETCOREAPP3_1_OR_GREATER Span bytes = stackalloc byte[16]; - System.Buffers.Binary.BinaryPrimitives.WriteUInt64LittleEndian(bytes, nodeHash.Value); - System.Buffers.Binary.BinaryPrimitives.WriteUInt64LittleEndian(bytes.Slice(8), parentHash.Value); + BinaryPrimitives.WriteUInt64LittleEndian(bytes, nodeHash.Value); + BinaryPrimitives.WriteUInt64LittleEndian(bytes.Slice(8), parentHash.Value); return new PathwayHash(FnvHash64.GenerateHash(bytes, HashVersion)); -#else - // annoyingly allocate-y, but meh - var bytes = new byte[8]; - BinaryPrimitivesHelper.WriteUInt64LittleEndian(bytes, nodeHash.Value); - var hash = FnvHash64.GenerateHash(bytes, HashVersion); - - BinaryPrimitivesHelper.WriteUInt64LittleEndian(bytes, parentHash.Value); - return new PathwayHash(FnvHash64.GenerateHash(bytes, HashVersion, hash)); -#endif } } diff --git a/tracer/src/Datadog.Trace/DataStreamsMonitoring/VarEncodingHelper.cs b/tracer/src/Datadog.Trace/DataStreamsMonitoring/VarEncodingHelper.cs index c446a83de233..4b8b1481fd6d 100644 --- a/tracer/src/Datadog.Trace/DataStreamsMonitoring/VarEncodingHelper.cs +++ b/tracer/src/Datadog.Trace/DataStreamsMonitoring/VarEncodingHelper.cs @@ -70,7 +70,6 @@ public static int WriteVarLong(byte[] bytes, int offset, ulong value) public static int WriteVarLong(BinaryWriter writer, ulong value) => WriteVarLong(value, new BinaryWriterByteWriter(writer)); -#if NETCOREAPP3_1_OR_GREATER /// /// Serializes 64-bit unsigned integers 7 bits at a time, /// starting with the least significant bits. The most significant bit in each @@ -95,7 +94,6 @@ public static int WriteVarLong(Span bytes, ulong value) bytes[length - 1] = (byte)(value); return length; } -#endif /// /// Serializes 64-bit signed integers using zig-zag encoding, @@ -122,7 +120,6 @@ public static int WriteVarLongZigZag(byte[] bytes, int offset, long value) public static int WriteVarLongZigZag(BinaryWriter writer, long value) => WriteVarLong(writer, ZigZag(value)); -#if NETCOREAPP3_1_OR_GREATER /// /// Serializes 64-bit signed integers using zig-zag encoding, /// which ensures small-scale integers are turned into unsigned integers @@ -134,7 +131,6 @@ public static int WriteVarLongZigZag(BinaryWriter writer, long value) /// The number of bytes written public static int WriteVarLongZigZag(Span bytes, long value) => WriteVarLong(bytes, ZigZag(value)); -#endif /// /// Serializes 32-bit unsigned integers 7 bits at a time, @@ -165,7 +161,6 @@ public static int WriteVarInt(byte[] bytes, int offset, uint value) public static int WriteVarInt(BinaryWriter writer, uint value) => WriteVarLong(value, new BinaryWriterByteWriter(writer)); -#if NETCOREAPP3_1_OR_GREATER /// /// Serializes 32-bit unsigned integers 7 bits at a time, /// starting with the least significant bits. The most significant bit in each @@ -179,7 +174,6 @@ public static int WriteVarInt(BinaryWriter writer, uint value) /// The number of bytes written public static int WriteVarInt(Span bytes, uint value) => WriteVarLong(bytes, value); -#endif /// /// Serializes 32-bit signed integers using zig-zag encoding, @@ -206,7 +200,6 @@ public static int WriteVarIntZigZag(byte[] bytes, int offset, int value) public static int WriteVarIntZigZag(BinaryWriter writer, int value) => WriteVarLongZigZag(writer, value); -#if NETCOREAPP3_1_OR_GREATER /// /// Serializes 32-bit signed integers using zig-zag encoding, /// which ensures small-scale integers are turned into unsigned integers @@ -218,7 +211,6 @@ public static int WriteVarIntZigZag(BinaryWriter writer, int value) /// The number of bytes written public static int WriteVarIntZigZag(Span bytes, int value) => WriteVarLongZigZag(bytes, value); -#endif /// /// Deserializes 64-bit unsigned integers that have been encoded using @@ -252,7 +244,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) return null; } -#if NETCOREAPP3_1_OR_GREATER /// /// Deserializes 64-bit unsigned integers that have been encoded using /// @@ -284,7 +275,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) bytesRead = default; return null; } -#endif /// /// Deserializes 64-bit unsigned integers that have been encoded using @@ -297,7 +287,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) public static long? ReadVarLongZigZag(byte[] bytes, int offset, out int bytesRead) => ReadVarLong(bytes, offset, out bytesRead) is { } decoded ? UnZigZag(decoded) : null; -#if NETCOREAPP3_1_OR_GREATER /// /// Deserializes 64-bit unsigned integers that have been encoded using /// @@ -307,7 +296,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) /// The decoded value, or null if decoding failed public static long? ReadVarLongZigZag(Span bytes, out int bytesRead) => ReadVarLong(bytes, out bytesRead) is { } decoded ? UnZigZag(decoded) : null; -#endif /// /// Deserializes 32-bit unsigned integers that have been encoded using @@ -322,7 +310,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) ? (uint)decoded : null; -#if NETCOREAPP3_1_OR_GREATER /// /// Deserializes 64-bit unsigned integers that have been encoded using /// @@ -334,7 +321,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) => ReadVarLong(bytes, out bytesRead) is { } decoded and <= int.MaxValue ? (uint)decoded : null; -#endif /// /// Deserializes 64-bit unsigned integers that have been encoded using @@ -349,7 +335,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) ? (int)decoded : null; -#if NETCOREAPP3_1_OR_GREATER /// /// Deserializes 64-bit unsigned integers that have been encoded using /// @@ -361,7 +346,6 @@ public static int WriteVarIntZigZag(Span bytes, int value) => ReadVarLongZigZag(bytes, out bytesRead) is { } decoded and >= int.MinValue and <= int.MaxValue ? (int)decoded : null; -#endif /// /// Returns the number of bytes that encodes a value into. diff --git a/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs b/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs index e99623859037..fca4ac09ecb6 100644 --- a/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs +++ b/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs @@ -32,11 +32,7 @@ public static string ToUUID(this string input) // note that we _could_ get a UUID from these bytes by trivially doing // new Guid(bytes).ToString("d") but that uses a slightly different // layout of the bytes, which would cause a different UUID to be generated -#if NETCOREAPP Span chars = stackalloc char[36]; -#else - var chars = new char[36]; -#endif var targetIndex = 0; for (var sourceIndex = 0; sourceIndex < 16; sourceIndex++) @@ -51,7 +47,11 @@ public static string ToUUID(this string input) chars[targetIndex++] = Hex[sourceByte & 0xF]; } +#if NETCOREAPP return new string(chars); +#else + return chars.ToString(); +#endif } } } diff --git a/tracer/src/Datadog.Trace/DiagnosticListeners/AspNetCoreResourceNameHelper.cs b/tracer/src/Datadog.Trace/DiagnosticListeners/AspNetCoreResourceNameHelper.cs index 8c82c77d3ecd..5c818e600a28 100644 --- a/tracer/src/Datadog.Trace/DiagnosticListeners/AspNetCoreResourceNameHelper.cs +++ b/tracer/src/Datadog.Trace/DiagnosticListeners/AspNetCoreResourceNameHelper.cs @@ -11,7 +11,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using System.Text; using Datadog.Trace.DuckTyping; using Datadog.Trace.SourceGenerators; using Datadog.Trace.Util; @@ -128,14 +127,9 @@ internal static string SimplifyRoutePattern( + (string.IsNullOrEmpty(actionName) ? 0 : Math.Max(actionName!.Length - 6, 0)) // "action".Length + 1; // '/' prefix -#if NETCOREAPP var sb = maxSize < 512 ? new ValueStringBuilder(stackalloc char[512]) : new ValueStringBuilder(); // too big to use stackallocation, so use array builder -#else - // In .NET Core 2.1, the ValueStringBuilder doesn't actually improve anything - var sb = StringBuilderCache.Acquire(maxSize); -#endif foreach (var pathSegment in routePattern.PathSegments) { @@ -227,7 +221,6 @@ internal static string SimplifyRoutePattern( } } -#if NETCOREAPP if (sb.Length <= 1) { sb.Dispose(); @@ -235,15 +228,6 @@ internal static string SimplifyRoutePattern( } return sb.ToString(); -#else - if (sb.Length <= 1) - { - StringBuilderCache.Release(sb); - return "/"; - } - - return StringBuilderCache.GetStringAndRelease(sb).ToLowerInvariant(); -#endif } internal static string SimplifyRouteTemplate( @@ -261,14 +245,9 @@ internal static string SimplifyRouteTemplate( + (string.IsNullOrEmpty(actionName) ? 0 : Math.Max(actionName!.Length - 6, 0)) // "action".Length + 1; // '/' prefix -#if NETCOREAPP var sb = maxSize < 512 ? new ValueStringBuilder(stackalloc char[512]) : new ValueStringBuilder(); // too big to use stackallocation, so use array builder -#else - // In .NET Core 2.1, the ValueStringBuilder doesn't actually improve anything - var sb = StringBuilderCache.Acquire(maxSize); -#endif // Remove the boxing of the enumerator // In all versions of .NET, this is implemented as a List @@ -367,7 +346,6 @@ internal static string SimplifyRouteTemplate( } // We never added anything, or we just added the first `/`, no need for explicit ToString() -#if NETCOREAPP if (sb.Length <= 1) { sb.Dispose(); @@ -375,15 +353,6 @@ internal static string SimplifyRouteTemplate( } return sb.ToString(); -#else - if (sb.Length <= 1) - { - StringBuilderCache.Release(sb); - return "/"; - } - - return StringBuilderCache.GetStringAndRelease(sb).ToLowerInvariant(); -#endif } [TestingAndPrivateOnly] @@ -412,10 +381,5 @@ internal static bool IsIdentifierSegment(object? value, out string? valueAsStrin return UriHelpers.IsIdentifierSegment(valueAsString, 0, valueAsString.Length); } - -#if !NETCOREAPP - // .NET Core 2.1 helper which doesn't _actually_ append as lower invariant, and just does it all at the end instead - private static void AppendAsLowerInvariant(this StringBuilder sb, string? value) => sb.Append(value); -#endif } #endif diff --git a/tracer/src/Datadog.Trace/Propagators/B3SingleHeaderContextPropagator.cs b/tracer/src/Datadog.Trace/Propagators/B3SingleHeaderContextPropagator.cs index 1c05b531c3e2..e3d47c85716e 100644 --- a/tracer/src/Datadog.Trace/Propagators/B3SingleHeaderContextPropagator.cs +++ b/tracer/src/Datadog.Trace/Propagators/B3SingleHeaderContextPropagator.cs @@ -62,7 +62,6 @@ public bool TryExtract(TCarrier carrier, TCarrierGette return false; } -#if NETCOREAPP ReadOnlySpan rawTraceId; ReadOnlySpan rawSpanId; char rawSampled; @@ -100,45 +99,6 @@ public bool TryExtract(TCarrier carrier, TCarrierGette var samplingPriority = rawSampled == '1' ? 1 : 0; var spanContext = new SpanContext(traceId, parentId, samplingPriority, serviceName: null, null, rawTraceId.ToString(), rawSpanId.ToString(), isRemote: true); -#else - string? rawTraceId; - string? rawSpanId; - char rawSampled; - - if (brValue.Length > 50 && brValue[32] == '-' && brValue[49] == '-') - { - // 128-bit trace id - rawTraceId = brValue.Substring(0, 32); - rawSpanId = brValue.Substring(33, 16); - rawSampled = brValue[50]; - } - else if (brValue.Length > 34 && brValue[16] == '-' && brValue[33] == '-') - { - // 64-bit trace id - rawTraceId = brValue.Substring(0, 16); - rawSpanId = brValue.Substring(17, 16); - rawSampled = brValue[34]; - } - else - { - return false; - } - - var success = HexString.TryParseTraceId(rawTraceId, out var traceId); - - if (!success || traceId == TraceId.Zero) - { - return false; - } - - if (!HexString.TryParseUInt64(rawSpanId, out var parentId)) - { - parentId = 0; - } - - var samplingPriority = rawSampled == '1' ? 1 : 0; - var spanContext = new SpanContext(traceId, parentId, samplingPriority, serviceName: null, null, rawTraceId, rawSpanId, isRemote: true); -#endif context = new PropagationContext(spanContext, baggage: null); diff --git a/tracer/src/Datadog.Trace/Propagators/W3CBaggagePropagator.cs b/tracer/src/Datadog.Trace/Propagators/W3CBaggagePropagator.cs index db5cfa57b187..dfcd704d5318 100644 --- a/tracer/src/Datadog.Trace/Propagators/W3CBaggagePropagator.cs +++ b/tracer/src/Datadog.Trace/Propagators/W3CBaggagePropagator.cs @@ -151,13 +151,7 @@ private static void EncodeStringAndAppendSlow(StringBuilder sb, string source, b private static void EncodeBytesAndAppend(StringBuilder sb, ReadOnlySpan bytes, bool isKey) { - // allocate a buffer on the stack (or rent one) for hexadecimal strings -#if NETCOREAPP3_1_OR_GREATER Span hexStringBuffer = stackalloc char[2]; -#else - var buffer = ArrayPool.Shared.Rent(minimumLength: 2); - var hexStringBuffer = buffer.AsSpan(start: 0, length: 2); -#endif for (var index = 0; index < bytes.Length; index++) { @@ -177,10 +171,6 @@ private static void EncodeBytesAndAppend(StringBuilder sb, ReadOnlySpan by sb.Append(c); } } - -#if !NETCOREAPP3_1_OR_GREATER - ArrayPool.Shared.Return(buffer); -#endif } private static bool CharRequiresEncoding(char c, bool isKey) diff --git a/tracer/src/Datadog.Trace/Util/FnvHash64.cs b/tracer/src/Datadog.Trace/Util/FnvHash64.cs index 51800c432b82..e3a75b4a801f 100644 --- a/tracer/src/Datadog.Trace/Util/FnvHash64.cs +++ b/tracer/src/Datadog.Trace/Util/FnvHash64.cs @@ -90,7 +90,7 @@ public static ulong GenerateHash(string data, Version version, ulong initialHash /// /// The 64-bit FNV hash of the data, as a ulong public static ulong GenerateHash(byte[] data, Version version) - => GenerateHash(data, 0, data.Length, version, OffsetBasis); + => GenerateHash(data, version, OffsetBasis); /// /// Generates the 64-bit FNV hash of using hash version . @@ -99,27 +99,10 @@ public static ulong GenerateHash(byte[] data, Version version) /// /// The 64-bit FNV hash of the data, as a ulong public static ulong GenerateHash(byte[] data, Version version, ulong initialHash) - => GenerateHash(data, 0, data.Length, version, initialHash); - - /// - /// Generates the 64-bit FNV hash of a region of using hash version . - /// - /// The 64-bit FNV hash of the data, as a ulong - public static ulong GenerateHash(byte[] data, int offset, int count, Version version) - => GenerateHash(data, offset, count, version, OffsetBasis); - - /// - /// Generates the 64-bit FNV hash of a region of using hash version . - /// Appends the hash to the existing value . Equivalent to concatenating - /// the two data values and subsequently calling GenerateHash. - /// - /// The 64-bit FNV hash of the data, as a ulong - public static ulong GenerateHash(byte[] data, int offset, int count, Version version, ulong initialHash) => version == Version.V1 - ? GenerateV1Hash(data, offset, count, initialHash) - : GenerateV1AHash(data, offset, count, initialHash); + ? GenerateV1Hash(data, initialHash) + : GenerateV1AHash(data, initialHash); -#if NETCOREAPP /// /// Generates the 64-bit FNV hash of using hash version . /// @@ -137,45 +120,13 @@ public static ulong GenerateHash(ReadOnlySpan data, Version version, ulong => version == Version.V1 ? GenerateV1Hash(data, initialHash) : GenerateV1AHash(data, initialHash); -#endif - private static ulong GenerateV1Hash(byte[] bytes, int offset, int count, ulong hash) - { - // for each octet_of_data to be hashed - var max = offset + count; - for (var i = offset; i < max; i++) - { - unchecked - { - // hash = hash * FNV_prime - hash *= FnvPrime; - // hash = hash xor octet_of_data - hash ^= bytes[i]; - } - } + private static ulong GenerateV1Hash(byte[] bytes, ulong hash) + => GenerateV1Hash(bytes.AsSpan(), hash); - return hash; - } + private static ulong GenerateV1AHash(byte[] bytes, ulong hash) + => GenerateV1AHash(bytes.AsSpan(), hash); - private static ulong GenerateV1AHash(byte[] bytes, int offset, int count, ulong hash) - { - // for each octet_of_data to be hashed - var max = offset + count; - for (var i = offset; i < max; i++) - { - unchecked - { - // hash = hash xor octet_of_data - hash ^= bytes[i]; - // hash = hash * FNV_prime - hash *= FnvPrime; - } - } - - return hash; - } - -#if NETCOREAPP private static ulong GenerateV1Hash(ReadOnlySpan bytes, ulong hash) { // for each octet_of_data to be hashed @@ -209,5 +160,4 @@ private static ulong GenerateV1AHash(ReadOnlySpan bytes, ulong hash) return hash; } -#endif } diff --git a/tracer/src/Datadog.Trace/Util/HexConverter.cs b/tracer/src/Datadog.Trace/Util/HexConverter.cs index ab847ba68947..8042c5f4d4be 100644 --- a/tracer/src/Datadog.Trace/Util/HexConverter.cs +++ b/tracer/src/Datadog.Trace/Util/HexConverter.cs @@ -35,13 +35,7 @@ public enum Casing : uint /// /// Gets a map from an ASCII char to its hex value, e.g. arr['b'] == 11. 0xFF means it's not a hex digit. /// -#if NETCOREAPP private static ReadOnlySpan CharToHexLookup => -#else -#pragma warning disable SA1201 // Elements should appear in the correct order - private static readonly byte[] CharToHexLookup = -#pragma warning restore SA1201 // Elements should appear in the correct order -#endif [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 15 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 31 diff --git a/tracer/src/Datadog.Trace/Util/RandomIdGenerator.cs b/tracer/src/Datadog.Trace/Util/RandomIdGenerator.cs index 7cf0e2e16817..2de96779db4b 100644 --- a/tracer/src/Datadog.Trace/Util/RandomIdGenerator.cs +++ b/tracer/src/Datadog.Trace/Util/RandomIdGenerator.cs @@ -27,7 +27,7 @@ using System; using System.Runtime.CompilerServices; -using Datadog.Trace.DataStreamsMonitoring.Utils; +using System.Runtime.InteropServices; namespace Datadog.Trace.Util; @@ -39,13 +39,6 @@ internal sealed class RandomIdGenerator : IRandomIdGenerator [ThreadStatic] private static RandomIdGenerator? _shared; -#if !NETCOREAPP3_1_OR_GREATER - /// - /// Buffer used to avoid allocating a new byte array each time we generate a 128-bit trace id. - /// - private static byte[]? _buffer; -#endif - // in .NET < 6, we implement Xoshiro256** instead of using System.Random, // so we need to keep some state. it is not safe to access from multiple threads, // hence the threadstatic field. @@ -56,39 +49,23 @@ internal sealed class RandomIdGenerator : IRandomIdGenerator public RandomIdGenerator() { -#if NETCOREAPP // don't allocate this inside the loop (CA2014) Span guidSpan = stackalloc Guid[2]; -#endif do { // generate two guids as a source of random bytes for the initial PRNG state. // reinterpret the 32 bytes (16 bytes x 2) as Int64s (8 bytes x 4). -#if NETCOREAPP guidSpan[0] = Guid.NewGuid(); guidSpan[1] = Guid.NewGuid(); - var int64Span = System.Runtime.InteropServices.MemoryMarshal.Cast(guidSpan); + var int64Span = MemoryMarshal.Cast(guidSpan); _s0 = int64Span[0]; _s1 = int64Span[1]; _s2 = int64Span[2]; _s3 = int64Span[3]; -#else - // we can't use `unsafe` pointers in this code because it can be called - // from manual instrumentation which could be running in partial trust. - // if we ever drop support for partial trust, - // we can rewrite this to use `unsafe` instead of allocating these arrays. - var guidBytes1 = Guid.NewGuid().ToByteArray(); - var guidBytes2 = Guid.NewGuid().ToByteArray(); - - _s0 = BitConverter.ToUInt64(guidBytes1, startIndex: 0); - _s1 = BitConverter.ToUInt64(guidBytes1, startIndex: 8); - _s2 = BitConverter.ToUInt64(guidBytes2, startIndex: 0); - _s3 = BitConverter.ToUInt64(guidBytes2, startIndex: 8); -#endif // Guid uses the 4 most significant bits of the first long as the version which would be fixed and not randomized. // and uses 2 other bits in the second long for variants which would be fixed and not randomized too. @@ -103,19 +80,6 @@ public RandomIdGenerator() public static RandomIdGenerator Shared => _shared ??= new RandomIdGenerator(); -#if !NETCOREAPP3_1_OR_GREATER - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte[] GetBuffer(int size) - { - if (_buffer == null || _buffer.Length < size) - { - _buffer = new byte[size]; - } - - return _buffer; - } -#endif - [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong RotateLeft(ulong x, int k) => (x << k) | (x >> (64 - k)); diff --git a/tracer/src/Datadog.Trace/Util/ValueStringBuilder.cs b/tracer/src/Datadog.Trace/Util/ValueStringBuilder.cs index a3cf0136afae..fd7e74b70881 100644 --- a/tracer/src/Datadog.Trace/Util/ValueStringBuilder.cs +++ b/tracer/src/Datadog.Trace/Util/ValueStringBuilder.cs @@ -3,15 +3,12 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // -#if NETCOREAPP - #nullable enable // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -235,6 +232,15 @@ public Span AppendSpan(int length) return _chars.Slice(origPos, length); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AppendAsLowerInvariant(string? value) + { + if (value is not null) + { + AppendAsLowerInvariant(value.AsSpan()); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendAsLowerInvariant(scoped ReadOnlySpan value) { @@ -315,4 +321,3 @@ internal void AppendSpanFormattable(T value, string? format = null, IFormatPr #endif } } -#endif diff --git a/tracer/test/Datadog.Trace.Tests/Util/FnvHash64Tests.cs b/tracer/test/Datadog.Trace.Tests/Util/FnvHash64Tests.cs index 6df352e925ce..75d41bf6c866 100644 --- a/tracer/test/Datadog.Trace.Tests/Util/FnvHash64Tests.cs +++ b/tracer/test/Datadog.Trace.Tests/Util/FnvHash64Tests.cs @@ -10,6 +10,11 @@ using FluentAssertions; using FluentAssertions.Execution; using Xunit; +#if NETCOREAPP3_1_OR_GREATER +using MemoryExtensions = System.MemoryExtensions; +#else +using MemoryExtensions = Datadog.Trace.VendoredMicrosoftCode.System.MemoryExtensions; +#endif namespace Datadog.Trace.Tests.Util; @@ -250,8 +255,10 @@ public void CalculatesBinaryHashCorrectlyWhenCombined() [MemberData(nameof(BinaryData))] public void CalculatesOffsetCountHashCorrectly(byte[] data, string v1HashAsHex, string v1AHashAsHex) { - var v1 = FnvHash64.GenerateHash(data, 0, data.Length, FnvHash64.Version.V1); - var v1A = FnvHash64.GenerateHash(data, 0, data.Length, FnvHash64.Version.V1A); + // not calling as extension method to avoid namespace ambiguity + var span = MemoryExtensions.AsSpan(data, 0, data.Length); + var v1 = FnvHash64.GenerateHash(span, FnvHash64.Version.V1); + var v1A = FnvHash64.GenerateHash(span, FnvHash64.Version.V1A); using var a = new AssertionScope(); v1.ToString("x16").Should().Be(v1HashAsHex); @@ -268,8 +275,10 @@ public void CalculatesOffsetCountHashCorrectlyWithOffset(byte[] data, string v1H new Random().NextBytes(padded); Array.Copy(data, 0, padded, padding, data.Length); - var v1 = FnvHash64.GenerateHash(padded, padding, data.Length, FnvHash64.Version.V1); - var v1A = FnvHash64.GenerateHash(padded, padding, data.Length, FnvHash64.Version.V1A); + var span = MemoryExtensions.AsSpan(padded, padding, data.Length); + + var v1 = FnvHash64.GenerateHash(span, FnvHash64.Version.V1); + var v1A = FnvHash64.GenerateHash(span, FnvHash64.Version.V1A); using var a = new AssertionScope(); v1.ToString("x16").Should().Be(v1HashAsHex);