1 /* $OpenBSD: paste.c,v 1.2 2009/07/02 16:15:43 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, char *data, u_int limit) 101 { 102 struct paste_buffer *pb; 103 104 if (*data == '\0') 105 return; 106 107 while (ARRAY_LENGTH(ps) >= limit) 108 ARRAY_TRUNC(ps, 1); 109 110 pb = xmalloc(sizeof *pb); 111 ARRAY_INSERT(ps, 0, pb); 112 113 pb->data = data; 114 if (gettimeofday(&pb->tv, NULL) != 0) 115 fatal("gettimeofday"); 116 } 117 118 int 119 paste_replace(struct paste_stack *ps, u_int idx, char *data) 120 { 121 struct paste_buffer *pb; 122 123 if (idx >= ARRAY_LENGTH(ps)) 124 return (-1); 125 126 pb = ARRAY_ITEM(ps, idx); 127 xfree(pb->data); 128 129 pb->data = data; 130 if (gettimeofday(&pb->tv, NULL) != 0) 131 fatal("gettimeofday"); 132 133 return (0); 134 } 135