1 /* $OpenBSD: paste.c,v 1.6 2009/11/03 17:17:24 nicm Exp $ */ 2 3 /* 4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net> 5 * 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. 9 * 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. 17 */ 18 19 #include <sys/types.h> 20 #include <sys/time.h> 21 22 #include <string.h> 23 24 #include "tmux.h" 25 26 void 27 paste_init_stack(struct paste_stack *ps) 28 { 29 ARRAY_INIT(ps); 30 } 31 32 void 33 paste_free_stack(struct paste_stack *ps) 34 { 35 while (paste_free_top(ps) == 0) 36 ; 37 } 38 39 struct paste_buffer * 40 paste_walk_stack(struct paste_stack *ps, uint *idx) 41 { 42 struct paste_buffer *pb; 43 44 pb = paste_get_index(ps, *idx); 45 (*idx)++; 46 return (pb); 47 } 48 49 struct paste_buffer * 50 paste_get_top(struct paste_stack *ps) 51 { 52 if (ARRAY_LENGTH(ps) == 0) 53 return (NULL); 54 return (ARRAY_FIRST(ps)); 55 } 56 57 struct paste_buffer * 58 paste_get_index(struct paste_stack *ps, u_int idx) 59 { 60 if (idx >= ARRAY_LENGTH(ps)) 61 return (NULL); 62 return (ARRAY_ITEM(ps, idx)); 63 } 64 65 int 66 paste_free_top(struct paste_stack *ps) 67 { 68 struct paste_buffer *pb; 69 70 if (ARRAY_LENGTH(ps) == 0) 71 return (-1); 72 73 pb = ARRAY_FIRST(ps); 74 ARRAY_REMOVE(ps, 0); 75 76 xfree(pb->data); 77 xfree(pb); 78 79 return (0); 80 } 81 82 int 83 paste_free_index(struct paste_stack *ps, u_int idx) 84 { 85 struct paste_buffer *pb; 86 87 if (idx >= ARRAY_LENGTH(ps)) 88 return (-1); 89 90 pb = ARRAY_ITEM(ps, idx); 91 ARRAY_REMOVE(ps, idx); 92 93 xfree(pb->data); 94 xfree(pb); 95 96 return (0); 97 } 98 99 void 100 paste_add(struct paste_stack *ps, u_char *data, size_t size, u_int limit) 101 { 102 struct paste_buffer *pb; 103 104 if (*data == '\0') 105 return; 106 107 while (ARRAY_LENGTH(ps) >= limit) { 108 pb = ARRAY_LAST(ps); 109 xfree(pb->data); 110 xfree(pb); 111 ARRAY_TRUNC(ps, 1); 112 } 113 114 pb = xmalloc(sizeof *pb); 115 ARRAY_INSERT(ps, 0, pb); 116 117 pb->data = data; 118 pb->size = size; 119 } 120 121 int 122 paste_replace(struct paste_stack *ps, u_int idx, u_char *data, size_t size) 123 { 124 struct paste_buffer *pb; 125 126 if (idx >= ARRAY_LENGTH(ps)) 127 return (-1); 128 129 pb = ARRAY_ITEM(ps, idx); 130 xfree(pb->data); 131 132 pb->data = data; 133 pb->size = size; 134 135 return (0); 136 } 137