4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
28 * Stack of paste buffers. Note that paste buffer data is not necessarily a C
33 paste_init_stack(struct paste_stack
*ps
)
39 paste_free_stack(struct paste_stack
*ps
)
41 while (paste_free_top(ps
) == 0)
45 /* Return each item of the stack in turn. */
47 paste_walk_stack(struct paste_stack
*ps
, uint
*idx
)
49 struct paste_buffer
*pb
;
51 pb
= paste_get_index(ps
, *idx
);
56 /* Get the top item on the stack. */
58 paste_get_top(struct paste_stack
*ps
)
60 if (ARRAY_LENGTH(ps
) == 0)
62 return (ARRAY_FIRST(ps
));
65 /* Get an item by its index. */
67 paste_get_index(struct paste_stack
*ps
, u_int idx
)
69 if (idx
>= ARRAY_LENGTH(ps
))
71 return (ARRAY_ITEM(ps
, idx
));
74 /* Free the top item on the stack. */
76 paste_free_top(struct paste_stack
*ps
)
78 struct paste_buffer
*pb
;
80 if (ARRAY_LENGTH(ps
) == 0)
92 /* Free an item by index. */
94 paste_free_index(struct paste_stack
*ps
, u_int idx
)
96 struct paste_buffer
*pb
;
98 if (idx
>= ARRAY_LENGTH(ps
))
101 pb
= ARRAY_ITEM(ps
, idx
);
102 ARRAY_REMOVE(ps
, idx
);
111 * Add an item onto the top of the stack, freeing the bottom if at limit. Note
112 * that the caller is responsible for allocating data.
115 paste_add(struct paste_stack
*ps
, char *data
, size_t size
, u_int limit
)
117 struct paste_buffer
*pb
;
122 while (ARRAY_LENGTH(ps
) >= limit
) {
129 pb
= xmalloc(sizeof *pb
);
130 ARRAY_INSERT(ps
, 0, pb
);
138 * Replace an item on the stack. Note that the caller is responsible for
142 paste_replace(struct paste_stack
*ps
, u_int idx
, char *data
, size_t size
)
144 struct paste_buffer
*pb
;
149 if (idx
>= ARRAY_LENGTH(ps
))
152 pb
= ARRAY_ITEM(ps
, idx
);
161 /* Convert a buffer into a visible string. */
163 paste_print(struct paste_buffer
*pb
, size_t width
)
170 buf
= xmalloc(width
* 4 + 1);
176 used
= strvisx(buf
, pb
->data
, len
, VIS_OCTAL
|VIS_TAB
|VIS_NL
);
177 if (pb
->size
> width
|| used
> width
) {
178 buf
[width
- 3] = '\0';
179 strlcat(buf
, "...", width
);