summaryrefslogtreecommitdiff
path: root/comm/MsgBuffer.cc
blob: f1dbeda2909173c44c79e2742cb5e3a0be9980ac (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
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
/*
 *	Ivy League
 *
 *	Buffers for messages
 *
 *	Copyright 1990-2000
 *	Laboratoire de Recherche en Informatique (LRI)
 *	Centre d'Etudes de la Navigation Aerienne (CENA)
 *
 *	original code by Michel Beaudouin-Lafon,
 *	modified by Stephane Chatty and Stephane Sire
 *
 *	$Id$
 *
 */

#include "MsgBuffer.h"
#include "Message.h"
#include "ivl/String.h"

#include <stdlib.h>
#include <string.h>
#include <memory.h>

//	management of buffers
//	The buffer is said to be allocated if Begin is non zero.
//	There is a special constructor that builds an allocated buffer with Begin = 0 :
//		IvlMsgBuffer (IvlMsgBuffer&, int len)
//	This buffer can only be read from and flushed
//	This is useful for creating a fake buffer that is actually a pointer to 
//	a subpart of the original one. Thus, the new buffer can be safely read from
//	without eating too far away
//

/*?class IvlMsgBuffer
A \typ{IvlMsgBuffer} is an array of bytes of a given size that can be partially filled.
The buffer may grow whenever bytes are appended to it.
The initial size, the increments and the maximum sizes can be defined.
If the buffer exceeds its maximal size, it will be deleted when it becomes empty
in order to give it a smaller size.

Data can be appended and extracted from the buffer by \fun{operator $<<$}
and \fun{operator $>>$}.
When extracting data, the buffer may not contain enough bytes.
We say that a ``get error'' has occurred and the buffer remembers it until it is modified
by the functions \fun{Append} or \fun{More}, or by \fun{operator $<<$}.

\fig{FIGURES/buffer}{Some operations on a buffer.}
?*/

static	int	padding [] =	{ 0, 1, 2, 3};
inline	int	pad (int sz)	{ return sz + padding [sz & 03]; }

/*?
Construct an empty buffer.
The buffer will be allocated with a default size whenever data is appended to it.
This default size is currently 128 bytes.
?*/
IvlMsgBuffer :: IvlMsgBuffer ()
: IvlIOS ()
{
	Begin = Start = Stop = End = 0;
	GetErr = false;
	GrowSize = MinSize = 128;
	MaxSize = 0;
}

/*?
Construct a buffer with \var{sz} bytes.
?*/
IvlMsgBuffer :: IvlMsgBuffer (int sz)
: IvlIOS ()
{
	MinSize = GrowSize = sz = pad (sz);
	Begin = Start = Stop = new byte [sz];
	End = Begin + sz;
	GetErr = false;
	MaxSize = 0;
}

/*?
Construct a buffer with minimum \var{sz} bytes, growing by \var{grow} bytes,
until a maximum size of \var{max} bytes.
?*/
IvlMsgBuffer :: IvlMsgBuffer (int sz, int grow, int max)
: IvlIOS ()
{
	MinSize = sz = pad (sz);
	Begin = Start = Stop = new byte [sz];
	End = Begin + sz;
	GetErr = false;
	GrowSize = grow;
	MaxSize = max;
}

/*?
Construct a so called fake buffer, i.e. a buffer whose contents is made of the
first \var{l} characters of buffer \var{b} (or the whole buffer if \var{l} is zero).
The contents of the buffers is actually shared until the fake buffer is destructed
or data is appended to it.
Fake buffers are mainly used to extract data without exceeding a given size and
without making a copy.
Note that the contents of the fake buffer can be overwritten if you read and then append to
the original buffer.
The rule of thumb is to avoid modifying the original buffer while there is a fake buffer on it.
?*/
IvlMsgBuffer :: IvlMsgBuffer (const IvlMsgBuffer& b, int l)
: IvlIOS (b)
{
	Begin = 0;
	Start = b.Start;
	if (l && Start + l <= b.Stop)
		End = Stop = Start + l;
	else
		End = Stop = b.Stop;
	GetErr = false;
	GrowSize = b.GrowSize;
	MinSize = b.MinSize;
	MaxSize = b.MaxSize;
}

/*?nodoc?*/
IvlMsgBuffer :: ~IvlMsgBuffer ()
{
	Clear ();
}

/*?
Delete a buffer, i.e. free its internal byte buffer.
The buffer can still be used after this function has been called (it will reallocate the byte buffer).
The destructor calls this function.
?*/
void
IvlMsgBuffer :: Clear ()
{
	if (Begin)
		delete Begin;
	Begin = Start = Stop = End = 0;
}

/*?
Insure that an IvlMsgBuffer has at least \var{sz} free bytes.
The buffer may be reallocated with a new size to provide the necessary space.
?*/
void
IvlMsgBuffer :: NeedSize (int sz)
{
	// brand new buffer
	if (! Begin) {
		if (End)		// ! Begin && End => fake buffer
			return;
		if ((sz = pad (sz)) < MinSize)
			sz = MinSize;
		Begin = Start = Stop = new byte [sz];
		End = Begin + sz;
		return;
	}
	
	// if enough space, do nothing
	if (End - Stop >= sz)
		return;
	
	// try to compact
	int l = Stop - Start;
	if (l && (Start - Begin) + (End - Stop) >= sz) {
		memcpy (Begin, Start, l);
		Start = Begin;
		Stop = Start + l;
		return;
	}
	
	// sigh! allocate new
	sz = pad (sz + ((l < GrowSize) ? GrowSize : l));
	byte* b = new byte [sz];
	if (l)
		memcpy (b, Start, l);
	delete Begin;
	Begin = Start = b;
	Stop = Start + l;
	End = Begin + sz;
}

/*?
Discard the \var{n} first bytes of a buffer, or the whole buffer if \var{n} is negative.
If the buffer becomes empty and had exceeded its maximum size, it is reset.
?*/
void
IvlMsgBuffer :: Flush (int n)
{
//printf ("IvlMsgBuffer %x : Flush (%d)\n", this, n);
	if (! Begin)
		if (! End)		// ! Begin && End => fake buffer
			return;
	if (n < 0 || Start + n >= Stop) {
		Start = Stop = Begin;
		// free if too big
		if (MaxSize > 0 && End - Start >= MaxSize)
			Clear ();
	} else
		Start += n;
//printf ("flushed\n");
}

/*?
Flush the buffer until \var{p}.
This can be used when the buffer has been accessed through \fun{Buffer ()}
and you want to flush until a given position in the buffer.
?*/
void
IvlMsgBuffer :: Flush (byte* p)
{
	if (p >= Start && p <= Stop)
		Flush (p - Start);
}

/*?
Set the minimum, increment and maximum size of a buffer (in bytes).
If an argument is negative, the corresponding size is not changed.
If an argument is zero, a default value is used:
128 for minimum and increment, 0 for maximum.
Sizes are rounded to the nearest multiple of 4.
If the maximum size is 0, there is no upper bound on the size of the buffer.
Note that the buffer can always grow as big as necessary to hold the appended data;
the maximum size is only used to reallocate the buffer whenever it becomes empty.
?*/
void
IvlMsgBuffer :: SetSizes (int min, int grow, int max)
{
	if (min >= 0)
		MinSize = pad (min);
	if (grow >= 0)
		GrowSize = pad (grow);
	if (max >= 0)
		MaxSize = pad (max);
	if (min == 0)
		MinSize = 128;
	if (grow == 0)
		GrowSize = 128;
}

//-----	append operations
//

/*?
Append the \var{n} first bytes of \var{buf} to the buffer.
All append functions call \fun{NeedSize} so that appending always succeeds.
?*/
void
IvlMsgBuffer :: WriteBuf (const byte* buf, int n)
{
	GetErr = false;
	if (! Begin || End - Stop < n)
		NeedSize (n);
	memcpy (Stop, buf, n);
	Stop += n;
}

/*?nextdoc?*/
void
IvlMsgBuffer :: WriteByte (byte b)
{
	GetErr = false;
	if (! Begin || End - Stop < 1)
		NeedSize (1);
	*Stop++ = b;
}

/*?nextdoc?*/
void
IvlMsgBuffer :: WriteChar (char c)
{
	WriteByte ((byte) c);
}

/*?nextdoc?*/
void
IvlMsgBuffer :: WriteLong (lword l)
{
	WriteBuf ((const byte*)&l, lwsize);
}
	
/*?
Append a short word, a long word, a byte or a character to a buffer.
The buffer is extended as necessary.
?*/
void
IvlMsgBuffer :: WriteShort (sword s)
{
	WriteBuf ((const byte*)&s, swsize);
}

void
IvlMsgBuffer :: WriteString (const char* s)
{
	Append (s);
}

/*?
Append a string to a buffer.
If the second argument is \var{true}, the terminating null byte is appended, else it is not.
If the string is the null pointer, nothing is appended to the buffer.
?*/
void
IvlMsgBuffer :: Append (const char* s, bool nullbyte)
{
	if (! s)
		return;
	GetErr = false;
	int l = strlen (s) + (nullbyte ? 1 : 0);
	if (! Begin || End - Stop < l)
		NeedSize (l);
	memcpy (Stop, s, l);
	Stop += l;
}

/*?
Append a message \var{msg} to the buffer.
The virtual function \fun{WriteTo} of the buffer is called.
The length of the message is automatically computed and prepended to the message itself.
?*/
void
IvlMsgBuffer :: WriteMsg (IvlMessage& msg)
{
	GetErr = false;
	
	// reserve space for length
	if (! Begin || End - Stop < lwsize)
		NeedSize (lwsize);
	// save current position (saving Start is wrong because it may move)
	lword l = Stop - Start;
	// skip space for length (this means that the length includes the 4 bytes of the length itself)
	Stop += lwsize;
	
	// append message to buffer
	msg.WriteTo (*this);
	
	// now patch the buffer ...
	// retrieve position
	byte* p = Start + l;
	// compute length
	lword len = (Stop - Start) - l;
	// and patch
	memcpy (p, &len, lwsize);
}

//-----	get operations
//

bool
IvlMsgBuffer :: GetBuf (byte* b, int n, bool peek, int offset)
{
	if (GetErr)
		return false;
	if (!peek || offset < 0)
		offset = 0;
	if (Stop - Start < offset + n) {
		GetErr = true;
		return false;
	}
	memcpy (b, Start+offset, n);
	if (! peek)
		Flush (n);
	return true;
}

int
IvlMsgBuffer :: GetString (char* str, int n, const char* delim, bool peek, int offset)
{
	if (GetErr)
		return 0;
	if (!peek || offset < 0)
		offset = 0;
	if (n < 0 || Stop - Start < offset + n)
		n = Stop - Start - offset;
	if (n < 0)
		return 0;

	int i = 0;
	char* q = str;
	char* p;
	for (p = (char*) (Start+offset); *p && n; n--, i++) {
		if (delim) {
			const char* s;
			for (s = delim; *s; s++)
				if (*s == *p)
					break;
			if (*s)
				break;
		}
		*q++ = *p++;
	}
	*q = '\0';

	/* if we reached the end of a string, flush the null character as well */
	if (! peek)
		Flush (*p ? i : i + 1);
	return i;
}

/*?nextdoc?*/
bool
IvlMsgBuffer :: ReadLong (lword& l)
{
	return GetBuf ((byte*) &l, lwsize, false);
}

/*?nextdoc?*/
bool
IvlMsgBuffer :: ReadShort (sword& s)
{
	return GetBuf ((byte*) &s, swsize, false);
}

/*?nextdoc?*/
bool
IvlMsgBuffer :: ReadByte (byte& b)
{
	return GetBuf (&b, 1, false);
}

/*?
Extract a long word, a short word, a byte, or a character from the buffer into the argument.
Return true if the data was actually extracted, else return false and mark the buffer with the get error flag.
If \var{peek} is true, the buffer is not flushed after extracting the data.
?*/
bool
IvlMsgBuffer :: ReadChar (char& c)
{
	return GetBuf ((byte*) &c, 1, false);
}

/*?
Extract a string from a buffer and copy it to a \typ{IvlString}.
This assumes that the string in the buffer is null-terminated.
?*/
int
IvlMsgBuffer :: ReadString (IvlString& s)
{
	if (GetErr)
		return 0;

	int n = Stop - Start;
	byte* p = Start;
	while (n-- && *p)
		++p;

	int l = p - Start;
	
	s.Assign ((const char*) Start, l);
	Flush (*p ? l : l + 1);
	return l;
}

/*?
Extract exactly \var{n} bytes from the buffer and copy them into \var{b}.
Return true if the bytes were extracted, else return false and mark the buffer with the get error flag.
If \var{peek} is true, the buffer is not flushed after extracting the data
(i.e. the extracted data is still in the buffer).
?*/

bool
IvlMsgBuffer :: ReadBuf (byte* b, int n)
{
	return GetBuf (b, n, false);
}

/*?nextdoc?*/
int
IvlMsgBuffer :: ReadString (char* str, char delim, int n)
{
	char ds [2];
	ds [0] = delim;
	ds [1] = 0;
	return GetString (str, n, ds, false);
}

/*?nextdoc?*/
int
IvlMsgBuffer :: ReadString (char* str, int n)
{
	return GetString (str, n, 0, false);
}

/*?
Get at most \var{n} characters from the buffer into \var{str}.
\var{delim} (resp. \var{ds} if not null) is a delimiter:
the buffer is transferred until a null character or the delimiter is encountered.
The number of characters actually transferred is returned.
\var{str} is always terminated by a null character.
?*/
int
IvlMsgBuffer :: ReadString (char* str, const char* ds, int n)
{
	return GetString (str, n, ds, false);
}

/*?
Get a message from the buffer.
The message must be prefixed by its length, as done by \fun{Append(IvlMessage*)}.
The virtual function \fun{ReadFrom} of the message is called to convert the buffer into a message.
If there is not enough data in the buffer, false is returned.
If \fun{ReadFrom} reads past the end of the message,
false is returned and the get error flag is set.
?*/
bool
IvlMsgBuffer :: ReadMsg (IvlMessage& msg)
{
	if (GetErr || (Stop - Start < lwsize))
		return false;
		
	// get length
	lword l = Stop - Start;
	lword len = 0;
	memcpy ((byte*) &len, Start, lwsize);
	
	// check that buffer is big enough
	if (l < len)
		return false;
	
	// read from buffer
	Start += lwsize;
	msg.ReadFrom (*this, len);
	
	// align to length
	lword rl = l - (Stop - Start);
	if (rl == len) {
		return true;
	} else
	if (rl < len) {
		Flush ((int) len - (int) rl);
		return true;
	} else {
		GetErr = true;
		return false;
	}
}

//------ peek operations

/*?nextdoc?*/
bool
IvlMsgBuffer :: PeekByte (byte& b, int offset)
{
	return GetBuf (&b, 1, true, offset);
}

/*?nextdoc?*/
bool
IvlMsgBuffer :: PeekShort (sword& sw, int offset)
{
	return GetBuf ((byte*) &sw, swsize, true, offset);
}

/*?nextdoc?*/
bool
IvlMsgBuffer :: PeekLong (lword& lw, int offset)
{
	return GetBuf ((byte*) &lw, lwsize, true, offset);
}

/*?
These functions extract a byte, a short word, a long word, a byte array
at \var{offset} bytes from the start of the buffer.
They return false if the data to peek falls outside the buffer, else true.
?*/
bool
IvlMsgBuffer :: PeekBuf (byte* b, int n, int offset)
{
	return  GetBuf (b, n, true, offset);
}

int
IvlMsgBuffer :: PeekString (IvlString& s, int offset)
{
	if (GetErr)
		return 0;

	int n = Stop - Start - offset;
	byte* p = Start + offset;
	while (n-- && *p)
		++p;

	int l = p - Start;
	
	s.Assign ((const char*) (Start + offset), l);
	return l;
}

/*?nextdoc?*/
int
IvlMsgBuffer :: PeekString (char* str, int n, char delim, int offset)
{
	char ds [2];
	ds [0] = delim;
	ds [1] = 0;
	return GetString (str, n, ds, true, offset);
}

/*?
Get at most \var{n} characters from the buffer into \var{str}.
\var{delim} (resp. \var{ds} if not null) is a delimiter:
the buffer is transferred until a null character or the delimiter is encountered.
The number of characters actually transferred is returned.
\var{str} is always terminated by a null character.
?*/
int
IvlMsgBuffer :: PeekString (char* str, int n, const char* delim, int offset)
{
	return GetString (str, n, delim, true, offset);
}

//-----	miscellaneous
//

/*?
Extend the buffer's contents by \var{n} bytes.
This function is useful when data has been appended to the buffer without
using one of the \fun{Append} functions.
For instance, to read \var{n} bytes from a Unix file descriptor into a buffer,
you would do:
\begin{ccode}
b.NeedSize (n);
int nb = read (fd, (char*) Free (), n);
if (nb > 0)
    b.More (n);
\end{ccode}
?*/
void
IvlMsgBuffer :: More (int n)
{
	GetErr = false;
	if (End)			// Begin == 0 for fake buffers
		Stop += n;
}

/*?
Discard the \var{n} last bytes of the buffer.
This is useful to remove erroneous data that has just been appended to the buffer.
This is in some sense the reverse operation of \fun{More}.
?*/
void
IvlMsgBuffer :: Discard (int n)
{
	if (! Begin)
		if (! End)		// ! Begin && End => fake buffer
			return;
	if (Stop - n <= Start) {
		Start = Stop = Begin;
		// free if too big
		if (MaxSize > 0 && End - Start >= MaxSize)
			Clear ();
	} else
		Stop -= n;
	
}

#ifdef DOC
// fake entries for inline functions

/*?nextdoc?*/
byte*
IvlMsgBuffer :: Buffer ()
{ }

/*?
Return the address of the beginning of the buffer and the length of the buffer.
This is used in conjunction with \fun{Flush} to extract data from the buffer, as in the following example:
\begin{ccode}
byte* p = b.Buffer ();
int n = b.BufLength ();
n = write (fd, (const char*) p, n);
if (n > 0)
    b.Flush (n);
\end{ccode}
?*/
int
IvlMsgBuffer :: BufLength ()
{ }

/*?nextdoc?*/
byte*
IvlMsgBuffer :: Free ()
{ }

/*?
Return the address of the first free byte in the buffer and the number of free bytes.
This may be used in conjunction with \fun{NeedSize} and \fun{More}
to append data to the buffer.
?*/
int
IvlMsgBuffer :: FreeLength ()
{ }

/*?
Grow the buffer if its free size is less than its grow size.
This function can be called when a buffer is full.
?*/
void
IvlMsgBuffer :: Grow ()
{ }

/*?
This operator is equivalent to the \fun{Append} operations.
The type of the data can be a long word, a short word, a byte, a character, or a string;
for strings, the null character is included.
The operator returns the buffer so that several items can be added.
?*/
IvlMsgBuffer&
IvlMsgBuffer :: operator << (type data)
{ }

/*?nextdoc?*/
IvlMsgBuffer&
IvlMsgBuffer :: operator >> (type* data)
{ }

/*?
This operator is equivalent to the \fun{Get} operations.
The type of the data can be a long word, a short word, a byte, or a character.
The operator returns the buffer so that several items can be read.
Errors can be tested by the functions \fun{Error} and \fun{Ok}.
?*/
IvlMsgBuffer&
IvlMsgBuffer :: operator >> (type& data)
{ }

/*?nextdoc?*/
bool
IvlMsgBuffer :: Error ()
{ }

/*?
Test the state of the buffer, as set by the get functions.
\fun{Error} returns true if a get error has occurred.
\fun{Ok} is the negation of \fun{Error}.
?*/
bool
IvlMsgBuffer :: Ok ()
{ }

/*?
Reset the error flag.
The error flag is automatically reset by the functions \fun{Append} and \fun{More},
and by \fun{operator $<<$}.
?*/
void
IvlMsgBuffer :: ResetError ()
{ }

#endif /* DOC */