updates.
[silc.git] / lib / silcutil / silcbufutil.h
1 /*
2
3   silcbufutil.h
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2000 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20
21 #ifndef SILCBUFUTIL_H
22 #define SILCBUFUTIL_H
23
24 #include "silcbuffer.h"
25
26 /* Clears and initialiazes the buffer to the state as if it was just
27    allocated by silc_buffer_alloc. */
28
29 static inline
30 void silc_buffer_clear(SilcBuffer sb)
31 {
32   memset(sb->head, 0, sb->truelen);
33   sb->data = sb->head;
34   sb->tail = sb->head;
35   sb->len = 0;
36 }
37
38 /* Generates copy of a SilcBuffer. This copies everything inside the
39    currently valid data area, nothing more. Use silc_buffer_clone to
40    copy entire buffer. */
41
42 static inline
43 SilcBuffer silc_buffer_copy(SilcBuffer sb)
44 {
45   SilcBuffer sb_new;
46
47   sb_new = silc_buffer_alloc(sb->len);
48   silc_buffer_pull_tail(sb_new, SILC_BUFFER_END(sb_new));
49   silc_buffer_put(sb_new, sb->data, sb->len);
50
51   return sb_new;
52 }
53
54 /* Clones SilcBuffer. This generates new SilcBuffer and copies
55    everything from the source buffer. The result is exact clone of
56    the original buffer. */
57
58 static inline
59 SilcBuffer silc_buffer_clone(SilcBuffer sb)
60 {
61   SilcBuffer sb_new;
62
63   sb_new = silc_buffer_alloc(sb->truelen);
64   silc_buffer_pull_tail(sb_new, SILC_BUFFER_END(sb_new));
65   silc_buffer_put(sb_new, sb->head, sb->truelen);
66   sb_new->data = sb_new->head + (sb->data - sb->head);
67   sb_new->tail = sb_new->data + sb->len;
68   sb_new->len = sb->len;
69
70   return sb_new;
71 }
72
73 /* Reallocates buffer. Old data is saved into the new buffer. Returns
74    new SilcBuffer pointer. The buffer is exact clone of the old one
75    except that there is now more space at the end of buffer. */
76
77 static inline
78 SilcBuffer silc_buffer_realloc(SilcBuffer sb, uint32 newsize)
79 {
80   SilcBuffer sb_new;
81
82   if (!sb)
83     return silc_buffer_alloc(newsize);
84
85   if (newsize <= sb->truelen)
86     return sb;
87
88   sb_new = silc_buffer_alloc(newsize);
89   silc_buffer_pull_tail(sb_new, SILC_BUFFER_END(sb_new));
90   silc_buffer_put(sb_new, sb->head, sb->truelen);
91   sb_new->data = sb_new->head + (sb->data - sb->head);
92   sb_new->tail = sb_new->data + sb->len;
93   sb_new->len = sb->len;
94
95   silc_buffer_free(sb);
96
97   return sb_new;
98 }
99
100 #endif