File: pc_bytes.c

package info (click to toggle)
pgpointcloud 1.2.5-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,892 kB
  • sloc: sql: 40,767; ansic: 11,045; xml: 935; makefile: 297; cpp: 282; perl: 248; python: 178; sh: 92
file content (1823 lines) | stat: -rw-r--r-- 44,685 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
/***********************************************************************
 * pc_bytes.c
 *
 *  Support for "dimensional compression", which is a catch-all
 *  term for applying compression separately on each dimension
 *  of a PCPATCH collection of PCPOINTS.
 *
 *  Depending on the character of the data, one of these schemes
 *  will be used:
 *
 *  - run-length encoding
 *  - significant-bit removal
 *  - deflate
 *
 *  PgSQL Pointcloud is free and open source software provided
 *  by the Government of Canada
 *  Copyright (c) 2013 Natural Resources Canada
 *
 ***********************************************************************/

#include "pc_api_internal.h"
#include "zlib.h"
#include <assert.h>
#include <float.h>
#include <stdarg.h>

void pc_bytes_free(PCBYTES pcb)
{
  if (!pcb.readonly)
    pcfree(pcb.bytes);
}

int pc_bytes_empty(const PCBYTES *pcb)
{
  return pcb->npoints == 0 || pcb->bytes == NULL || pcb->size == 0;
}

PCBYTES
pc_bytes_make(const PCDIMENSION *dim, uint32_t npoints)
{
  PCBYTES pcb;
  pcb.size = dim->size * npoints;
  pcb.bytes = pcalloc(pcb.size);
  pcb.npoints = npoints;
  pcb.interpretation = dim->interpretation;
  pcb.compression = PC_DIM_NONE;
  pcb.readonly = PC_FALSE;
  return pcb;
}

static PCBYTES pc_bytes_clone(PCBYTES pcb)
{
  PCBYTES pcbnew = pcb;
  if (!pc_bytes_empty(&pcb))
  {
    pcbnew.bytes = pcalloc(pcb.size);
    memcpy(pcbnew.bytes, pcb.bytes, pcb.size);
  }
  pcbnew.readonly = PC_FALSE;
  return pcbnew;
}

PCBYTES
pc_bytes_encode(PCBYTES pcb, int compression)
{
  PCBYTES epcb;
  switch (compression)
  {
  case PC_DIM_RLE:
  {
    epcb = pc_bytes_run_length_encode(pcb);
    break;
  }
  case PC_DIM_SIGBITS:
  {
    epcb = pc_bytes_sigbits_encode(pcb);
    break;
  }
  case PC_DIM_ZLIB:
  {
    epcb = pc_bytes_zlib_encode(pcb);
    break;
  }
  case PC_DIM_NONE:
  {
    epcb = pc_bytes_clone(pcb);
    break;
  }
  default:
  {
    pcerror("%s: Uh oh", __func__);
  }
  }
  return epcb;
}

PCBYTES
pc_bytes_decode(PCBYTES epcb)
{
  PCBYTES pcb;
  switch (epcb.compression)
  {
  case PC_DIM_RLE:
  {
    pcb = pc_bytes_run_length_decode(epcb);
    break;
  }
  case PC_DIM_SIGBITS:
  {
    pcb = pc_bytes_sigbits_decode(epcb);
    break;
  }
  case PC_DIM_ZLIB:
  {
    pcb = pc_bytes_zlib_decode(epcb);
    break;
  }
  case PC_DIM_NONE:
  {
    pcb = pc_bytes_clone(epcb);
    break;
  }
  default:
  {
    pcerror("%s: Uh oh", __func__);
  }
  }
  return pcb;
}

/**
 * How many distinct runs of values are there in this array?
 * One? Two? Five? Great news for run-length encoding!
 * N? Not so great news.
 */
uint32_t pc_bytes_run_count(const PCBYTES *pcb)
{
  int i;
  const uint8_t *ptr0;
  const uint8_t *ptr1;
  size_t size = pc_interpretation_size(pcb->interpretation);
  uint32_t runcount = 1;

  for (i = 1; i < pcb->npoints; i++)
  {
    ptr0 = pcb->bytes + (i - 1) * size;
    ptr1 = pcb->bytes + i * size;
    if (memcmp(ptr0, ptr1, size) != 0)
    {
      runcount++;
    }
  }
  return runcount;
}

/**
 * Take the uncompressed bytes and run-length encode (RLE) them.
 * Structure of RLE array as:
 * <uint8> number of elements
 * <val> value
 * ...
 */
