summaryrefslogtreecommitdiff
path: root/inbuf.c
blob: 4f135b2629ca875b27629a5dd8524f583123e092 (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
/* -*- mode: c; c-file-style: "gnu" -*-  */

/* libhsync
   Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
   USA
*/

#include "includes.h"
#include "hsync.h"
#include "hsyncproto.h"
#include "private.h"




int
_hs_fill_inbuf (inbuf_t * inbuf, rs_read_fn_t read_fn, void *readprivate)
{
  int ret;

  assert (inbuf->amount < inbuf->len && 0 <= inbuf->amount);
  ret = read_fn (readprivate,
		 inbuf->buf + inbuf->amount, inbuf->len - inbuf->amount);
  if (ret < 0)
    {
      _hs_error ( __FILE__ ": error reading into input buffer");
      return ret;
    }
  else if (ret == 0)
    {
      _hs_trace ("reached end of input file");
    }
  else
    {
      _hs_trace ("read %d bytes into input buffer"
		  " at position %d", ret, inbuf->abspos);
    }
  inbuf->amount += ret;
  return ret;
}



int
_hs_alloc_inbuf (inbuf_t * inbuf, int block_len)
{
  bzero (inbuf, sizeof *inbuf);
  /* must be at least two blocks; shouldn't be too small. */
  inbuf->len = MAX (block_len * 2, 8192);
  inbuf->buf = malloc (inbuf->len);
  inbuf->amount = 0;
  inbuf->abspos = 0;

  return 0;
}


int
_hs_slide_inbuf (inbuf_t *inbuf)
{
  /* Copy the remaining data into the front of
     the buffer */
  if (inbuf->cursor != 0)
    {
      if (inbuf->amount != inbuf->cursor)
	{
	  memcpy (inbuf->buf,
		  inbuf->buf + inbuf->cursor, inbuf->amount - inbuf->cursor);
	  _hs_trace (": slide %d bytes down to the start of the buffer",
		     inbuf->amount - inbuf->cursor);
	}
      
      inbuf->amount -= inbuf->cursor;
      inbuf->abspos += inbuf->cursor;
    }
  
  return 0;
}