Hasher.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* Copyright 2010-2014 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. namespace MongoDB.Shared
  19. {
  20. internal class Hasher
  21. {
  22. // private fields
  23. private int _hashCode;
  24. // constructors
  25. public Hasher()
  26. {
  27. _hashCode = 17;
  28. }
  29. public Hasher(int seed)
  30. {
  31. _hashCode = seed;
  32. }
  33. // public methods
  34. public override int GetHashCode()
  35. {
  36. return _hashCode;
  37. }
  38. // this overload added to avoid boxing
  39. public Hasher Hash(bool obj)
  40. {
  41. _hashCode = 37 * _hashCode + obj.GetHashCode();
  42. return this;
  43. }
  44. // this overload added to avoid boxing
  45. public Hasher Hash(int obj)
  46. {
  47. _hashCode = 37 * _hashCode + obj.GetHashCode();
  48. return this;
  49. }
  50. // this overload added to avoid boxing
  51. public Hasher Hash(long obj)
  52. {
  53. _hashCode = 37 * _hashCode + obj.GetHashCode();
  54. return this;
  55. }
  56. // this overload added to avoid boxing
  57. public Hasher Hash<T>(Nullable<T> obj) where T : struct
  58. {
  59. _hashCode = 37 * _hashCode + ((obj == null) ? -1 : obj.Value.GetHashCode());
  60. return this;
  61. }
  62. public Hasher Hash(object obj)
  63. {
  64. _hashCode = 37 * _hashCode + ((obj == null) ? -1 : obj.GetHashCode());
  65. return this;
  66. }
  67. public Hasher HashElements(IEnumerable sequence)
  68. {
  69. if (sequence == null)
  70. {
  71. _hashCode = 37 * _hashCode + -1;
  72. }
  73. else
  74. {
  75. foreach (var value in sequence)
  76. {
  77. _hashCode = 37 * _hashCode + ((value == null) ? -1 : value.GetHashCode());
  78. }
  79. }
  80. return this;
  81. }
  82. public Hasher HashStructElements<T>(IEnumerable<T> sequence) where T : struct
  83. {
  84. foreach (var value in sequence)
  85. {
  86. _hashCode = 37 * _hashCode + value.GetHashCode();
  87. }
  88. return this;
  89. }
  90. }
  91. }