tampon.c (1260B)
1 #include <assert.h> 2 #include <stdlib.h> 3 4 #include "general.h" 5 #include "tampon.h" 6 7 #define tp_invariants(t) \ 8 (assert((t)), \ 9 assert((t)->tp), \ 10 assert((t)->po), \ 11 assert((t)->po >= (t)->tp), \ 12 assert((t)->oc >= 0), \ 13 assert((t)->tll >= (t)->ol)) 14 15 int 16 tp_init(struct tampon *tp, size_t tll) 17 { 18 assert(tp); 19 assert(tll >= 1); 20 21 if ((tp->tp = malloc(tll)) == NULL) 22 return -1; 23 tp->po = tp->tp; 24 tp->tll = tp->ol = tll; 25 tp->oc = 0; 26 27 tp_invariants(tp); 28 29 return 0; 30 } 31 32 int 33 tp_ecr(struct tampon *tp, char c) 34 { 35 tp_invariants(tp); 36 37 if (tp->ol > 0) { 38 tp->ol--; 39 *tp->po++ = c; 40 tp_invariants(tp); 41 return (unsigned char) c; 42 } 43 44 return -1; 45 } 46 47 void 48 tp_reinit(struct tampon *tp) 49 { 50 tp_invariants(tp); 51 52 tp->ol = tp->tll; 53 tp->po = tp->tp; 54 if (tp->oc > 0) { 55 char *src; 56 tp->ol -= tp->oc; 57 src = tp->tp + tp->tll - tp->oc; 58 while (tp->oc-- > 0) 59 *tp->po++ = *src++; 60 tp->oc = 0; 61 } 62 63 tp_invariants(tp); 64 } 65 66 int 67 tp_terminer(struct tampon *tp) 68 { 69 tp_invariants(tp); 70 71 if (tp->ol == 0) { 72 if ((tp->oc = utf8_trop(tp->tp, tp->po-1)) < 0) { 73 tp->oc = 0; 74 return -1; 75 } 76 } 77 78 tp_invariants(tp); 79 80 return 0; 81 } 82 83 size_t 84 tp_longueur(struct tampon *tp) 85 { 86 tp_invariants(tp); 87 88 return tp->tll - tp->ol - tp->oc; 89 }