Guest User

Untitled

a guest
Mar 17th, 2023
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.Intrinsics;
  4. using System.Runtime.Intrinsics.X86;
  5.  
  6. public class SIMDStringToLower
  7. {
  8.     public static string ToLowerCase(string input)
  9.     {
  10.         if (input == null)
  11.         {
  12.             throw new ArgumentNullException(nameof(input));
  13.         }
  14.  
  15.         int length = input.Length;
  16.         char[] result = new char[length];
  17.  
  18.         if (Sse2.IsSupported)
  19.         {
  20.             int simdLength = Vector128<ushort>.Count;
  21.             int simdIterations = length / simdLength;
  22.             Vector128<ushort> upperCaseMask = Vector128.Create((ushort)0x0020);
  23.  
  24.             for (int i = 0; i < simdIterations * simdLength; i += simdLength)
  25.             {
  26.                 Vector128<ushort> inputVector = Unsafe.ReadUnaligned<Vector128<ushort>>(ref Unsafe.As<char, byte>(ref input[i]));
  27.                 Vector128<ushort> upperCaseMaskApplied = Sse2.Add(inputVector, upperCaseMask);
  28.                 Vector128<ushort> isInRange = Sse2.And(Sse2.CompareGreaterThan(inputVector, Vector128.Create((ushort)0x0040)), Sse2.CompareLessThan(inputVector, Vector128.Create((ushort)0x005b)));
  29.  
  30.                 Vector128<ushort> resultVector = Sse2.Or(Sse2.And(isInRange, upperCaseMaskApplied), Sse2.AndNot(isInRange, inputVector));
  31.  
  32.                 Unsafe.WriteUnaligned(ref Unsafe.As<char, byte>(ref result[i]), resultVector);
  33.             }
  34.  
  35.             // Process the remaining characters
  36.             for (int i = simdIterations * simdLength; i < length; i++)
  37.             {
  38.                 char c = input[i];
  39.                 result[i] = (c >= 'A' && c <= 'Z') ? (char)(c | 0x20) : c;
  40.             }
  41.         }
  42.         else
  43.         {
  44.             for (int i = 0; i < length; i++)
  45.             {
  46.                 char c = input[i];
  47.                 result[i] = (c >= 'A' && c <= 'Z') ? (char)(c | 0x20) : c;
  48.             }
  49.         }
  50.  
  51.         return new string(result);
  52.     }
  53. }
Add Comment
Please, Sign In to add comment