Version.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. // See the LICENSE file in the project root for more information.
  4. using System.Globalization;
  5. using System.Diagnostics;
  6. using System.Text;
  7. using System.Runtime.CompilerServices;
  8. using System.Diagnostics.CodeAnalysis;
  9. namespace System
  10. {
  11. // A Version object contains four hierarchical numeric components: major, minor,
  12. // build and revision. Build and revision may be unspecified, which is represented
  13. // internally as a -1. By definition, an unspecified component matches anything
  14. // (both unspecified and specified), and an unspecified component is "less than" any
  15. // specified component.
  16. [Serializable]
  17. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  18. public sealed class Version : ICloneable, IComparable, IComparable<Version?>,
  19. #nullable disable // see comment on String
  20. IEquatable<Version>,
  21. #nullable restore
  22. ISpanFormattable
  23. {
  24. // AssemblyName depends on the order staying the same
  25. private readonly int _Major; // Do not rename (binary serialization)
  26. private readonly int _Minor; // Do not rename (binary serialization)
  27. private readonly int _Build = -1; // Do not rename (binary serialization)
  28. private readonly int _Revision = -1; // Do not rename (binary serialization)
  29. public Version(int major, int minor, int build, int revision)
  30. {
  31. if (major < 0)
  32. throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
  33. if (minor < 0)
  34. throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
  35. if (build < 0)
  36. throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
  37. if (revision < 0)
  38. throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version);
  39. _Major = major;
  40. _Minor = minor;
  41. _Build = build;
  42. _Revision = revision;
  43. }
  44. public Version(int major, int minor, int build)
  45. {
  46. if (major < 0)
  47. throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
  48. if (minor < 0)
  49. throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
  50. if (build < 0)
  51. throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
  52. _Major = major;
  53. _Minor = minor;
  54. _Build = build;
  55. }
  56. public Version(int major, int minor)
  57. {
  58. if (major < 0)
  59. throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
  60. if (minor < 0)
  61. throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
  62. _Major = major;
  63. _Minor = minor;
  64. }
  65. public Version(string version)
  66. {
  67. Version v = Version.Parse(version);
  68. _Major = v.Major;
  69. _Minor = v.Minor;
  70. _Build = v.Build;
  71. _Revision = v.Revision;
  72. }
  73. public Version()
  74. {
  75. _Major = 0;
  76. _Minor = 0;
  77. }
  78. private Version(Version version)
  79. {
  80. Debug.Assert(version != null);
  81. _Major = version._Major;
  82. _Minor = version._Minor;
  83. _Build = version._Build;
  84. _Revision = version._Revision;
  85. }
  86. public object Clone()
  87. {
  88. return new Version(this);
  89. }
  90. // Properties for setting and getting version numbers
  91. public int Major => _Major;
  92. public int Minor => _Minor;
  93. public int Build => _Build;
  94. public int Revision => _Revision;
  95. public short MajorRevision => (short)(_Revision >> 16);
  96. public short MinorRevision => (short)(_Revision & 0xFFFF);
  97. public int CompareTo(object? version)
  98. {
  99. if (version == null)
  100. {
  101. return 1;
  102. }
  103. if (version is Version v)
  104. {
  105. return CompareTo(v);
  106. }
  107. throw new ArgumentException(SR.Arg_MustBeVersion);
  108. }
  109. public int CompareTo(Version? value)
  110. {
  111. return
  112. object.ReferenceEquals(value, this) ? 0 :
  113. value is null ? 1 :
  114. _Major != value._Major ? (_Major > value._Major ? 1 : -1) :
  115. _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
  116. _Build != value._Build ? (_Build > value._Build ? 1 : -1) :
  117. _Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
  118. 0;
  119. }
  120. public override bool Equals(object? obj)
  121. {
  122. return Equals(obj as Version);
  123. }
  124. public bool Equals(Version? obj)
  125. {
  126. return object.ReferenceEquals(obj, this) ||
  127. (!(obj is null) &&
  128. _Major == obj._Major &&
  129. _Minor == obj._Minor &&
  130. _Build == obj._Build &&
  131. _Revision == obj._Revision);
  132. }
  133. public override int GetHashCode()
  134. {
  135. // Let's assume that most version numbers will be pretty small and just
  136. // OR some lower order bits together.
  137. int accumulator = 0;
  138. accumulator |= (_Major & 0x0000000F) << 28;
  139. accumulator |= (_Minor & 0x000000FF) << 20;
  140. accumulator |= (_Build & 0x000000FF) << 12;
  141. accumulator |= (_Revision & 0x00000FFF);
  142. return accumulator;
  143. }
  144. public override string ToString() =>
  145. ToString(DefaultFormatFieldCount);
  146. public string ToString(int fieldCount) =>
  147. fieldCount == 0 ? string.Empty :
  148. fieldCount == 1 ? _Major.ToString() :
  149. StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
  150. public bool TryFormat(Span<char> destination, out int charsWritten) =>
  151. TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
  152. public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
  153. {
  154. if (fieldCount == 0)
  155. {
  156. charsWritten = 0;
  157. return true;
  158. }
  159. else if (fieldCount == 1)
  160. {
  161. return _Major.TryFormat(destination, out charsWritten);
  162. }
  163. StringBuilder sb = ToCachedStringBuilder(fieldCount);
  164. if (sb.Length <= destination.Length)
  165. {
  166. sb.CopyTo(0, destination, sb.Length);
  167. StringBuilderCache.Release(sb);
  168. charsWritten = sb.Length;
  169. return true;
  170. }
  171. StringBuilderCache.Release(sb);
  172. charsWritten = 0;
  173. return false;
  174. }
  175. bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
  176. {
  177. // format and provider are ignored.
  178. return TryFormat(destination, out charsWritten);
  179. }
  180. private int DefaultFormatFieldCount =>
  181. _Build == -1 ? 2 :
  182. _Revision == -1 ? 3 :
  183. 4;
  184. private StringBuilder ToCachedStringBuilder(int fieldCount)
  185. {
  186. // Note: As we always have positive numbers then it is safe to convert the number to string
  187. // regardless of the current culture as we'll not have any punctuation marks in the number.
  188. if (fieldCount == 2)
  189. {
  190. StringBuilder sb = StringBuilderCache.Acquire();
  191. sb.Append(_Major);
  192. sb.Append('.');
  193. sb.Append(_Minor);
  194. return sb;
  195. }
  196. else
  197. {
  198. if (_Build == -1)
  199. {
  200. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
  201. }
  202. if (fieldCount == 3)
  203. {
  204. StringBuilder sb = StringBuilderCache.Acquire();
  205. sb.Append(_Major);
  206. sb.Append('.');
  207. sb.Append(_Minor);
  208. sb.Append('.');
  209. sb.Append(_Build);
  210. return sb;
  211. }
  212. if (_Revision == -1)
  213. {
  214. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
  215. }
  216. if (fieldCount == 4)
  217. {
  218. StringBuilder sb = StringBuilderCache.Acquire();
  219. sb.Append(_Major);
  220. sb.Append('.');
  221. sb.Append(_Minor);
  222. sb.Append('.');
  223. sb.Append(_Build);
  224. sb.Append('.');
  225. sb.Append(_Revision);
  226. return sb;
  227. }
  228. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
  229. }
  230. }
  231. public static Version Parse(string input)
  232. {
  233. if (input == null)
  234. {
  235. throw new ArgumentNullException(nameof(input));
  236. }
  237. return ParseVersion(input.AsSpan(), throwOnFailure: true)!;
  238. }
  239. public static Version Parse(ReadOnlySpan<char> input) =>
  240. ParseVersion(input, throwOnFailure: true)!;
  241. public static bool TryParse(string? input, [NotNullWhen(true)] out Version? result)
  242. {
  243. if (input == null)
  244. {
  245. result = null;
  246. return false;
  247. }
  248. return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null;
  249. }
  250. public static bool TryParse(ReadOnlySpan<char> input, [NotNullWhen(true)] out Version? result) =>
  251. (result = ParseVersion(input, throwOnFailure: false)) != null;
  252. private static Version? ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
  253. {
  254. // Find the separator between major and minor. It must exist.
  255. int majorEnd = input.IndexOf('.');
  256. if (majorEnd < 0)
  257. {
  258. if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
  259. return null;
  260. }
  261. // Find the ends of the optional minor and build portions.
  262. // We musn't have any separators after build.
  263. int buildEnd = -1;
  264. int minorEnd = input.Slice(majorEnd + 1).IndexOf('.');
  265. if (minorEnd != -1)
  266. {
  267. minorEnd += (majorEnd + 1);
  268. buildEnd = input.Slice(minorEnd + 1).IndexOf('.');
  269. if (buildEnd != -1)
  270. {
  271. buildEnd += (minorEnd + 1);
  272. if (input.Slice(buildEnd + 1).Contains('.'))
  273. {
  274. if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
  275. return null;
  276. }
  277. }
  278. }
  279. int minor, build, revision;
  280. // Parse the major version
  281. if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out int major))
  282. {
  283. return null;
  284. }
  285. if (minorEnd != -1)
  286. {
  287. // If there's more than a major and minor, parse the minor, too.
  288. if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
  289. {
  290. return null;
  291. }
  292. if (buildEnd != -1)
  293. {
  294. // major.minor.build.revision
  295. return
  296. TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
  297. TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
  298. new Version(major, minor, build, revision) :
  299. null;
  300. }
  301. else
  302. {
  303. // major.minor.build
  304. return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
  305. new Version(major, minor, build) :
  306. null;
  307. }
  308. }
  309. else
  310. {
  311. // major.minor
  312. return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
  313. new Version(major, minor) :
  314. null;
  315. }
  316. }
  317. private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
  318. {
  319. if (throwOnFailure)
  320. {
  321. if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
  322. {
  323. throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
  324. }
  325. return true;
  326. }
  327. return int.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent) && parsedComponent >= 0;
  328. }
  329. // Force inline as the true/false ternary takes it above ALWAYS_INLINE size even though the asm ends up smaller
  330. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  331. public static bool operator ==(Version? v1, Version? v2)
  332. {
  333. // Test "right" first to allow branch elimination when inlined for null checks (== null)
  334. // so it can become a simple test
  335. if (v2 is null)
  336. {
  337. // return true/false not the test result https://github.com/dotnet/coreclr/issues/914
  338. return (v1 is null) ? true : false;
  339. }
  340. // Quick reference equality test prior to calling the virtual Equality
  341. return ReferenceEquals(v2, v1) ? true : v2.Equals(v1);
  342. }
  343. public static bool operator !=(Version? v1, Version? v2) => !(v1 == v2);
  344. public static bool operator <(Version? v1, Version? v2)
  345. {
  346. if (v1 is null)
  347. {
  348. return !(v2 is null);
  349. }
  350. return v1.CompareTo(v2) < 0;
  351. }
  352. public static bool operator <=(Version? v1, Version? v2)
  353. {
  354. if (v1 is null)
  355. {
  356. return true;
  357. }
  358. return v1.CompareTo(v2) <= 0;
  359. }
  360. public static bool operator >(Version? v1, Version? v2) => v2 < v1;
  361. public static bool operator >=(Version? v1, Version? v2) => v2 <= v1;
  362. }
  363. }