blob: 190ddbbc5f320d4432254ff19da51ee589a12a33 [file] [log] [blame]
Jens Geyer62445c12022-06-29 00:00:00 +02001// Licensed to the Apache Software Foundation(ASF) under one
2// or more contributor license agreements.See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18using System;
19using System.Collections.Generic;
20using System.Diagnostics;
21using System.Text;
22
23namespace Thrift.Protocol.Utilities
24{
25 public static class TGuidExtensions
26 {
27 public static Guid SwapByteOrder(this Guid self)
28 {
29 var bytes = self.ToByteArray();
30
31 // already network order on BigEndian machines
32 if (BitConverter.IsLittleEndian)
33 {
34 SwapBytes(ref bytes[0], ref bytes[3]);
35 SwapBytes(ref bytes[1], ref bytes[2]);
36 SwapBytes(ref bytes[4], ref bytes[5]);
37 SwapBytes(ref bytes[6], ref bytes[7]);
38 }
39
40 return new Guid(bytes);
41 }
42
43 private static void SwapBytes(ref byte one, ref byte two)
44 {
45 var tmp = one;
46 one = two;
47 two = tmp;
48 }
49
50 #region SelfTest
51#if DEBUG
52 static private readonly Guid TEST_GUID = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");
53
54 static TGuidExtensions()
55 {
56 SelfTest();
57 }
58
59 private static void SelfTest()
60 {
61 // host to network
62 var guid = TEST_GUID;
63 guid = guid.SwapByteOrder();
64
65 // validate network order
66 var bytes = guid.ToByteArray();
67 for (var i = 0; i < 10; ++i)
68 {
69 var expected = i * 0x11;
70 Debug.Assert( bytes[i] == expected);
71 }
72
73 // network to host and final validation
74 guid = guid.SwapByteOrder();
75 Debug.Assert(guid.Equals(TEST_GUID));
76 }
77
78#endif
79 #endregion
80
81 }
82}