_Extensions.Nullables.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Numerics;
  4. using System.Text;
  5. namespace SharpGLTF.Schema2
  6. {
  7. /// <summary>
  8. /// Extensions used internally.
  9. /// </summary>
  10. static partial class _Schema2Extensions
  11. {
  12. #region nullables
  13. internal static String AsName(this string name)
  14. {
  15. return string.IsNullOrWhiteSpace(name) ? null : name;
  16. }
  17. internal static T AsValue<T>(this T? value, T defval)
  18. where T : struct
  19. {
  20. return value ?? defval;
  21. }
  22. internal static T? AsNullable<T>(this T value, T defval)
  23. where T : struct
  24. {
  25. return value.Equals(defval) ? (T?)null : value;
  26. }
  27. internal static T? AsNullable<T>(this T value, T defval, T minval, T maxval)
  28. where T : struct, IEquatable<T>, IComparable<T>
  29. {
  30. if (value.Equals(defval)) return null;
  31. if (value.CompareTo(minval) < 0) value = minval;
  32. if (value.CompareTo(maxval) > 0) value = maxval;
  33. return value.Equals(defval) ? (T?)null : value;
  34. }
  35. internal static Vector2? AsNullable(this Vector2 value, Vector2 defval, Vector2 minval, Vector2 maxval)
  36. {
  37. if (value.Equals(defval)) return null;
  38. value = Vector2.Min(value, maxval);
  39. value = Vector2.Max(value, minval);
  40. return value.Equals(defval) ? (Vector2?)null : value;
  41. }
  42. internal static Vector3? AsNullable(this Vector3 value, Vector3 defval, Vector3 minval, Vector3 maxval)
  43. {
  44. if (value.Equals(defval)) return null;
  45. value = Vector3.Min(value, maxval);
  46. value = Vector3.Max(value, minval);
  47. return value.Equals(defval) ? (Vector3?)null : value;
  48. }
  49. internal static Vector4? AsNullable(this Vector4 value, Vector4 defval, Vector4 minval, Vector4 maxval)
  50. {
  51. if (value.Equals(defval)) return (Vector4?)null;
  52. value = Vector4.Min(value, maxval);
  53. value = Vector4.Max(value, minval);
  54. return value.Equals(defval) ? (Vector4?)null : value;
  55. }
  56. internal static String AsNullable(this string value)
  57. {
  58. return string.IsNullOrEmpty(value) ? null : value;
  59. }
  60. internal static String AsEmptyNullable(this string value)
  61. {
  62. return string.IsNullOrWhiteSpace(value) ? null : value;
  63. }
  64. #endregion
  65. }
  66. }