PageRenderTime 157ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/PhpBuf/Base128.php

http://github.com/undr/phpbuf
PHP | 76 lines | 49 code | 5 blank | 22 comment | 8 complexity | afe7760cb6f20531b4b036cfbbd8926b MD5 | raw file
  1. <?php
  2. /**
  3. * @author Andrey Lepeshkin (lilipoper@gmail.com)
  4. * @link http://code.google.com/p/php-protobuf/
  5. *
  6. */
  7. class PhpBuf_Base128 {
  8. private function __construct() {}
  9. /**
  10. * Encode value into varint string
  11. *
  12. * @param integer $value
  13. * @return string
  14. */
  15. public static function encode($value) {
  16. if(!is_integer($value) || $value < 0) {
  17. throw new PhpBuf_Base128_Exception("value mast be unsigned integer");
  18. }
  19. if($value <= 127) {
  20. return chr($value);
  21. }
  22. $result = '';
  23. $bin = decbin($value);
  24. $bit8 = '1';
  25. $index = strlen($bin);
  26. $substrLenght = 7;
  27. while (0 < $index) {
  28. if($index < 8) {
  29. $bit8 = '0';
  30. }
  31. $index = $index - 7;
  32. if($index < 0) {
  33. $substrLenght = $substrLenght + $index; $index = 0;
  34. }
  35. $bin7bit = substr($bin, $index, $substrLenght);
  36. $dec = bindec($bit8 . $bin7bit);
  37. $char = chr($dec);
  38. $result = $result . $char;
  39. }
  40. return $result;
  41. }
  42. /**
  43. * Encode value and write to PhpBuf_IO_Writer_Interface
  44. *
  45. * @param PhpBuf_IO_Writer_Interface $writer
  46. */
  47. public static function encodeToWriter(PhpBuf_IO_Writer_Interface $writer, $value) {
  48. $writer->writeBytes(self::encode($value));
  49. }
  50. /**
  51. * Decode varint encoded string from PhpBuf_IO_Writer_Interface
  52. *
  53. * @param PhpBuf_IO_Reader_Interface $value
  54. * @return integer
  55. */
  56. public static function decodeFromReader(PhpBuf_IO_Reader_Interface $reader) {
  57. $continue = true;
  58. $result = '';
  59. while ($continue) {
  60. $byte = unpack('C', $reader->getByte());
  61. $bin = sprintf('%b', $byte[1]);
  62. if(strlen($bin) < 8) {
  63. $continue = false;
  64. }
  65. $bin = str_pad($bin, 8, '0', STR_PAD_LEFT);
  66. $bin7bit = substr($bin, 1, 7);
  67. $result = $bin7bit . $result;
  68. }
  69. return bindec($result);
  70. }
  71. }