| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | namespace CoreWCF.Channels |
| | | 10 | | { |
| | | 11 | | internal static class CorrelationIdGenerator |
| | | 12 | | { |
| | | 13 | | // Base32 encoding - in ascii sort order for easy text based sorting |
| | 0 | 14 | | private static readonly char[] s_encode32Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUV".ToCharArray(); |
| | | 15 | | |
| | | 16 | | // Seed the _lastConnectionId for this application instance with |
| | | 17 | | // the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 |
| | | 18 | | // for a roughly increasing _lastId over restarts |
| | 0 | 19 | | private static long _lastId = DateTime.UtcNow.Ticks; |
| | | 20 | | |
| | 0 | 21 | | public static string GetNextId() => GenerateId(Interlocked.Increment(ref _lastId)); |
| | | 22 | | |
| | | 23 | | private static string GenerateId(long id) |
| | | 24 | | { |
| | 0 | 25 | | char[] encode32Chars = s_encode32Chars; |
| | 0 | 26 | | Span<char> buffer = stackalloc char[13]; |
| | 0 | 27 | | buffer[12] = encode32Chars[id & 31]; |
| | 0 | 28 | | buffer[11] = encode32Chars[(id >> 5) & 31]; |
| | 0 | 29 | | buffer[10] = encode32Chars[(id >> 10) & 31]; |
| | 0 | 30 | | buffer[9] = encode32Chars[(id >> 15) & 31]; |
| | 0 | 31 | | buffer[8] = encode32Chars[(id >> 20) & 31]; |
| | 0 | 32 | | buffer[7] = encode32Chars[(id >> 25) & 31]; |
| | 0 | 33 | | buffer[6] = encode32Chars[(id >> 30) & 31]; |
| | 0 | 34 | | buffer[5] = encode32Chars[(id >> 35) & 31]; |
| | 0 | 35 | | buffer[4] = encode32Chars[(id >> 40) & 31]; |
| | 0 | 36 | | buffer[3] = encode32Chars[(id >> 45) & 31]; |
| | 0 | 37 | | buffer[2] = encode32Chars[(id >> 50) & 31]; |
| | 0 | 38 | | buffer[1] = encode32Chars[(id >> 55) & 31]; |
| | 0 | 39 | | buffer[0] = encode32Chars[(id >> 60) & 31]; |
| | 0 | 40 | | return buffer.ToString(); |
| | | 41 | | } |
| | | 42 | | } |
| | | 43 | | } |