Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.Intrinsics;
- using System.Runtime.Intrinsics.X86;
- public class SIMDStringToLower
- {
- public static string ToLowerCase(string input)
- {
- if (input == null)
- {
- throw new ArgumentNullException(nameof(input));
- }
- int length = input.Length;
- char[] result = new char[length];
- if (Sse2.IsSupported)
- {
- int simdLength = Vector128<ushort>.Count;
- int simdIterations = length / simdLength;
- Vector128<ushort> upperCaseMask = Vector128.Create((ushort)0x0020);
- for (int i = 0; i < simdIterations * simdLength; i += simdLength)
- {
- Vector128<ushort> inputVector = Unsafe.ReadUnaligned<Vector128<ushort>>(ref Unsafe.As<char, byte>(ref input[i]));
- Vector128<ushort> upperCaseMaskApplied = Sse2.Add(inputVector, upperCaseMask);
- Vector128<ushort> isInRange = Sse2.And(Sse2.CompareGreaterThan(inputVector, Vector128.Create((ushort)0x0040)), Sse2.CompareLessThan(inputVector, Vector128.Create((ushort)0x005b)));
- Vector128<ushort> resultVector = Sse2.Or(Sse2.And(isInRange, upperCaseMaskApplied), Sse2.AndNot(isInRange, inputVector));
- Unsafe.WriteUnaligned(ref Unsafe.As<char, byte>(ref result[i]), resultVector);
- }
- // Process the remaining characters
- for (int i = simdIterations * simdLength; i < length; i++)
- {
- char c = input[i];
- result[i] = (c >= 'A' && c <= 'Z') ? (char)(c | 0x20) : c;
- }
- }
- else
- {
- for (int i = 0; i < length; i++)
- {
- char c = input[i];
- result[i] = (c >= 'A' && c <= 'Z') ? (char)(c | 0x20) : c;
- }
- }
- return new string(result);
- }
- }
Add Comment
Please, Sign In to add comment