long MoveToNextBoundary ()
{
long retval = 0;
bool got_cr = false;
int state = 0;
int c = data.ReadByte ();
while (true) {
if (c == -1)
return -1;
if (state == 0 && c == LF) {
retval = data.Position - 1;
if (got_cr)
retval--;
state = 1;
c = data.ReadByte ();
} else if (state == 0) {
got_cr = (c == CR);
c = data.ReadByte ();
} else if (state == 1 && c == '-') {
c = data.ReadByte ();
if (c == -1)
return -1;
if (c != '-') {
state = 0;
got_cr = false;
continue; // no ReadByte() here
}
int nread = data.Read (buffer, 0, buffer.Length);
int bl = buffer.Length;
if (nread != bl)
return -1;
if (!CompareBytes (boundary_bytes, buffer)) {
state = 0;
data.Position = retval + 2;
if (got_cr) {
data.Position++;
got_cr = false;
}
c = data.ReadByte ();
continue;
}
if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
at_eof = true;
} else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
state = 0;
data.Position = retval + 2;
if (got_cr) {
data.Position++;
got_cr = false;
}
c = data.ReadByte ();
continue;
}
data.Position = retval + 2;
if (got_cr)
data.Position++;
break;
} else {
// state == 1
state = 0; // no ReadByte() here
}
}
return retval;
}