PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/core/src/main/php/util/collections/HashProvider.class.php

http://github.com/xp-framework/xp-framework
PHP | 95 lines | 32 code | 10 blank | 53 comment | 2 complexity | b77912bea5d9b0e9d4d21baec42fe201 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /* This class is part of the XP framework
  3. *
  4. * $Id$
  5. */
  6. uses('util.collections.MD5HashImplementation');
  7. /**
  8. * Provides hashing functionality for maps.
  9. *
  10. * Basic usage:
  11. * <code>
  12. * $hashCode= HashProvider::hashOf($string);
  13. * </code>
  14. *
  15. * Uses MD5 as default hashing implementation. To change the hashing
  16. * implementation to be used, use the following:
  17. * <code>
  18. * HashProvider::getInstance()->setImplementation(new MyHashImplementation());
  19. * </code>
  20. *
  21. * @see xp://util.collections.DJBX33AHashImplementation
  22. * @see xp://util.collections.MD5HashImplementation
  23. * @see xp://util.collections.Map
  24. * @test xp://net.xp_framework.unittest.util.collections.HashProviderTest
  25. */
  26. class HashProvider extends Object {
  27. protected static
  28. $instance = NULL;
  29. public
  30. $impl = NULL;
  31. static function __static() {
  32. self::$instance= new self();
  33. // Workaround for bugs in older PHP versions, see MD5HexHashImplementation's
  34. // class apidoc for an explanation. Earlier versions returned LONG_MAX for
  35. // hex numbers larger than LONG_MAX. Use 2^64 + 1 as hex literal and see if
  36. // it's "truncated", using the slower hexdec(md5()) implementation then.
  37. if (LONG_MAX === @0x20c49ba5e35423) {
  38. $impl= XPClass::forName('util.collections.MD5HexHashImplementation')->newInstance();
  39. } else {
  40. $impl= new MD5HashImplementation();
  41. }
  42. self::$instance->setImplementation($impl);
  43. }
  44. /**
  45. * Constructor
  46. *
  47. */
  48. protected function __construct() {
  49. }
  50. /**
  51. * Retrieve sole instance of this object
  52. *
  53. * @return util.collections.HashProvider
  54. */
  55. public static function getInstance() {
  56. return self::$instance;
  57. }
  58. /**
  59. * Returns hash for a given string
  60. *
  61. * @param string str
  62. * @return int
  63. */
  64. public static function hashOf($str) {
  65. return self::$instance->impl->hashOf($str);
  66. }
  67. /**
  68. * Set hashing implementation
  69. *
  70. * @param util.collections.HashImplementation impl
  71. * @throws lang.IllegalArgumentException when impl is not a HashImplementation
  72. */
  73. public function setImplementation(HashImplementation $impl) {
  74. $this->impl= $impl;
  75. }
  76. /**
  77. * Get hashing implementation
  78. *
  79. * @return util.collections.HashImplementation
  80. */
  81. public function getImplementation() {
  82. return $this->impl;
  83. }
  84. }
  85. ?>