blob: ecc026369c0c7bdb4cfd286d701bdd3337e65fb4 [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 {
Jens Geyer4115e952023-11-21 23:00:01 +010045 (two, one) = (one, two);
Jens Geyer62445c12022-06-29 00:00:00 +020046 }
47
48 #region SelfTest
49#if DEBUG
50 static private readonly Guid TEST_GUID = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");
51
52 static TGuidExtensions()
53 {
54 SelfTest();
55 }
56
57 private static void SelfTest()
58 {
59 // host to network
60 var guid = TEST_GUID;
61 guid = guid.SwapByteOrder();
62
63 // validate network order
64 var bytes = guid.ToByteArray();
65 for (var i = 0; i < 10; ++i)
66 {
67 var expected = i * 0x11;
68 Debug.Assert( bytes[i] == expected);
69 }
70
71 // network to host and final validation
72 guid = guid.SwapByteOrder();
73 Debug.Assert(guid.Equals(TEST_GUID));
74 }
75
76#endif
77 #endregion
78
79 }
80}