Hasher.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. namespace MongoDB.Shared
  18. {
  19. internal class Hasher
  20. {
  21. // private fields
  22. private int _hashCode;
  23. // constructors
  24. public Hasher()
  25. {
  26. _hashCode = 17;
  27. }
  28. public Hasher(int seed)
  29. {
  30. _hashCode = seed;
  31. }
  32. // public methods
  33. public override int GetHashCode()
  34. {
  35. return _hashCode;
  36. }
  37. // this overload added to avoid boxing
  38. public Hasher Hash(bool obj)
  39. {
  40. _hashCode = 37 * _hashCode + obj.GetHashCode();
  41. return this;
  42. }
  43. // this overload added to avoid boxing
  44. public Hasher Hash(int obj)
  45. {
  46. _hashCode = 37 * _hashCode + obj.GetHashCode();
  47. return this;
  48. }
  49. // this overload added to avoid boxing
  50. public Hasher Hash(long obj)
  51. {
  52. _hashCode = 37 * _hashCode + obj.GetHashCode();
  53. return this;
  54. }
  55. // this overload added to avoid boxing
  56. public Hasher Hash<T>(Nullable<T> obj) where T : struct
  57. {
  58. _hashCode = 37 * _hashCode + ((obj == null) ? 0 : obj.Value.GetHashCode());
  59. return this;
  60. }
  61. public Hasher Hash(object obj)
  62. {
  63. _hashCode = 37 * _hashCode + ((obj == null) ? 0 : obj.GetHashCode());
  64. return this;
  65. }
  66. public Hasher HashElements(IEnumerable sequence)
  67. {
  68. if (sequence == null)
  69. {
  70. _hashCode = 37 * _hashCode + 0;
  71. }
  72. else
  73. {
  74. foreach (var obj in sequence)
  75. {
  76. _hashCode = 37 * _hashCode + ((obj == null) ? 0 : obj.GetHashCode());
  77. }
  78. }
  79. return this;
  80. }
  81. }
  82. }