|
| 1 | +/* |
| 2 | + * Copyright (c) 2016-Present, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 7 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + */ |
| 9 | + |
| 10 | +using System; |
| 11 | +using System.Threading; |
| 12 | + |
| 13 | +namespace React |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// React ID generator. |
| 17 | + /// </summary> |
| 18 | + public class ReactIdGenerator : IReactIdGenerator |
| 19 | + { |
| 20 | + private static readonly string _encode32Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; |
| 21 | + |
| 22 | + private static long _random = DateTime.UtcNow.Ticks; |
| 23 | + |
| 24 | + private static readonly char[] reactPrefix = "react_".ToCharArray(); |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// "react_".Length = 6 + 13 random symbols |
| 28 | + /// </summary> |
| 29 | + private const int reactIdLength = 19; |
| 30 | + |
| 31 | + [ThreadStatic] |
| 32 | + private static char[] _chars; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Returns a short react identifier starts with "react_". |
| 36 | + /// </summary> |
| 37 | + /// <returns></returns> |
| 38 | + public string Generate() |
| 39 | + { |
| 40 | + var chars = _chars; |
| 41 | + if (chars == null) |
| 42 | + { |
| 43 | + _chars = chars = new char[reactIdLength]; |
| 44 | + Array.Copy(reactPrefix, 0, chars, 0, reactPrefix.Length); |
| 45 | + } |
| 46 | + |
| 47 | + var id = Interlocked.Increment(ref _random); |
| 48 | + |
| 49 | + // from 6 because "react_".Length == 6, _encode32Chars.Length == 32 (base32), |
| 50 | + // base32 characters are 5 bits in length and from long (64 bits) we can get 13 symbols |
| 51 | + chars[6] = _encode32Chars[(int)(id >> 60) & 31]; |
| 52 | + chars[7] = _encode32Chars[(int)(id >> 55) & 31]; |
| 53 | + chars[8] = _encode32Chars[(int)(id >> 50) & 31]; |
| 54 | + chars[9] = _encode32Chars[(int)(id >> 45) & 31]; |
| 55 | + chars[10] = _encode32Chars[(int)(id >> 40) & 31]; |
| 56 | + chars[11] = _encode32Chars[(int)(id >> 35) & 31]; |
| 57 | + chars[12] = _encode32Chars[(int)(id >> 30) & 31]; |
| 58 | + chars[13] = _encode32Chars[(int)(id >> 25) & 31]; |
| 59 | + chars[14] = _encode32Chars[(int)(id >> 20) & 31]; |
| 60 | + chars[15] = _encode32Chars[(int)(id >> 15) & 31]; |
| 61 | + chars[16] = _encode32Chars[(int)(id >> 10) & 31]; |
| 62 | + chars[17] = _encode32Chars[(int)(id >> 5) & 31]; |
| 63 | + chars[18] = _encode32Chars[(int)id & 31]; |
| 64 | + |
| 65 | + return new string(chars, 0, reactIdLength); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments