1 module psd.rle;
2 import psd.layer;
3 import utils.io;
4 import std.exception;
5 import std.format;
6 
7 /**
8     Taken from psd_sdk
9 
10     https://github.com/MolecularMatters/psd_sdk/blob/master/src/Psd/PsdDecompressRle.cpp#L18
11 */
12 void decodeRLE(ubyte[] source, ubyte[] destination) {
13     import core.stdc..string : memset, memcpy;
14 
15     ubyte* dest = destination.ptr;
16     ubyte* src = source.ptr;
17     uint bytesRead = 0u;
18     uint offset = 0u;
19     size_t size = destination.length;
20     
21     while (offset < size)
22     {
23         const ubyte tag = *src++;
24         ++bytesRead;
25 
26         if (tag == 0x80)
27         {
28             // tag == -128 (0x80) is a no-op
29         }
30         // 0x81 - 0XFF
31         else if (tag > 0x80)
32         {
33             // next 257-tag bytes are replicated from the next source tag
34             const uint count = cast(uint)(257 - tag);
35             ubyte data = *src++;
36 
37             memset(dest + offset, data, count);
38             offset += count;
39 
40             ++bytesRead;
41         }
42         // 0x00 - 0x7F
43         else
44         {
45             // copy next tag+1 bytes 1-by-1
46             const uint count = cast(uint)(tag + 1);
47             
48             memcpy(dest + offset, src, count);
49 
50             src += count;
51             offset += count;
52 
53             bytesRead += count;
54         }
55     }
56 }