Version.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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
  92. {
  93. get { return _Major; }
  94. }
  95. public int Minor
  96. {
  97. get { return _Minor; }
  98. }
  99. public int Build
  100. {
  101. get { return _Build; }
  102. }
  103. public int Revision
  104. {
  105. get { return _Revision; }
  106. }
  107. public short MajorRevision
  108. {
  109. get { return (short)(_Revision >> 16); }
  110. }
  111. public short MinorRevision
  112. {
  113. get { return (short)(_Revision & 0xFFFF); }
  114. }
  115. public int CompareTo(object? version)
  116. {
  117. if (version == null)
  118. {
  119. return 1;
  120. }
  121. if (version is Version v)
  122. {
  123. return CompareTo(v);
  124. }
  125. throw new ArgumentException(SR.Arg_MustBeVersion);
  126. }
  127. public int CompareTo(Version? value)
  128. {
  129. return
  130. object.ReferenceEquals(value, this) ? 0 :
  131. value is null ? 1 :
  132. _Major != value._Major ? (_Major > value._Major ? 1 : -1) :
  133. _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
  134. _Build != value._Build ? (_Build > value._Build ? 1 : -1) :
  135. _Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
  136. 0;
  137. }
  138. public override bool Equals(object? obj)
  139. {
  140. return Equals(obj as Version);
  141. }
  142. public bool Equals(Version? obj)
  143. {
  144. return object.ReferenceEquals(obj, this) ||
  145. (!(obj is null) &&
  146. _Major == obj._Major &&
  147. _Minor == obj._Minor &&
  148. _Build == obj._Build &&
  149. _Revision == obj._Revision);
  150. }
  151. public override int GetHashCode()
  152. {
  153. // Let's assume that most version numbers will be pretty small and just
  154. // OR some lower order bits together.
  155. int accumulator = 0;
  156. accumulator |= (_Major & 0x0000000F) << 28;
  157. accumulator |= (_Minor & 0x000000FF) << 20;
  158. accumulator |= (_Build & 0x000000FF) << 12;
  159. accumulator |= (_Revision & 0x00000FFF);
  160. return accumulator;
  161. }
  162. public override string ToString() =>
  163. ToString(DefaultFormatFieldCount);
  164. public string ToString(int fieldCount) =>
  165. fieldCount == 0 ? string.Empty :
  166. fieldCount == 1 ? _Major.ToString() :
  167. StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
  168. public bool TryFormat(Span<char> destination, out int charsWritten) =>
  169. TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
  170. public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
  171. {
  172. if (fieldCount == 0)
  173. {
  174. charsWritten = 0;
  175. return true;
  176. }
  177. else if (fieldCount == 1)
  178. {
  179. return _Major.TryFormat(destination, out charsWritten);
  180. }
  181. StringBuilder sb = ToCachedStringBuilder(fieldCount);
  182. if (sb.Length <= destination.Length)
  183. {
  184. sb.CopyTo(0, destination, sb.Length);
  185. StringBuilderCache.Release(sb);
  186. charsWritten = sb.Length;
  187. return true;
  188. }
  189. StringBuilderCache.Release(sb);
  190. charsWritten = 0;
  191. return false;
  192. }
  193. bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
  194. {
  195. // format and provider are ignored.
  196. return TryFormat(destination, out charsWritten);
  197. }
  198. private int DefaultFormatFieldCount =>
  199. _Build == -1 ? 2 :
  200. _Revision == -1 ? 3 :
  201. 4;
  202. private StringBuilder ToCachedStringBuilder(int fieldCount)
  203. {
  204. // Note: As we always have positive numbers then it is safe to convert the number to string
  205. // regardless of the current culture as we'll not have any punctuation marks in the number.
  206. if (fieldCount == 2)
  207. {
  208. StringBuilder sb = StringBuilderCache.Acquire();
  209. sb.Append(_Major);
  210. sb.Append('.');
  211. sb.Append(_Minor);
  212. return sb;
  213. }
  214. else
  215. {
  216. if (_Build == -1)
  217. {
  218. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
  219. }
  220. if (fieldCount == 3)
  221. {
  222. StringBuilder sb = StringBuilderCache.Acquire();
  223. sb.Append(_Major);
  224. sb.Append('.');
  225. sb.Append(_Minor);
  226. sb.Append('.');
  227. sb.Append(_Build);
  228. return sb;
  229. }
  230. if (_Revision == -1)
  231. {
  232. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
  233. }
  234. if (fieldCount == 4)
  235. {
  236. StringBuilder sb = StringBuilderCache.Acquire();
  237. sb.Append(_Major);
  238. sb.Append('.');
  239. sb.Append(_Minor);
  240. sb.Append('.');
  241. sb.Append(_Build);
  242. sb.Append('.');
  243. sb.Append(_Revision);
  244. return sb;
  245. }
  246. throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
  247. }
  248. }
  249. public static Version Parse(string input)
  250. {
  251. if (input == null)
  252. {
  253. throw new ArgumentNullException(nameof(input));
  254. }
  255. return ParseVersion(input.AsSpan(), throwOnFailure: true)!;
  256. }
  257. public static Version Parse(ReadOnlySpan<char> input) =>
  258. ParseVersion(input, throwOnFailure: true)!;
  259. public static bool TryParse(string? input, [NotNullWhen(true)] out Version? result)
  260. {
  261. if (input == null)
  262. {
  263. result = null;
  264. return false;
  265. }
  266. return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null;
  267. }
  268. public static bool TryParse(ReadOnlySpan<char> input, [NotNullWhen(true)] out Version? result) =>
  269. (result = ParseVersion(input, throwOnFailure: false)) != null;
  270. private static Version? ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
  271. {
  272. // Find the separator between major and minor. It must exist.
  273. int majorEnd = input.IndexOf('.');
  274. if (majorEnd < 0)
  275. {
  276. if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
  277. return null;
  278. }
  279. // Find the ends of the optional minor and build portions.
  280. // We musn't have any separators after build.
  281. int buildEnd = -1;
  282. int minorEnd = input.Slice(majorEnd + 1).IndexOf('.');
  283. if (minorEnd != -1)
  284. {
  285. minorEnd += (majorEnd + 1);
  286. buildEnd = input.Slice(minorEnd + 1).IndexOf('.');
  287. if (buildEnd != -1)
  288. {
  289. buildEnd += (minorEnd + 1);
  290. if (input.Slice(buildEnd + 1).Contains('.'))
  291. {
  292. if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
  293. return null;
  294. }
  295. }
  296. }
  297. int minor, build, revision;
  298. // Parse the major version
  299. if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out int major))
  300. {
  301. return null;
  302. }
  303. if (minorEnd != -1)
  304. {
  305. // If there's more than a major and minor, parse the minor, too.
  306. if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
  307. {
  308. return null;
  309. }
  310. if (buildEnd != -1)
  311. {
  312. // major.minor.build.revision
  313. return
  314. TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
  315. TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
  316. new Version(major, minor, build, revision) :
  317. null;
  318. }
  319. else
  320. {
  321. // major.minor.build
  322. return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
  323. new Version(major, minor, build) :
  324. null;
  325. }
  326. }
  327. else
  328. {
  329. // major.minor
  330. return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
  331. new Version(major, minor) :
  332. null;
  333. }
  334. }
  335. private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
  336. {
  337. if (throwOnFailure)
  338. {
  339. if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
  340. {
  341. throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
  342. }
  343. return true;
  344. }
  345. return int.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent) && parsedComponent >= 0;
  346. }
  347. // Force inline as the true/false ternary takes it above ALWAYS_INLINE size even though the asm ends up smaller
  348. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  349. public static bool operator ==(Version? v1, Version? v2)
  350. {
  351. // Test "right" first to allow branch elimination when inlined for null checks (== null)
  352. // so it can become a simple test
  353. if (v2 is null)
  354. {
  355. // return true/false not the test result https://github.com/dotnet/coreclr/issues/914
  356. return (v1 is null) ? true : false;
  357. }
  358. // Quick reference equality test prior to calling the virtual Equality
  359. return ReferenceEquals(v2, v1) ? true : v2.Equals(v1);
  360. }
  361. public static bool operator !=(Version? v1, Version? v2)
  362. {
  363. return !(v1 == v2);
  364. }
  365. public static bool operator <(Version? v1, Version? v2)
  366. {
  367. if (v1 is null)
  368. {
  369. return !(v2 is null);
  370. }
  371. return (v1.CompareTo(v2) < 0);
  372. }
  373. public static bool operator <=(Version? v1, Version? v2)
  374. {
  375. if (v1 is null)
  376. {
  377. return true;
  378. }
  379. return (v1.CompareTo(v2) <= 0);
  380. }
  381. public static bool operator >(Version? v1, Version? v2)
  382. {
  383. return (v2 < v1);
  384. }
  385. public static bool operator >=(Version? v1, Version? v2)
  386. {
  387. return (v2 <= v1);
  388. }
  389. }
  390. }