LzwCompressionTest.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. use Mike42\GfxPhp\Util\LzwCompression;
  3. use Mike42\GfxPhp\Util\LzwDecodeBuffer;
  4. use PHPUnit\Framework\TestCase;
  5. class LzwCompressionTest extends TestCase
  6. {
  7. /*
  8. * Known-good GIF-LZW strings from Wikipedia
  9. * for 3x5 image like the one shown below.
  10. *
  11. * https://en.wikipedia.org/wiki/GIF
  12. *╭──────╮
  13. *│██░░░░│ ██ = 0x40
  14. *│░░██░░│ ░░ = 0xFF
  15. *│░░░░░░│
  16. *│░░░░░░│
  17. *│░░░░░░│
  18. *╰──────╯
  19. */
  20. const compressedChars = [0x00, 0x51, 0xFC, 0x1B, 0x28, 0x70, 0xA0, 0xC1, 0x83, 0x01, 0x01];
  21. const uncompressedChars = [0x28, 0xFF, 0xFF, 0xFF, 0x28, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
  22. public function testLzwDecodeBufferBytes()
  23. {
  24. // Ensure we can extract numbers from input stream
  25. $contents = "ABCD";
  26. $buffer = new LzwDecodeBuffer($contents);
  27. $this -> assertEquals(65, $buffer -> read(8));
  28. $this -> assertEquals(66, $buffer -> read(8));
  29. $this -> assertEquals(67, $buffer -> read(8));
  30. $this -> assertEquals(68, $buffer -> read(8));
  31. $this -> assertEquals(false, $buffer -> read(8));
  32. }
  33. public function testLzwDecodeBufferBits()
  34. {
  35. // Ensure we can extract numbers of strange lengths from input stream
  36. $inp = pack("C*", ... LzwCompressionTest::compressedChars);
  37. $buffer = new LzwDecodeBuffer($inp);
  38. $this -> assertEquals(0x100, $buffer -> read(9));
  39. $this -> assertEquals(0x028, $buffer -> read(9));
  40. $this -> assertEquals(0x0FF, $buffer -> read(9));
  41. $this -> assertEquals(0x103, $buffer -> read(9));
  42. $this -> assertEquals(0x102, $buffer -> read(9));
  43. $this -> assertEquals(0x103, $buffer -> read(9));
  44. $this -> assertEquals(0x106, $buffer -> read(9));
  45. $this -> assertEquals(0x107, $buffer -> read(9));
  46. $this -> assertEquals(0x101, $buffer -> read(9));
  47. $this -> assertEquals(false, $buffer -> read(9));
  48. }
  49. public function testLzwDecompression()
  50. {
  51. // Test de-compression
  52. $compressedStr = pack("C*", ... LzwCompressionTest::compressedChars);
  53. $uncompressedStr = LzwCompression::decompress($compressedStr, 8);
  54. $this -> assertEquals(LzwCompressionTest::uncompressedChars, array_values(unpack("C*", $uncompressedStr)));
  55. }
  56. public function testLzwCompression()
  57. {
  58. // Test de-compression
  59. $uncompressedStr = pack("C*", ... LzwCompressionTest::uncompressedChars);
  60. $compressedStr = LzwCompression::compress($uncompressedStr, 8);
  61. $this -> assertEquals(LzwCompressionTest::compressedChars, array_values(unpack("C*", $compressedStr)));
  62. }
  63. }