PCBYTES
pc_bytes_run_length_encode(const PCBYTES pcb)
{
  int i;
  uint8_t *buf, *bufptr;
  const uint8_t *bytesptr;
  const uint8_t *runstart;
  uint8_t *bytes_rle;
  size_t size = pc_interpretation_size(pcb.interpretation);
  uint8_t runlength = 1;
  PCBYTES pcbout = pcb;

  /* Allocate more size than we need (worst case: n elements, n runs) */
  buf = pcalloc(pcb.npoints * size + sizeof(uint8_t) * pcb.npoints);
  bufptr = buf;

  /* First run starts at the start! */
  runstart = pcb.bytes;

  for (i = 1; i <= pcb.npoints; i++)
  {
    bytesptr = pcb.bytes + i * size;
    /* Run continues... */
    if (i < pcb.npoints && runlength < 255 &&
        memcmp(runstart, bytesptr, size) == 0)
    {
      runlength++;
    }
    else
    {
      /* Write # elements in the run */
      *bufptr = runlength;
      bufptr += 1;
      /* Write element value */
      memcpy(bufptr, runstart, size);
      bufptr += size;
      /* Advance read head */
      runstart = bytesptr;
      runlength = 1;
    }
  }
  /* Length of buffer */
  pcbout.size = (bufptr - buf);
  /* Write out shortest buffer possible */
  bytes_rle = pcalloc(pcbout.size);
  memcpy(bytes_rle, buf, pcbout.size);
  pcfree(buf);
  /* We're going to replace the current buffer */
  pcbout.bytes = bytes_rle;
  pcbout.compression = PC_DIM_RLE;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * Take the compressed bytes and run-length dencode (RLE) them.
 * Structure of RLE array is:
 * <uint8> number of elements
 * <val> value
 * ...
 */
PCBYTES
pc_bytes_run_length_decode(const PCBYTES pcb)
{
  int i, n;
  uint8_t *bytes;
  uint8_t *bytes_ptr;
  const uint8_t *bytes_rle_ptr = pcb.bytes;
  const uint8_t *bytes_rle_end = pcb.bytes + pcb.size;

  size_t size = pc_interpretation_size(pcb.interpretation);
  size_t size_out;
  uint32_t npoints = 0;
  PCBYTES pcbout = pcb;

  assert(pcb.compression == PC_DIM_RLE);

  /* Count up how big our output is. */
  while (bytes_rle_ptr < bytes_rle_end)
  {
    npoints += *bytes_rle_ptr;
    bytes_rle_ptr += 1 + size;
  }

  assert(npoints == pcb.npoints);

  /* Alocate output and fill it up */
  size_out = size * npoints;
  bytes = pcalloc(size_out);
  bytes_ptr = bytes;
  bytes_rle_ptr = pcb.bytes;
  while (bytes_rle_ptr < bytes_rle_end)
  {
    n = *bytes_rle_ptr;
    bytes_rle_ptr += 1;
    for (i = 0; i < n; i++)
    {
      memcpy(bytes_ptr, bytes_rle_ptr, size);
      bytes_ptr += size;
    }
    bytes_rle_ptr += size;
  }
  pcbout.compression = PC_DIM_NONE;
  pcbout.size = size_out;
  pcbout.bytes = bytes;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * RLE bytes consist of a <byte:count><word:value><byte:count><word:value>
 * pattern so we can hope from word to word and flip each one in place.
 */
static PCBYTES pc_bytes_run_length_flip_endian(PCBYTES pcb)
{
  int n;
  uint8_t *bytes_ptr = pcb.bytes;
  uint8_t *end_ptr = pcb.bytes + pcb.size;
  uint8_t tmp;
  size_t size = pc_interpretation_size(pcb.interpretation);

  assert(pcb.compression == PC_DIM_RLE);
  assert(pcb.npoints > 0);

  /* If the type isn't multibyte, it doesn't need flipping */
  if (size < 2)
    return pcb;

  /* Don't try to modify read-only memory, make some fresh memory */
  if (pcb.readonly == PC_TRUE)
  {
    uint8_t *oldbytes = pcb.bytes;
    pcb.bytes = pcalloc(pcb.size);
    memcpy(pcb.bytes, oldbytes, pcb.size);
    pcb.readonly = PC_FALSE;
  }

  bytes_ptr++; /* Advance past count */

  /* Visit each entry and flip the word, skip the count */
  while (bytes_ptr < end_ptr)
  {

    /* Swap the bytes in a way that makes sense for this word size */
    for (n = 0; n < size / 2; n++)
    {
      tmp = bytes_ptr[n];
      bytes_ptr[n] = bytes_ptr[size - n - 1];
      bytes_ptr[size - n - 1] = tmp;
    }

    /* Move past this word */
    bytes_ptr += size;
    /* Advance past next count */
    bytes_ptr++;
  }

  return pcb;
}

uint8_t pc_bytes_sigbits_count_8(const PCBYTES *pcb, uint32_t *nsigbits)
{
  static uint8_t nbits = 8;
  uint8_t *bytes = (uint8_t *)(pcb->bytes);
  uint8_t elem_and = bytes[0];
  uint8_t elem_or = bytes[0];
  uint32_t commonbits = nbits;
  int i;

  for (i = 0; i < pcb->npoints; i++)
  {
    elem_and &= bytes[i];
    elem_or |= bytes[i];
  }

  while (elem_and != elem_or)
  {
    elem_and >>= 1;
    elem_or >>= 1;
    commonbits -= 1;
  }
  elem_and <<= nbits - commonbits;
  if (nsigbits)
    *nsigbits = commonbits;
  return elem_and;
}

uint16_t pc_bytes_sigbits_count_16(const PCBYTES *pcb, uint32_t *nsigbits)
{
  static int nbits = 16;
  uint16_t *bytes = (uint16_t *)(pcb->bytes);
  uint16_t elem_and = bytes[0];
  uint16_t elem_or = bytes[0];
  uint32_t commonbits = nbits;
  int i;

  for (i = 0; i < pcb->npoints; i++)
  {
    elem_and &= bytes[i];
    elem_or |= bytes[i];
  }

  while (elem_and != elem_or)
  {
    elem_and >>= 1;
    elem_or >>= 1;
    commonbits -= 1;
  }
  elem_and <<= nbits - commonbits;
  if (nsigbits)
    *nsigbits = commonbits;
  return elem_and;
}

uint32_t pc_bytes_sigbits_count_32(const PCBYTES *pcb, uint32_t *nsigbits)
{
  static int nbits = 32;
  uint32_t *bytes = (uint32_t *)(pcb->bytes);
  uint32_t elem_and = bytes[0];
  uint32_t elem_or = bytes[0];
  uint32_t commonbits = nbits;
  int i;

  for (i = 0; i < pcb->npoints; i++)
  {
    elem_and &= bytes[i];
    elem_or |= bytes[i];
  }

  while (elem_and != elem_or)
  {
    elem_and >>= 1;
    elem_or >>= 1;
    commonbits -= 1;
  }
  elem_and <<= nbits - commonbits;
  if (nsigbits)
    *nsigbits = commonbits;
  return elem_and;
}

uint64_t pc_bytes_sigbits_count_64(const PCBYTES *pcb, uint32_t *nsigbits)
{
  static int nbits = 64;
  uint64_t *bytes = (uint64_t *)(pcb->bytes);
  uint64_t elem_and = bytes[0];
  uint64_t elem_or = bytes[0];
  uint32_t commonbits = nbits;
  int i;

  for (i = 0; i < pcb->npoints; i++)
  {
    elem_and &= bytes[i];
    elem_or |= bytes[i];
  }

  while (elem_and != elem_or)
  {
    elem_and >>= 1;
    elem_or >>= 1;
    commonbits -= 1;
  }
  elem_and <<= nbits - commonbits;
  if (nsigbits)
    *nsigbits = commonbits;
  return elem_and;
}

/**
 * How many bits are shared by all elements of this array?
 */
uint32_t pc_bytes_sigbits_count(const PCBYTES *pcb)
{
  size_t size = pc_interpretation_size(pcb->interpretation);
  uint32_t nbits = -1;
  switch (size)
  {
  case 1: /* INT8, UINT8 */
    pc_bytes_sigbits_count_8(pcb, &nbits);
    break;
  case 2: /* INT16, UINT16 */
    pc_bytes_sigbits_count_16(pcb, &nbits);
    break;
  case 4: /* INT32, UINT32 */
    pc_bytes_sigbits_count_32(pcb, &nbits);
    break;
  case 8: /* DOUBLE, INT64, UINT64 */
    pc_bytes_sigbits_count_64(pcb, &nbits);
    break;
  default:
    pcerror("%s: cannot handle interpretation %d", __func__,
            pcb->interpretation);
    return -1;
  }
  return nbits;
}

/**
 * Encoded array:
 * <uint8> number of bits per unique section
 * <uint8> common bits for the array
 * [n_bits]... unique bits packed in
 * Size of encoded array comes out in ebytes_size.
 */
PCBYTES
pc_bytes_sigbits_encode_8(const PCBYTES pcb, uint8_t commonvalue,
                          uint8_t commonbits)
{
  int i;
  int shift;
  uint8_t *bytes = (uint8_t *)(pcb.bytes);
  /* How wide are our words? */
  static int bitwidth = 8;
  /* How wide are our unique values? */
  int nbits = bitwidth - commonbits;
  /* Size of output buffer (#bits/8+1remainder+2metadata) */
  size_t size_out = (nbits * pcb.npoints / 8) + 3;
  uint8_t *bytes_out = pcalloc(size_out);
  /* Use this to zero out the parts that are common */
  uint8_t mask = (0xFF >> commonbits);
  /* Write head */
  uint8_t *byte_ptr = bytes_out;
  /* What bit are we writing to now? */
  int bit = bitwidth;
  /* Write to... */
  PCBYTES pcbout = pcb;

  /* Number of unique bits goes up front */
  *byte_ptr = nbits;
  byte_ptr++;
  /* The common value we'll add the unique values to */
  *byte_ptr = commonvalue;
  byte_ptr++;

  /* All the values are the same... */
  if (bitwidth == commonbits)
  {
    pcbout.size = size_out;
    pcbout.bytes = bytes_out;
    pcbout.compression = PC_DIM_SIGBITS;
    pcbout.readonly = PC_FALSE;
    return pcbout;
  }

  for (i = 0; i < pcb.npoints; i++)
  {
    uint8_t val = bytes[i];
    /* Clear off common parts */
    val &= mask;
    /* How far to move unique parts to get to write head? */
    shift = bit - nbits;
    /* If positive, we can fit this part into the current word */
    if (shift >= 0)
    {
      val <<= shift;
      *byte_ptr |= val;
      bit -= nbits;
      if (bit <= 0)
      {
        bit = bitwidth;
        byte_ptr++;
      }
    }
    /* If negative, then we need to split this part across words */
    else
    {
      /* First the bit into the current word */
      uint8_t v = val;
      int s = abs(shift);
      v >>= s;
      *byte_ptr |= v;
      /* The reset to write the next word */
      bit = bitwidth;
      byte_ptr++;
      v = val;
      shift = bit - s;
      /* But only those parts we didn't already write */
      v <<= shift;
      *byte_ptr |= v;
      bit -= s;
    }
  }

  pcbout.size = size_out;
  pcbout.bytes = bytes_out;
  pcbout.compression = PC_DIM_SIGBITS;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * Encoded array:
 * <uint16> number of bits per unique section
 * <uint16> common bits for the array
 * [n_bits]... unique bits packed in
 * Size of encoded array comes out in ebytes_size.
 */
PCBYTES
pc_bytes_sigbits_encode_16(const PCBYTES pcb, uint16_t commonvalue,
                           uint8_t commonbits)
{
  int i;
  int shift;
  uint16_t *bytes = (uint16_t *)(pcb.bytes);

  /* How wide are our words? */
  static int bitwidth = 16;
  /* How wide are our unique values? */
  int nbits = bitwidth - commonbits;
  /* Size of output buffer (#bits/8+1remainder+4metadata)  */
  size_t size_out_raw = (nbits * pcb.npoints / 8) + 1 + 4;
  /* Make sure buffer is size to hold all our words */
  size_t size_out = size_out_raw + (size_out_raw % 2);
  uint8_t *bytes_out = pcalloc(size_out);
  /* Use this to zero out the parts that are common */
  uint16_t mask = (0xFFFF >> commonbits);
  /* Write head */
  uint16_t *byte_ptr = (uint16_t *)(bytes_out);
  /* What bit are we writing to now? */
  int bit = bitwidth;
  /* Write to... */
  PCBYTES pcbout = pcb;

  /* Number of unique bits goes up front */
  *byte_ptr = nbits;
  byte_ptr++;
  /* The common value we'll add the unique values to */
  *byte_ptr = commonvalue;
  byte_ptr++;

  /* All the values are the same... */
  if (bitwidth == commonbits)
  {
    pcbout.size = size_out;
    pcbout.bytes = bytes_out;
    pcbout.compression = PC_DIM_SIGBITS;
    pcbout.readonly = PC_FALSE;
    return pcbout;
  }

  for (i = 0; i < pcb.npoints; i++)
  {
    uint16_t val = bytes[i];
    /* Clear off common parts */
    val &= mask;
    /* How far to move unique parts to get to write head? */
    shift = bit - nbits;
    /* If positive, we can fit this part into the current word */
    if (shift >= 0)
    {
      val <<= shift;
      *byte_ptr |= val;
      bit -= nbits;
      if (bit <= 0)
      {
        bit = bitwidth;
        byte_ptr++;
      }
    }
    /* If negative, then we need to split this part across words */
    else
    {
      /* First the bit into the current word */
      uint16_t v = val;
      int s = abs(shift);
      v >>= s;
      *byte_ptr |= v;
      /* The reset to write the next word */
      bit = bitwidth;
      byte_ptr++;
      v = val;
      shift = bit - s;
      /* But only those parts we didn't already write */
      v <<= shift;
      *byte_ptr |= v;
      bit -= s;
    }
  }

  pcbout.size = size_out;
  pcbout.bytes = bytes_out;
  pcbout.compression = PC_DIM_SIGBITS;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * Encoded array:
 * <uint32> number of bits per unique section
 * <uint32> common bits for the array
 * [n_bits]... unique bits packed in
 * Size of encoded array comes out in ebytes_size.
 */
PCBYTES
pc_bytes_sigbits_encode_32(const PCBYTES pcb, uint32_t commonvalue,
                           uint8_t commonbits)
{
  int i;
  int shift;
  uint32_t *bytes = (uint32_t *)(pcb.bytes);

  /* How wide are our words? */
  static int bitwidth = 32;
  /* How wide are our unique values? */
  int nbits = bitwidth - commonbits;
  /* Size of output buffer (#bits/8+1remainder+8metadata) */
  size_t size_out_raw = (nbits * pcb.npoints / 8) + 1 + 8;
  size_t size_out = size_out_raw + (4 - (size_out_raw % 4));
  uint8_t *bytes_out = pcalloc(size_out);
  /* Use this to zero out the parts that are common */
  uint32_t mask = (0xFFFFFFFF >> commonbits);
  /* Write head */
  uint32_t *byte_ptr = (uint32_t *)bytes_out;
  /* What bit are we writing to now? */
  int bit = bitwidth;
  /* Write to... */
  PCBYTES pcbout = pcb;

  /* Number of unique bits goes up front */
  *byte_ptr = nbits;
  byte_ptr++;
  /* The common value we'll add the unique values to */
  *byte_ptr = commonvalue;
  byte_ptr++;

  /* All the values are the same... */
  if (bitwidth == commonbits)
  {
    pcbout.size = size_out;
    pcbout.bytes = bytes_out;
    pcbout.compression = PC_DIM_SIGBITS;
    pcbout.readonly = PC_FALSE;
    return pcbout;
  }

  for (i = 0; i < pcb.npoints; i++)
  {
    uint32_t val = bytes[i];
    /* Clear off common parts */
    val &= mask;
    /* How far to move unique parts to get to write head? */
    shift = bit - nbits;
    /* If positive, we can fit this part into the current word */
    if (shift >= 0)
    {
      val <<= shift;
      *byte_ptr |= val;
      bit -= nbits;
      if (bit <= 0)
      {
        bit = bitwidth;
        byte_ptr++;
      }
    }
    /* If negative, then we need to split this part across words */
    else
    {
      /* First the bit into the current word */
      uint32_t v = val;
      int s = abs(shift);
      v >>= s;
      *byte_ptr |= v;
      /* The reset to write the next word */
      bit = bitwidth;
      byte_ptr++;
      v = val;
      shift = bit - s;
      /* But only those parts we didn't already write */
      v <<= shift;
      *byte_ptr |= v;
      bit -= s;
    }
  }

  pcbout.size = size_out;
  pcbout.bytes = bytes_out;
  pcbout.compression = PC_DIM_SIGBITS;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * Encoded array:
 * <uint64> number of bits per unique section
 * <uint64> common bits for the array
 * [n_bits]... unique bits packed in
 * Size of encoded array comes out in ebytes_size.
 */
PCBYTES
pc_bytes_sigbits_encode_64(const PCBYTES pcb, uint64_t commonvalue,
                           uint8_t commonbits)
{
  int i;
  int shift;
  uint64_t *bytes = (uint64_t *)(pcb.bytes);

  /* How wide are our words? */
  static int bitwidth = 64;
  /* How wide are our unique values? */
  int nbits = bitwidth - commonbits;
  /* Size of output buffer (#bits/8+1remainder+16metadata) */
  size_t size_out_raw = (nbits * pcb.npoints / 8) + 1 + 16;
  size_t size_out = size_out_raw + (8 - (size_out_raw % 8));
  uint8_t *bytes_out = pcalloc(size_out);
  /* Use this to zero out the parts that are common */
  uint64_t mask = (0xFFFFFFFFFFFFFFFF >> commonbits);
  /* Write head */
  uint64_t *byte_ptr = (uint64_t *)bytes_out;
  /* What bit are we writing to now? */
  int bit = bitwidth;
  /* Write to... */
  PCBYTES pcbout = pcb;

  /* Number of unique bits goes up front */
  *byte_ptr = nbits;
  byte_ptr++;
  /* The common value we'll add the unique values to */
  *byte_ptr = commonvalue;
  byte_ptr++;

  /* All the values are the same... */
  if (bitwidth == commonbits)
  {
    pcbout.size = size_out;
    pcbout.bytes = bytes_out;
    pcbout.compression = PC_DIM_SIGBITS;
    pcbout.readonly = PC_FALSE;
    return pcbout;
  }

  for (i = 0; i < pcb.npoints; i++)
  {
    uint64_t val = bytes[i];
    /* Clear off common parts */
    val &= mask;
    /* How far to move unique parts to get to write head? */
    shift = bit - nbits;
    /* If positive, we can fit this part into the current word */
    if (shift >= 0)
    {
      val <<= shift;
      *byte_ptr |= val;
      bit -= nbits;
      if (bit <= 0)
      {
        bit = bitwidth;
        byte_ptr++;
      }
    }
    /* If negative, then we need to split this part across words */
    else
    {
      /* First the bit into the current word */
      uint64_t v = val;
      int s = abs(shift);
      v >>= s;
      *byte_ptr |= v;
      /* The reset to write the next word */
      bit = bitwidth;
      byte_ptr++;
      v = val;
      shift = bit - s;
      /* But only those parts we didn't already write */
      v <<= shift;
      *byte_ptr |= v;
      bit -= s;
    }
  }

  pcbout.size = size_out;
  pcbout.bytes = bytes_out;
  pcbout.compression = PC_DIM_SIGBITS;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

/**
 * Convert a raw byte array into with common bits stripped and the
 * remaining bits packed in.
 * <uint8|uint16|uint32> number of bits per unique section
 * <uint8|uint16|uint32> common bits for the array
 * [n_bits]... unique bits packed in
 * Size of encoded array comes out in ebytes_size.
 */
PCBYTES
pc_bytes_sigbits_encode(const PCBYTES pcb)
{
  size_t size = pc_interpretation_size(pcb.interpretation);
  uint32_t nbits;
  switch (size)
  {
  case 1:
  {
    uint8_t commonvalue = pc_bytes_sigbits_count_8(&pcb, &nbits);
    return pc_bytes_sigbits_encode_8(pcb, commonvalue, nbits);
  }
  case 2:
  {
    uint16_t commonvalue = pc_bytes_sigbits_count_16(&pcb, &nbits);
    return pc_bytes_sigbits_encode_16(pcb, commonvalue, nbits);
  }
  case 4:
  {
    uint32_t commonvalue = pc_bytes_sigbits_count_32(&pcb, &nbits);
    return pc_bytes_sigbits_encode_32(pcb, commonvalue, nbits);
  }
  case 8:
  {
    uint64_t commonvalue = pc_bytes_sigbits_count_64(&pcb, &nbits);
    return pc_bytes_sigbits_encode_64(pcb, commonvalue, nbits);
  }
  default:
  {
    pcerror("%s: bits_encode cannot handle interpretation %d", __func__,
            pcb.interpretation);
  }
  }
  pcerror("Uh Oh");
  return pcb;
}

static PCBYTES pc_bytes_sigbits_flip_endian(const PCBYTES pcb)
{
  int n;
  uint8_t tmp1, tmp2;
  size_t size = pc_interpretation_size(pcb.interpretation);
  uint8_t *b1 = pcb.bytes;
  uint8_t *b2 = pcb.bytes + size;

  /* If it's not multi-byte words, it doesn't need flipping */
  if (size < 2)
    return pcb;

  /* We only need to flip the first two words, */
  /* which are the common bit count and common bits word */
  for (n = 0; n < size / 2; n++)
  {
    /* Flip bit count */
    tmp1 = b1[n];
    b1[n] = b1[size - n - 1];
    b1[size - n - 1] = tmp1;
    /* Flip common bits */
    tmp2 = b2[n];
    b2[n] = b2[size - n - 1];
    b2[size - n - 1] = tmp2;
  }

  return pcb;
}

PCBYTES
pc_bytes_sigbits_decode_8(const PCBYTES pcb)
{
  int i;
  const uint8_t *bytes_ptr = (const uint8_t *)(pcb.bytes);
  uint8_t nbits;
  uint8_t commonvalue;
  uint8_t mask;
  int bit = 8;
  size_t outbytes_size = sizeof(uint8_t) * pcb.npoints;
  uint8_t *outbytes = pcalloc(outbytes_size);
  uint8_t *obytes = (uint8_t *)outbytes;
  PCBYTES pcbout = pcb;

  /* How many unique bits? */
  nbits = *bytes_ptr;
  bytes_ptr++;
  /* What is the shared bit value? */
  commonvalue = *bytes_ptr;
  bytes_ptr++;
  /* Mask for just the unique parts */
  mask = (0xFF >> (bit - nbits));

  for (i = 0; i < pcb.npoints; i++)
  {
    int shift = bit - nbits;
    uint8_t val = *bytes_ptr;
    /* The unique part is all in this word */
    if (shift >= 0)
    {
      /* Push unique part to bottom of word */
      val >>= shift;
      /* Mask out any excess */
      val &= mask;
      /* Add in the common part */
      val |= commonvalue;
      /* Save */
      obytes[i] = val;
      /* Move read head */
      bit -= nbits;
    }
    /* The unique part is split over this word and the next */
    else
    {
      int s = abs(shift);
      val <<= s;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bytes_ptr++;
      bit = 8;
      val = *bytes_ptr;
      shift = bit - s;
      val >>= shift;
      val &= mask;
      obytes[i] |= val;
      bit -= s;
    }
  }
  pcbout.size = outbytes_size;
  pcbout.compression = PC_DIM_NONE;
  pcbout.bytes = outbytes;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

PCBYTES
pc_bytes_sigbits_decode_16(const PCBYTES pcb)
{
  int i;
  const uint16_t *bytes_ptr = (const uint16_t *)(pcb.bytes);
  uint16_t nbits;
  uint16_t commonvalue;
  uint16_t mask;
  static const int bitwidth = 16;
  int bit = bitwidth;
  size_t outbytes_size = sizeof(uint16_t) * pcb.npoints;
  uint8_t *outbytes = pcalloc(outbytes_size);
  uint16_t *obytes = (uint16_t *)outbytes;
  PCBYTES pcbout = pcb;

  /* How many unique bits? */
  nbits = *bytes_ptr;
  bytes_ptr++;
  /* What is the shared bit value? */
  commonvalue = *bytes_ptr;
  bytes_ptr++;
  /* Calculate mask */
  mask = (0xFFFF >> (bit - nbits));

  for (i = 0; i < pcb.npoints; i++)
  {
    int shift = bit - nbits;
    uint16_t val = *bytes_ptr;
    if (shift >= 0)
    {
      val >>= shift;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bit -= nbits;
      if (bit <= 0)
      {
        bytes_ptr++;
        bit = bitwidth;
      }
    }
    else
    {
      int s = abs(shift);
      val <<= s;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bytes_ptr++;
      bit = bitwidth;
      val = *bytes_ptr;
      shift = bit - s;
      val >>= shift;
      val &= mask;
      obytes[i] |= val;
      bit -= s;
    }
  }
  pcbout.size = outbytes_size;
  pcbout.compression = PC_DIM_NONE;
  pcbout.bytes = outbytes;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

PCBYTES
pc_bytes_sigbits_decode_32(const PCBYTES pcb)
{
  int i;
  const uint32_t *bytes_ptr = (const uint32_t *)(pcb.bytes);
  uint32_t nbits;
  uint32_t commonvalue;
  uint32_t mask;
  static const int bitwidth = 32;
  int bit = bitwidth;
  size_t outbytes_size = sizeof(uint32_t) * pcb.npoints;
  uint8_t *outbytes = pcalloc(outbytes_size);
  uint32_t *obytes = (uint32_t *)outbytes;
  PCBYTES pcbout = pcb;

  /* How many unique bits? */
  nbits = *bytes_ptr;
  bytes_ptr++;
  /* What is the shared bit value? */
  commonvalue = *bytes_ptr;
  bytes_ptr++;
  /* Calculate mask */
  mask = (0xFFFFFFFF >> (bit - nbits));

  for (i = 0; i < pcb.npoints; i++)
  {
    int shift = bit - nbits;
    uint32_t val = *bytes_ptr;
    if (shift >= 0)
    {
      val >>= shift;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bit -= nbits;
      if (bit <= 0)
      {
        bytes_ptr++;
        bit = bitwidth;
      }
    }
    else
    {
      int s = abs(shift);
      val <<= s;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bytes_ptr++;
      bit = bitwidth;
      val = *bytes_ptr;
      shift = bit - s;
      val >>= shift;
      val &= mask;
      bit -= s;
      obytes[i] |= val;
    }
  }

  pcbout.size = outbytes_size;
  pcbout.compression = PC_DIM_NONE;
  pcbout.bytes = outbytes;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

PCBYTES
pc_bytes_sigbits_decode_64(const PCBYTES pcb)
{
  int i;
  const uint64_t *bytes_ptr = (const uint64_t *)(pcb.bytes);
  uint64_t nbits;
  uint64_t commonvalue;
  uint64_t mask;
  static const int bitwidth = 64;
  int bit = bitwidth;
  size_t outbytes_size = sizeof(uint64_t) * pcb.npoints;
  uint8_t *outbytes = pcalloc(outbytes_size);
  uint64_t *obytes = (uint64_t *)outbytes;
  PCBYTES pcbout = pcb;

  /* How many unique bits? */
  nbits = *bytes_ptr;
  bytes_ptr++;
  /* What is the shared bit value? */
  commonvalue = *bytes_ptr;
  bytes_ptr++;
  /* Calculate mask */
  mask = (0xFFFFFFFFFFFFFFFF >> (bit - nbits));

  for (i = 0; i < pcb.npoints; i++)
  {
    int shift = bit - nbits;
    uint64_t val = *bytes_ptr;
    if (shift >= 0)
    {
      val >>= shift;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bit -= nbits;
      if (bit <= 0)
      {
        bytes_ptr++;
        bit = bitwidth;
      }
    }
    else
    {
      int s = abs(shift);
      val <<= s;
      val &= mask;
      val |= commonvalue;
      obytes[i] = val;
      bytes_ptr++;
      bit = bitwidth;
      val = *bytes_ptr;
      shift = bit - s;
      val >>= shift;
      val &= mask;
      bit -= s;
      obytes[i] |= val;
    }
  }

  pcbout.size = outbytes_size;
  pcbout.compression = PC_DIM_NONE;
  pcbout.bytes = outbytes;
  pcbout.readonly = PC_FALSE;
  return pcbout;
}

PCBYTES
pc_bytes_sigbits_decode(const PCBYTES pcb)
{
  size_t size = pc_interpretation_size(pcb.interpretation);
  switch (size)
  {
  case 1:
  {
    return pc_bytes_sigbits_decode_8(pcb);
  }
  case 2:
  {
    return pc_bytes_sigbits_decode_16(pcb);
  }
  case 4:
  {
    return pc_bytes_sigbits_decode_32(pcb);
  }
  case 8:
  {
    return pc_bytes_sigbits_decode_64(pcb);
  }
  default:
  {
    pcerror("%s: cannot handle interpretation %d", __func__,
            pcb.interpretation);
  }
  }
  pcerror("%s: got an unhandled errror", __func__);
  return pcb;
}

static voidpf pc_zlib_alloc(voidpf opaque, uInt nitems, uInt sz)
{
  return pcalloc(sz * nitems);
}

static void pc_zlib_free(voidpf opaque, voidpf ptr) { pcfree(ptr); }

/* TO DO look for Z_STREAM_END on the write */

/**
 * Returns compressed byte array with
 * <size_t> size of compressed portion
 * <size_t> size of original data
 * <.....> compresssed bytes
 */
PCBYTES
pc_bytes_zlib_encode(const PCBYTES pcb)
{
  z_stream strm;
  int ret;
  size_t have;
  size_t bufsize = 4 * pcb.size;
  uint8_t *buf = pcalloc(bufsize);
  PCBYTES pcbout = pcb;

  /* Use our own allocators */
  strm.zalloc = pc_zlib_alloc;
  strm.zfree = pc_zlib_free;
  strm.opaque = Z_NULL;
  ret = deflateInit(&strm, 9);
  /* Set up input buffer */
  strm.avail_in = pcb.size;
  strm.next_in = pcb.bytes;
  /* Set up output buffer */
  strm.avail_out = bufsize;
  strm.next_out = buf;
  /* Compress */
  ret = deflate(&strm, Z_FINISH);
  assert(ret != Z_STREAM_ERROR);
  have = strm.total_out;
  pcbout.size = have;
  pcbout.bytes = pcalloc(pcbout.size);
  pcbout.compression = PC_DIM_ZLIB;
  pcbout.readonly = PC_FALSE;
  memcpy(pcbout.bytes, buf, have);
  pcfree(buf);
  deflateEnd(&strm);
  return pcbout;
}

/**
 * Returns uncompressed byte array from input with
 * <size_t> size of compressed portion
 * <size_t> size of original data
 * <.....> compresssed bytes
 */
PCBYTES
pc_bytes_zlib_decode(const PCBYTES pcb)
{
  z_stream strm;
  int ret;
  PCBYTES pcbout = pcb;

  pcbout.size = pc_interpretation_size(pcb.interpretation) * pcb.npoints;

  /* Set up output memory */
  pcbout.bytes = pcalloc(pcbout.size);
  pcbout.readonly = PC_FALSE;

  /* Use our own allocators */
  strm.zalloc = pc_zlib_alloc;
  strm.zfree = pc_zlib_free;
  strm.opaque = Z_NULL;
  ret = inflateInit(&strm);
  /* Set up input buffer */
  strm.avail_in = pcb.size;
  strm.next_in = pcb.bytes;

  strm.avail_out = pcbout.size;
  strm.next_out = pcbout.bytes;
  ret = inflate(&strm, Z_FINISH);
  assert(ret != Z_STREAM_ERROR);
  inflateEnd(&strm);

  pcbout.compression = PC_DIM_NONE;
  return pcbout;
}

/**
 * This flips bytes in-place, so won't work on readonly bytes
 */
PCBYTES
pc_bytes_flip_endian(PCBYTES pcb)
{
  if (pcb.readonly)
    pcerror("pc_bytes_flip_endian: cannot flip readonly bytes");

  switch (pcb.compression)
  {
  case PC_DIM_NONE:
    return pcb;
  case PC_DIM_SIGBITS:
    return pc_bytes_sigbits_flip_endian(pcb);
  case PC_DIM_ZLIB:
    return pcb;
  case PC_DIM_RLE:
    return pc_bytes_run_length_flip_endian(pcb);
  default:
    pcerror("%s: unknown compression", __func__);
  }

  return pcb;
}

size_t pc_bytes_serialized_size(const PCBYTES *pcb)
{
  /* compression type (1) + size of data (4) + data */
  return 1 + 4 + pcb->size;
}

int pc_bytes_serialize(const PCBYTES *pcb, uint8_t *buf, size_t *size)
{
  static int compression_num_size = 1;
  static int size_num_size = 4;
  int32_t pcbsize = pcb->size;

  /* Compression type number */
  *buf = pcb->compression;
  buf += compression_num_size;
  /* Buffer size */
  memcpy(buf, &pcbsize, size_num_size);
  buf += size_num_size;
  /* Buffer contents */
  memcpy(buf, pcb->bytes, pcb->size);
  /* Return total size */
  *size = compression_num_size + size_num_size + pcbsize;
  return PC_SUCCESS;
}

int pc_bytes_deserialize(const uint8_t *buf, const PCDIMENSION *dim,
                         PCBYTES *pcb, int readonly, int flip_endian)
{
  pcb->compression = buf[0];
  pcb->size = wkb_get_int32(buf + 1, flip_endian);
  pcb->readonly = readonly;
  if (readonly && flip_endian)
    pcerror("pc_bytes_deserialize: cannot create a read-only buffer on "
            "byteswapped input");
  if (readonly)
  {
    pcb->bytes = (uint8_t *)(buf + 5);
  }
  else
  {
    pcb->bytes = pcalloc(pcb->size);
    memcpy(pcb->bytes, buf + 5, pcb->size);
    if (flip_endian)
    {
      *pcb = pc_bytes_flip_endian(*pcb);
    }
  }
  pcb->interpretation = dim->interpretation;
  /* WARNING, still need to set externally */
  /*   pcb.npoints */
  return PC_SUCCESS;
}

static int pc_bytes_uncompressed_minmax(const PCBYTES *pcb, double *min,
                                        double *max, double *avg)
{
  int i;
  int element_size = pc_interpretation_size(pcb->interpretation);
  double d;
  double mn = FLT_MAX;
  double mx = -1 * FLT_MAX;
  double sm = 0.0;
  for (i = 0; i < pcb->npoints; i++)
  {
    d = pc_double_from_ptr(pcb->bytes + i * element_size, pcb->interpretation);
    if (d < mn)
      mn = d;
    if (d > mx)
      mx = d;
    sm += d;
  }
  *min = mn;
  *max = mx;
  *avg = sm / pcb->npoints;
  return PC_SUCCESS;
}

static int pc_bytes_run_length_minmax(const PCBYTES *pcb, double *min,
                                      double *max, double *avg)
{
  int element_size = pc_interpretation_size(pcb->interpretation);
  double mn = FLT_MAX;
  double mx = -1 * FLT_MAX;
  double sm = 0.0;
  double d;
  uint8_t *ptr = pcb->bytes;
  uint8_t *ptr_end = pcb->bytes + pcb->size;
  uint8_t count;

  while (ptr < ptr_end)
  {
    /* Read count and advance */
    count = *ptr;
    ptr += 1;

    /* Read value and advance */
    d = pc_double_from_ptr(ptr, pcb->interpretation);
    ptr += element_size;

    /* Calc min */
    if (d < mn)
      mn = d;
    /* Calc max */
    if (d > mx)
      mx = d;
    /* Calc sum */
    sm += count * d;
  }

  *min = mn;
  *max = mx;
  *avg = sm / pcb->npoints;
  return PC_SUCCESS;
}

static int pc_bytes_zlib_minmax(const PCBYTES *pcb, double *min, double *max,
                                double *avg)
{
  PCBYTES zcb = pc_bytes_zlib_decode(*pcb);
  int rv = pc_bytes_uncompressed_minmax(&zcb, min, max, avg);
  pc_bytes_free(zcb);
  return rv;
}

static int pc_bytes_sigbits_minmax(const PCBYTES *pcb, double *min, double *max,
                                   double *avg)
{
  PCBYTES zcb = pc_bytes_sigbits_decode(*pcb);
  int rv = pc_bytes_uncompressed_minmax(&zcb, min, max, avg);
  pc_bytes_free(zcb);
  return rv;
}

int pc_bytes_minmax(const PCBYTES *pcb, double *min, double *max, double *avg)
{
  switch (pcb->compression)
  {
  case PC_DIM_NONE:
    return pc_bytes_uncompressed_minmax(pcb, min, max, avg);
  case PC_DIM_SIGBITS:
    return pc_bytes_sigbits_minmax(pcb, min, max, avg);
  case PC_DIM_ZLIB:
    return pc_bytes_zlib_minmax(pcb, min, max, avg);
  case PC_DIM_RLE:
    return pc_bytes_run_length_minmax(pcb, min, max, avg);
  default:
    pcerror("%s: unknown compression", __func__);
  }
  return PC_FAILURE;
}

/* NOTE: stats are gathered without applying scale and offset */
static PCBYTES pc_bytes_uncompressed_filter(const PCBYTES *pcb,
                                            const PCBITMAP *map,
                                            PCDOUBLESTAT *stats)
{
  int i = 0, j = 0;
  double d;
  PCBYTES fpcb = pc_bytes_clone(*pcb);
  int interp = pcb->interpretation;
  int sz = pc_interpretation_size(interp);
  uint8_t *buf = pcb->bytes;
  uint8_t *fbuf = fpcb.bytes;

  while (i < pcb->npoints)
  {
    /* This entry is flagged to copy, so... */
    if (pc_bitmap_get(map, i))
    {
      /* Update stats on filtered bytes */
      if (stats)
      {
        d = pc_double_from_ptr(buf, interp);
        if (d < stats->min)
          stats->min = d;
        if (d > stats->max)
          stats->max = d;
        stats->sum += d;
      }
      /* Copy into filtered byte array */
      memcpy(fbuf, buf, sz);
      fbuf += sz;
      j++;
    }
    buf += sz;
    i++;
  }
  fpcb.size = fbuf - fpcb.bytes;
  fpcb.npoints = j;
  return fpcb;
}

/* NOTE: stats are gathered without applying scale and offset */
static PCBYTES pc_bytes_run_length_filter(const PCBYTES *pcb,
                                          const PCBITMAP *map,
                                          PCDOUBLESTAT *stats)
{
  int i = 0, j = 0, npoints = 0;
  double d;

  PCBYTES fpcb = pc_bytes_clone(*pcb);
  int sz = pc_interpretation_size(pcb->interpretation);
  uint8_t *fptr = fpcb.bytes;
  uint8_t *ptr = pcb->bytes;
  uint8_t *ptr_end = pcb->bytes + pcb->size;
  uint8_t count;
  uint8_t fcount;

  while (ptr < ptr_end)
  {
    /* Read unfiltered count */
    count = *ptr;
    /* Initialize filtered count */
    fcount = 0;

    /* How many filtered points are in this value entry? */
    for (j = i; j < i + count; j++)
    {
      if (pc_bitmap_get(map, j))
      {
        fcount++;
      }
    }

    /* If there are some, we need to copy */
    if (fcount)
    {
      /* Copy in the filtered count */
      memcpy(fptr, &fcount, 1);
      /* Advance to the value */
      fptr++;
      /* Copy in the value */
      memcpy(fptr, ptr + 1, sz);
      /* Advance to next entry */
      fptr += sz;
      /* Increment point counter */
      npoints += fcount;
      /* Update the stats */
      if (stats)
      {
        d = pc_double_from_ptr(ptr + 1, pcb->interpretation);
        if (d < stats->min)
          stats->min = d;
        if (d > stats->max)
          stats->max = d;
        stats->sum += d;
      }
    }

    /* Move to next value in unfiltered bytes */
    ptr += sz + 1;
    i += count;
  }
  fpcb.size = fptr - fpcb.bytes;
  fpcb.npoints = npoints;
  return fpcb;
}

/* NOTE: stats are gathered without applying scale and offset */
PCBYTES
pc_bytes_filter(const PCBYTES *pcb, const PCBITMAP *map, PCDOUBLESTAT *stats)
{
  switch (pcb->compression)
  {
  case PC_DIM_NONE:
    return pc_bytes_uncompressed_filter(pcb, map, stats);

  case PC_DIM_RLE:
    return pc_bytes_run_length_filter(pcb, map, stats);

  case PC_DIM_SIGBITS:
  case PC_DIM_ZLIB:
  {
    PCBYTES dpcb = pc_bytes_decode(*pcb);
    PCBYTES fpcb = pc_bytes_uncompressed_filter(&dpcb, map, stats);
    PCBYTES efpcb = pc_bytes_encode(fpcb, pcb->compression);
    pc_bytes_free(fpcb);
    pc_bytes_free(dpcb);
    return efpcb;
  }

  default:
    pcerror("%s: unknown compression", __func__);
  }
  return *pcb;
}

static PCBITMAP *pc_bytes_run_length_bitmap(const PCBYTES *pcb,
                                            PC_FILTERTYPE filter, double val1,
                                            double val2)
{
  int i = 0, run = 0;
  double d;
  PCBITMAP *map = pc_bitmap_new(pcb->npoints);
  int element_size = pc_interpretation_size(pcb->interpretation);
  uint8_t *ptr = pcb->bytes;
  uint8_t *ptr_end = pcb->bytes + pcb->size;
  uint8_t count;

  while (ptr < ptr_end)
  {
    /* Read count */
    count = *ptr;
    ptr++;
    run = i + count;

    /* Read value */
    d = pc_double_from_ptr(ptr, pcb->interpretation);
    ptr += element_size;

    /* Apply run to bitmap */
    while (i < run)
    {
      pc_bitmap_filter(map, filter, i, d, val1, val2);
      i++;
    }
  }

  return map;
}

static PCBITMAP *pc_bytes_uncompressed_bitmap(const PCBYTES *pcb,
                                              PC_FILTERTYPE filter, double val1,
                                              double val2)
{
  int i = 0;
  double d;
  PCBITMAP *map = pc_bitmap_new(pcb->npoints);
  int element_size = pc_interpretation_size(pcb->interpretation);
  uint8_t *buf = pcb->bytes;

  while (i < pcb->npoints)
  {
    d = pc_double_from_ptr(buf, pcb->interpretation);
    pc_bitmap_filter(map, filter, i, d, val1, val2);
    /* Advance the pointer */
    buf += element_size;
    i++;
  }
  return map;
}

PCBITMAP *pc_bytes_bitmap(const PCBYTES *pcb, PC_FILTERTYPE filter, double val1,
                          double val2)
{
  switch (pcb->compression)
  {
  case PC_DIM_NONE:
    return pc_bytes_uncompressed_bitmap(pcb, filter, val1, val2);
  case PC_DIM_SIGBITS:
  case PC_DIM_ZLIB:
  {
    PCBYTES dpcb = pc_bytes_decode(*pcb);
    PCBITMAP *map = pc_bytes_uncompressed_bitmap(&dpcb, filter, val1, val2);
    pc_bytes_free(dpcb);
    return map;
  }
  case PC_DIM_RLE:
    return pc_bytes_run_length_bitmap(pcb, filter, val1, val2);
  default:
    pcerror("%s: unknown compression", __func__);
  }
  return NULL;
}

/** get n-th value, 0-based, positive */
void pc_bytes_uncompressed_to_ptr(uint8_t *buf, PCBYTES pcb, int n)
{
  size_t size = pc_interpretation_size(pcb.interpretation);
  memcpy(buf, pcb.bytes + n * size, size);
}

void pc_bytes_run_length_to_ptr(uint8_t *buf, PCBYTES pcb, int n)
{
  const uint8_t *bytes_rle_ptr = pcb.bytes;
  const uint8_t *bytes_rle_end = pcb.bytes + pcb.size;
  uint8_t run;

  size_t size = pc_interpretation_size(pcb.interpretation);
  assert(pcb.compression == PC_DIM_RLE);

  while (bytes_rle_ptr < bytes_rle_end)
  {
    run = *bytes_rle_ptr;
    if (n < run)
    {
      memcpy(buf, bytes_rle_ptr + 1, size);
      return;
    }
    n -= run;
    bytes_rle_ptr += 1 + size;
  }
  pcerror("%s: out of bound", __func__);
}

#define PC_BYTES_SIGBITS_TO_PTR(N)                                             \
  void pc_bytes_sigbits_to_ptr_##N(uint8_t *buf, PCBYTES pcb, int n)           \
  {                                                                            \
    const uint##N##_t *bytes_ptr = (const uint##N##_t *)(pcb.bytes);           \
    /* How many unique bits? */                                                \
    uint##N##_t nbits = *bytes_ptr++;                                          \
    /* What is the shared bit value? */                                        \
    uint##N##_t commonvalue = *bytes_ptr++;                                    \
    /* Mask for just the unique parts */                                       \
    uint##N##_t mask = 0xFFFFFFFFFFFFFFFF >> (64 - nbits);                     \
                                                                               \
    uint##N##_t bitoffset = n * nbits;                                         \
    bytes_ptr += bitoffset / N;                                                \
    int shift = N - (bitoffset % N) - nbits;                                   \
                                                                               \
    uint##N##_t res = commonvalue;                                             \
    uint##N##_t val = *bytes_ptr;                                              \
    /* The unique part is split over this word and the next */                 \
    if (shift < 0)                                                             \
    {                                                                          \
      val <<= -shift;                                                          \
      val &= mask;                                                             \
      res |= val;                                                              \
      bytes_ptr++;                                                             \
      val = *bytes_ptr;                                                        \
      shift += N;                                                              \
    }                                                                          \
    /* Push unique part to bottom of word */                                   \
    val >>= shift;                                                             \
    /* Mask out any excess */                                                  \
    val &= mask;                                                               \
    /* Save */                                                                 \
    res |= val;                                                                \
    memcpy(buf, &res, sizeof(res));                                            \
  }

PC_BYTES_SIGBITS_TO_PTR(8)
PC_BYTES_SIGBITS_TO_PTR(16)
PC_BYTES_SIGBITS_TO_PTR(32)
PC_BYTES_SIGBITS_TO_PTR(64)

void pc_bytes_sigbits_to_ptr(uint8_t *buf, PCBYTES pcb, int n)
{
  size_t size = pc_interpretation_size(pcb.interpretation);
  switch (size)
  {
  case 1:
  {
    return pc_bytes_sigbits_to_ptr_8(buf, pcb, n);
  }
  case 2:
  {
    return pc_bytes_sigbits_to_ptr_16(buf, pcb, n);
  }
  case 4:
  {
    return pc_bytes_sigbits_to_ptr_32(buf, pcb, n);
  }
  case 8:
  {
    return pc_bytes_sigbits_to_ptr_64(buf, pcb, n);
  }
  default:
  {
    pcerror("%s: cannot handle interpretation %d", __func__,
            pcb.interpretation);
  }
  }
}

void pc_bytes_zlib_to_ptr(uint8_t *buf, PCBYTES pcb, int n)
{
  PCBYTES dpcb = pc_bytes_decode(pcb);
  pc_bytes_uncompressed_to_ptr(buf, dpcb, n);
  pc_bytes_free(dpcb);
}

void pc_bytes_to_ptr(uint8_t *buf, PCBYTES pcb, int n)
{
  switch (pcb.compression)
  {
  case PC_DIM_RLE:
  {
    pc_bytes_run_length_to_ptr(buf, pcb, n);
    break;
  }
  case PC_DIM_SIGBITS:
  {
    pc_bytes_sigbits_to_ptr(buf, pcb, n);
    break;
  }
  case PC_DIM_ZLIB:
  {
    pc_bytes_zlib_to_ptr(buf, pcb, n);
    break;
  }
  case PC_DIM_NONE:
  {
    pc_bytes_uncompressed_to_ptr(buf, pcb, n);
    break;
  }
  default:
  {
    pcerror("%s: Uh oh", __func__);
  }
  }
}