Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

52
LINES

< > BotCompany Repo | #1035731 // HuffmanByteArray - Huffman codec [OK]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (15231L/90K).

persistable sclass HuffmanByteArray is BitIO {
  settable byte[] data;
  gettable int[] histogram;
  gettable HuffmanTreeMaker tm;
  gettable new HuffmanTree tree;
  
  // options
  settable bool startWithMagicCode;
  settable S magicCode = "HUF1";
  
  *(byte[] *data) {}

  public void readWrite(BitHead head) {
    if (head.writeMode() && histogram == null) {
      histogram = byteHistogramArray(data);
      tm = new HuffmanTreeMaker;
      tm.importByteHistogram(histogram);
      tree = tm!;
    }

    // Part 1 (magic code)
    if (startWithMagicCode)
      head.exchangeASCII(magicCode);
  
    // Part 2 (Huffman character tree)
    tree.readWrite(head);

    // Part 3a (size)

    new VariableSizeUIntForBitHead().chunkSize(3).readWrite(head, -> data.length, size -> data = new byte[size]);
    //print("length " + data.length);
    
    // Part 3 (text)
    if (head.writeMode()) {
      fOr (b : data)
        tree.writeCharacter(b, head);
    }
    
    if (head.readMode()) {
      for i over data: {
        if (head.isEOF()) break;
        data[i] = toUByte(tree.readSymbol(head));
      }
    }
  }
  
  byte[] get() { ret data; }
  
  // update selfType
  public selfType fromByteArray(byte[] data) { BitIO.super.fromByteArray(data); this; }
  public selfType load(byte[] data) { BitIO.super.load(data); this; }
}

Author comment

Began life as a copy of #1035674

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mqqgnosmbjvj, onxytkatvevr

No comments. add comment

Snippet ID: #1035731
Snippet name: HuffmanByteArray - Huffman codec [OK]
Eternal ID of this version: #1035731/11
Text MD5: 53e855445a153fb8f77787f862df7555
Transpilation MD5: e9e4978b3f68996a4e9f87e3509db72d
Author: stefan
Category: javax / compression
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-07-15 20:56:00
Source code size: 1385 bytes / 52 lines
Pitched / IR pitched: No / No
Views / Downloads: 93 / 192
Version history: 10 change(s)
Referenced in: [show references]