summaryrefslogtreecommitdiff
path: root/src/compression/rle.c
blob: 2adeae248170f152527752b45dfcc973455c8c62 (plain)
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
/* This code is part of the tng compression routines.
 *
 * Written by Daniel Spangberg
 * Copyright (c) 2010, 2013, The GROMACS development team.
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 */


#include "compression/rle.h"

static void add_rle(unsigned int *rle,
		    int v,int nsim,
		    int *j,int min_rle)
{
  if (nsim>min_rle)
    {
      /* Insert run-length */
      unsigned int run=((unsigned int)nsim);
      while (run>1)
	{
	  if (run&0x1U)
	    rle[(*j)++]=1;
	  else
	    rle[(*j)++]=0;
	  run>>=1;
	}
      nsim=1;
    }
  while (nsim--)
    rle[(*j)++]=v+2;
}

/* Run length encoding.
   Acceptable inputs are about 16 bits (0-0xFFFF)
   If input is 0-N output will be be values of 0-(N+2) */
void Ptngc_comp_conv_to_rle(unsigned int *vals, int nvals,
		      unsigned int *rle, int *nrle,
		      int min_rle)
{
  int i;
  int j=0;
  int nsim=0;
  int v=-1;
  for (i=0; i<nvals; i++)
    {
      if (!nsim)
	{
	  v=vals[i];
	  nsim=1;
	}
      else
	{
	  if (v==vals[i])
	    nsim++;
	  else
	    {
	      add_rle(rle,v,nsim,&j,min_rle);
	      nsim=1;
	      v=vals[i];
	    }
	}
    }
  if (nsim!=0)
    add_rle(rle,v,nsim,&j,min_rle);
  *nrle=j;
}

void Ptngc_comp_conv_from_rle(unsigned int *rle,
			unsigned int *vals, int nvals)
{
  int i=0;
  int j=0;
  while (i<nvals)
    {
      int k;
      unsigned int len=0;
      unsigned int mask=0x1;
      unsigned int v=rle[j++];
      unsigned int hasrle=0;
      while (v<2)
	{
	  if (v)
	    len|=mask;
	  mask<<=1;
	  hasrle=1;
	  v=rle[j++];
	}
      if (!hasrle)
	len=1;
      else
	len|=mask;
      for (k=0; k<(int)len; k++)
	vals[i++]=v-2;
    }
}

contact: Jan Huwald // Impressum