NanoXLSX.Core 3.0.0-rc.4
Loading...
Searching...
No Matches
Comparators.cs
1using System;
2using System.Runtime.InteropServices;
3using System.Security;
4
6{
10 public static class Comparators
11 {
12
16 private const float FLOAT_THRESHOLD = 0.00001f;
20 private const double DOUBLE_THRESHOLD = 1e-12;
21
28 public static bool CompareSecureStrings(SecureString value1, SecureString value2)
29 {
30 bool v1Empty = false;
31 bool v2Empty = false;
32 if (value1 == null || value1.Length == 0)
33 {
34 v1Empty = true;
35 }
36 if (value2 == null || value2.Length == 0)
37 {
38 v2Empty = true;
39 }
40 if (v1Empty && !v2Empty || !v1Empty && v2Empty)
41 {
42 return false;
43 }
44 if (v1Empty && v2Empty)
45 {
46 return true;
47 }
48 IntPtr unmanagedString1 = IntPtr.Zero;
49 IntPtr unmanagedString2 = IntPtr.Zero;
50 try
51 {
52 unmanagedString1 = Marshal.SecureStringToBSTR(value1);
53 unmanagedString2 = Marshal.SecureStringToBSTR(value2);
54 int length1 = Marshal.ReadInt32(unmanagedString1, -4);
55 int length2 = Marshal.ReadInt32(unmanagedString2, -4);
56 if (length1 == length2)
57 {
58 for (int i = 0; i < length1; ++i)
59 {
60 byte byte1 = Marshal.ReadByte(unmanagedString1, i);
61 byte byte2 = Marshal.ReadByte(unmanagedString2, i);
62 if (byte1 != byte2) return false;
63 }
64 }
65 else
66 {
67 return false;
68 }
69 return true;
70 }
71 finally
72 {
73 // Cleanup
74 if (unmanagedString2 != IntPtr.Zero) Marshal.ZeroFreeBSTR(unmanagedString2);
75 if (unmanagedString1 != IntPtr.Zero) Marshal.ZeroFreeBSTR(unmanagedString1);
76 }
77 }
78
86 public static int CompareDimensions(float? dimension1, float? dimension2)
87 {
88 if (dimension1 == null)
89 {
90 dimension1 = float.MinValue;
91 }
92 if (dimension2 == null)
93 {
94 dimension2 = float.MinValue;
95 }
96 if (Math.Abs(dimension1.Value - dimension2.Value) < FLOAT_THRESHOLD)
97 {
98 return 0;
99 }
100 else if (dimension1 > dimension2)
101 {
102 return 1;
103 }
104 else
105 {
106 return -1;
107 }
108 }
109
115 public static bool IsZero(double value)
116 {
117 return Math.Abs(value) < DOUBLE_THRESHOLD;
118 }
119
125 public static bool IsZero(float value)
126 {
127 return Math.Abs(value) < FLOAT_THRESHOLD;
128 }
129 }
130}
Class providing general comparator methods.
static bool IsZero(float value)
Checks whether the passed float value is considered as zero using a defined threshold.
static bool CompareSecureStrings(SecureString value1, SecureString value2)
Compares whether the content of two SecureString instances are equal. The comparison method tries to ...
static int CompareDimensions(float? dimension1, float? dimension2)
Compares two dimensions (e.g. column width, column height).
static bool IsZero(double value)
Checks whether the passed double value is considered as zero using a defined threshold.