#include "positions.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool
Positions::contains (int pos) const
{
unsigned int count = _size;
const int *p = _positions + _size - 1;
for (; count > 0; p--, count--)
{
if (*p == pos)
return true;
if (*p > pos)
break;
}
return false;
}
void
Positions::add (int pos)
{
set_useall (false);
unsigned int count = _size;
if (count == MAX_SIZE)
{
fprintf (stderr, "Positions::add internal error: overflow\n");
exit (1);
}
int *p = _positions + _size - 1;
for (; count > 0; p--, count--)
{
if (*p == pos)
{
fprintf (stderr, "Positions::add internal error: duplicate\n");
exit (1);
}
if (*p > pos)
break;
p[1] = p[0];
}
p[1] = pos;
_size++;
}
void
Positions::remove (int pos)
{
set_useall (false);
unsigned int count = _size;
if (count > 0)
{
int *p = _positions + _size - 1;
if (*p == pos)
{
_size--;
return;
}
if (*p < pos)
{
int prev = *p;
for (;;)
{
p--;
count--;
if (count == 0)
break;
if (*p == pos)
{
*p = prev;
_size--;
return;
}
if (*p > pos)
break;
int curr = *p;
*p = prev;
prev = curr;
}
}
}
fprintf (stderr, "Positions::remove internal error: not found\n");
exit (1);
}
void
Positions::print () const
{
if (_useall)
printf ("*");
else
{
bool first = true;
bool seen_LASTCHAR = false;
unsigned int count = _size;
const int *p = _positions + _size - 1;
for (; count > 0; p--)
{
count--;
if (*p == LASTCHAR)
seen_LASTCHAR = true;
else
{
if (!first)
printf (",");
printf ("%d", *p + 1);
if (count > 0 && p[-1] == *p + 1)
{
printf ("-");
do
{
p--;
count--;
}
while (count > 0 && p[-1] == *p + 1);
printf ("%d", *p + 1);
}
first = false;
}
}
if (seen_LASTCHAR)
{
if (!first)
printf (",");
printf ("$");
}
}
}
#ifndef __OPTIMIZE__
#define INLINE
#include "positions.icc"
#undef INLINE
#endif