GenericFixedWidthReader.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Provides fixed-width byte sizes for reading fixed-width character sets.
  11. *
  12. * @package Swift
  13. * @subpackage Encoder
  14. * @author Chris Corbyn
  15. * @author Xavier De Cock <xdecock@gmail.com>
  16. */
  17. class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader
  18. {
  19. /**
  20. * The number of bytes in a single character.
  21. *
  22. * @var integer
  23. */
  24. private $_width;
  25. /**
  26. * Creates a new GenericFixedWidthReader using $width bytes per character.
  27. *
  28. * @param integer $width
  29. */
  30. public function __construct($width)
  31. {
  32. $this->_width = $width;
  33. }
  34. /**
  35. * Returns the complete character map.
  36. *
  37. * @param string $string
  38. * @param integer $startOffset
  39. * @param array $currentMap
  40. * @param mixed $ignoredChars
  41. *
  42. * @return integer
  43. */
  44. public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
  45. {
  46. $strlen = strlen($string);
  47. // % and / are CPU intensive, so, maybe find a better way
  48. $ignored = $strlen % $this->_width;
  49. $ignoredChars = substr($string, - $ignored);
  50. $currentMap = $this->_width;
  51. return ($strlen - $ignored) / $this->_width;
  52. }
  53. /**
  54. * Returns the mapType.
  55. *
  56. * @return integer
  57. */
  58. public function getMapType()
  59. {
  60. return self::MAP_TYPE_FIXED_LEN;
  61. }
  62. /**
  63. * Returns an integer which specifies how many more bytes to read.
  64. *
  65. * A positive integer indicates the number of more bytes to fetch before invoking
  66. * this method again.
  67. *
  68. * A value of zero means this is already a valid character.
  69. * A value of -1 means this cannot possibly be a valid character.
  70. *
  71. * @param string $bytes
  72. * @param integer $size
  73. *
  74. * @return integer
  75. */
  76. public function validateByteSequence($bytes, $size)
  77. {
  78. $needed = $this->_width - $size;
  79. return ($needed > -1) ? $needed : -1;
  80. }
  81. /**
  82. * Returns the number of bytes which should be read to start each character.
  83. *
  84. * @return integer
  85. */
  86. public function getInitialByteSize()
  87. {
  88. return $this->_width;
  89. }
  90. }