repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
github188/catlib
include/cat/netinc.h
<gh_stars>1-10 /* * cat/netinc.h -- standard headers to include in a network application * * <NAME> * * Copyright 1999-2012 -- See accompanying license * */ #ifndef __CAT_NETINC_H #define __CAT_NETINC_H /* Here go all of the include files for the networking code */ #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/un.h> #include <sys/select.h> #include <poll.h> #include <sys/ioctl.h> /* XXX do we want these always? */ #include <pthread.h> #include <string.h> #include <strings.h> #include <stdarg.h> #include <syslog.h> #ifndef SUN_LEN #define SUN_LEN(su) \ (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path)) #endif /* SUN_LEN */ #endif /* __CAT_NETINC_H */
github188/catlib
src/mem.c
/* * mem.c -- memory management interface * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> #include <stdlib.h> void *mem_get(struct memmgr *mm, size_t len) { if ( !mm || !mm->mm_alloc ) return NULL; return mm->mm_alloc(mm, len); } void *mem_resize(struct memmgr *mm, void *mem, size_t len) { if ( !mm || !mm->mm_resize ) return NULL; return mm->mm_resize(mm, mem, len); } void mem_free(struct memmgr *mm, void *mem) { if ( !mm || !mm->mm_free ) return; mm->mm_free(mm, mem); } void applyfree(void *data, void *mp) { struct memmgr *mm = mp; mm->mm_free(mm, data); } static void *amm_get_hi2lo(struct memmgr *mm, size_t len) { struct arraymm *amm = container(mm, struct arraymm, mm); size_t nu = (len + (1 << amm->alignp2) - 1) >> amm->alignp2; if ( nu > amm->mlen - amm->fill ) return NULL; amm->fill += nu; return amm->mem - (amm->fill << amm->alignp2); } static void *amm_get_lo2hi(struct memmgr *mm, size_t len) { struct arraymm *amm = container(mm, struct arraymm, mm); size_t nu = (len + (1 << amm->alignp2) - 1) >> amm->alignp2; void *a; if ( nu > amm->mlen - amm->fill ) return NULL; a = amm->mem + (amm->fill << amm->alignp2); amm->fill += nu; return a; } void amm_init(struct arraymm *amm, void *mem, size_t mlen, int align, int hi2lo) { int i = 0; abort_unless(amm && mem && mlen > 0 && align >= 0 && !(align & (align-1))); if ( align == 0 ) align = sizeof(cat_align_t); while ( (align >>= 1) > 0 ) /* Dumb log base-2 */ ++i; amm->fill = 0; amm->alignp2 = i; amm->mlen = mlen >> i; if ( hi2lo ) { amm->mm.mm_alloc = amm_get_hi2lo; amm->mem = (byte_t *)mem + (amm->mlen << i); } else { amm->mm.mm_alloc = amm_get_lo2hi; amm->mem = mem; } amm->mm.mm_resize = NULL; amm->mm.mm_free = NULL; amm->mm.mm_ctx = amm; amm->hi2lo = hi2lo; } void amm_reset(struct arraymm *amm) { abort_unless(amm); amm->fill = 0; } size_t amm_get_fill(struct arraymm *amm) { abort_unless(amm); return amm->fill << amm->alignp2; } size_t amm_get_avail(struct arraymm *amm) { abort_unless(amm); return (amm->mlen - amm->fill) << amm->alignp2; } static void * std_alloc(struct memmgr *mm, size_t size) { abort_unless(mm && size > 0); return malloc(size); } static void * std_resize(struct memmgr *mm, void *old, size_t newsize) { abort_unless(mm && newsize > 0); return realloc(old, newsize); } static void std_free(struct memmgr *mm, void *old) { abort_unless(mm); free(old); } struct memmgr stdmm = { std_alloc, std_resize, std_free, &stdmm };
github188/catlib
src/dynmem.c
<reponame>github188/catlib /* * src/dynmem.c -- Dynamic memory management * * by <NAME> * * Copyright 2008-2015 See accompanying license * */ #include <cat/dynmem.h> #include <cat/archops.h> #include <string.h> union dynmempool_u { union align_u u; struct dynmempool p; }; #define sizetonu(n) (((size_t)(n) + UNITSIZE - 1) / UNITSIZE) #define nutosize(n) ((size_t)(n) * UNITSIZE) #define round2u(n) (nutosize(sizetonu(n))) #define MINNU sizetonu(sizeof(struct memblk)+UNITSIZE) #define MINSZ (MINNU * UNITSIZE) #define MINASZ nutosize(MINNU + 2) #define mb2ptr(mb) ((void *)((union align_u *)(mb) + 1)) #define ptr2mb(ptr) ((struct memblk *)((union align_u *)(ptr) - 1)) #define ALLOC_BIT ((size_t)1) #define PREV_ALLOC_BIT ((size_t)2) #define CTLBMASK (ALLOC_BIT|PREV_ALLOC_BIT) #define MAX_ALLOC round2u((size_t)~0 - UNITSIZE) #define MBSIZE(p) (((union align_u *)(p))->sz & ~CTLBMASK) #define PTR2U(p, o) ((union align_u *)((char *)(p) + (o))) #ifndef CAT_MIN_MOREMEM #define CAT_MIN_MOREMEM 8192 #endif /* CAT_MIN_MOREMEM */ /* global data structures */ void *(*add_mem_func)(size_t len) = NULL; static void set_free_mb(struct memblk *mb, size_t size, size_t bits) { mb->mb_len.sz = size | bits; PTR2U(mb, size - UNITSIZE)->sz = size; } static struct memblk *split_block(struct memblk *mb, size_t amt) { struct memblk *nmb; size_t flags; /* caller must assure that amt is a multiple of UNITSIZE */ abort_unless(amt % UNITSIZE == 0); flags = mb->mb_len.sz & CTLBMASK; nmb = (struct memblk *)PTR2U(mb, amt); set_free_mb(nmb, MBSIZE(mb) - amt, flags); l_ins(&mb->mb_entry, &nmb->mb_entry); set_free_mb(mb, amt, flags); return mb; } static void mark_free(struct memblk *mb) { abort_unless(mb); /* note, we set the original PREV_ALLOC_BIT, but clear the ALLOC_BIT */ set_free_mb(mb, MBSIZE(mb), mb->mb_len.sz & PREV_ALLOC_BIT); } #define MERGEBACK 1 #define MERGEFRONT 2 static int coalesce(struct memblk **mbparam) { struct memblk *mb, *nmb; union align_u *unitp; size_t sz; int rv = 0; abort_unless(mbparam && *mbparam); mb = *mbparam; sz = MBSIZE(mb); if ( !(mb->mb_len.sz & PREV_ALLOC_BIT) ) { unitp = (union align_u *)mb - 1; mb = (struct memblk *)((char *)mb - unitp->sz); l_rem(&mb->mb_entry); sz += unitp->sz; /* note that we are using aggressive coalescing, so this */ /* the prev alloc bit must always be set here: be safe */ /* in case we decide to do delayed coalescing some time later */ set_free_mb(mb, sz, mb->mb_len.sz & CTLBMASK); rv |= MERGEBACK; } unitp = PTR2U(mb, sz); if ( !(unitp->sz & ALLOC_BIT) ) { nmb = (struct memblk *)unitp; l_rem(&nmb->mb_entry); sz += MBSIZE(nmb); set_free_mb(mb, sz, mb->mb_len.sz & CTLBMASK); rv |= MERGEFRONT; } else { unitp->sz &= ~PREV_ALLOC_BIT; } *mbparam = mb; return rv; } void dynmem_init(struct dynmem *dm) { l_init(&dm->dm_pools); l_init(&dm->dm_blocks); dm->dm_current = &dm->dm_blocks; dm->add_mem_func = NULL; dm->dm_init = 1; } static void dynmem_init_pool(struct dynmempool *pool, struct dynmem *dm, size_t tlen, size_t ulen, union align_u *start) { l_ins(dm->dm_pools.prev, &pool->dmp_entry); pool->dmp_total_len = tlen; pool->dmp_useable_len = ulen; pool->dmp_start = start; } void dynmem_add_pool(struct dynmem *dm, void *mem, size_t len) { struct memblk *obj; union dynmempool_u *pool_u; union align_u *unitp; size_t ulen; ulen = nutosize(len / UNITSIZE); /* round down to unit size */ abort_unless(ulen >= MINASZ); abort_unless((ulong)mem % UNITSIZE == 0); pool_u = mem; unitp = (union align_u *)(pool_u + 1); ulen -= sizeof(*pool_u) + UNITSIZE; dynmem_init_pool(&pool_u->p, dm, len, ulen, unitp); /* add sentiel at the end */ PTR2U(unitp, ulen)->sz = ALLOC_BIT; obj = (struct memblk *)unitp; obj->mb_len.sz = ulen | PREV_ALLOC_BIT; dynmem_free(dm, mb2ptr(obj)); } void *dynmem_malloc(struct dynmem *dm, size_t amt) { struct list *t; struct memblk *mb; void *mm = NULL; size_t moreamt; abort_unless(dm); /* the first condition tests for overflow */ amt += UNITSIZE; if ( !dm->dm_init || amt < UNITSIZE || amt > MAX_ALLOC ) return NULL; if ( amt < MINSZ ) amt = MINSZ; else amt = round2u(amt); /* round up size */ again: /* first fit search that starts at the previous allocation */ t = dm->dm_current; do { if ( t == &dm->dm_blocks ) { t = t->next; continue; } mb = container(t, struct memblk, mb_entry); if ( MBSIZE(mb) >= amt ) { if ( MBSIZE(mb) > amt + MINSZ ) mb = split_block(mb, amt); else amt = MBSIZE(mb); dm->dm_current = mb->mb_entry.next; l_rem(&mb->mb_entry); mb->mb_len.sz |= ALLOC_BIT; PTR2U(mb, amt)->sz |= PREV_ALLOC_BIT; return mb2ptr(mb); } t = t->next; } while ( t != dm->dm_current ); /* should not get here twice */ abort_unless(mm == NULL); if ( add_mem_func ) { /* add 2 units for boundary sentinels */ moreamt = amt + UNITSIZE + sizeof(union dynmempool_u); if ( moreamt < CAT_MIN_MOREMEM ) moreamt = CAT_MIN_MOREMEM; mm = (*add_mem_func)(moreamt); if ( !mm ) return NULL; else dynmem_add_pool(dm, mm, moreamt); goto again; } return NULL; } void dynmem_free(struct dynmem *dm, void *mem) { struct memblk *mb; abort_unless(dm); if ( !dm->dm_init || mem == NULL ) return; mb = ptr2mb(mem); mark_free(mb); coalesce(&mb); /* if the following block was "dm_current" adjust */ if (((char *)dm->dm_current >= (char *)mb) && ((char *)dm->dm_current < ((char *)mb + MBSIZE(mb)))) dm->dm_current = &mb->mb_entry; l_ins(dm->dm_current->prev, &mb->mb_entry); } #ifndef CAT_MIN_ALLOC_SHRINK #define CAT_MIN_ALLOC_SHRINK 128 #endif /* CAT_MIN_ALLOC_SHRINK */ static void shrink_alloc_block(struct dynmem *dm, struct memblk *mb, size_t sz) { size_t nbsz; struct memblk *nmb; union align_u *unitp; /* caller should assure that sz is a multiple of UNITSIZE */ abort_unless(sz % UNITSIZE == 0); nbsz = MBSIZE(mb) - sz; if ( !dm->dm_init || nbsz < MINSZ ) return; unitp = PTR2U(mb, MBSIZE(mb)); if ( !(unitp->sz & ALLOC_BIT) ) { /* expand the next block? OK if small since no fragmentation */ nbsz += MBSIZE(unitp); l_rem(&((struct memblk *)unitp)->mb_entry); /* remove the block and fall through to create the new one */ } else if ( nbsz < CAT_MIN_ALLOC_SHRINK ) { /* only shrink current block if size savings is worth it */ return; } nmb = (struct memblk *)PTR2U(mb, sz); set_free_mb(nmb, nbsz, PREV_ALLOC_BIT); l_ins(dm->dm_current, &nmb->mb_entry); mb->mb_len.sz = sz | (mb->mb_len.sz & CTLBMASK); } void *dynmem_realloc(struct dynmem *dm, void *omem, size_t newamt) { void *nmem = NULL; struct memblk *mb; union align_u *lenp; size_t tsz; abort_unless(dm); if ( newamt == 0 ) { dynmem_free(dm, omem); return NULL; } if ( !omem ) return dynmem_malloc(dm, newamt); tsz = round2u(newamt); if ( (tsz < newamt) || (tsz > MAX_ALLOC - UNITSIZE) ) return NULL; newamt = tsz + UNITSIZE; mb = ptr2mb(omem); if ( mb->mb_len.sz >= newamt ) { shrink_alloc_block(dm, mb, newamt); return omem; } /* See if we can just add the next adjacent block */ lenp = PTR2U(mb, MBSIZE(mb)); if ( !(lenp->sz & ALLOC_BIT) ) { struct memblk *nmb = (struct memblk *)lenp; tsz = MBSIZE(mb) + MBSIZE(nmb); if ( tsz >= newamt ) { size_t delta = tsz - newamt; if ( MBSIZE(nmb) > delta + MINSZ ) nmb = split_block(nmb, delta); /* remove the block and merge it with the alloced one */ l_rem(&nmb->mb_entry); lenp = PTR2U(nmb, MBSIZE(nmb)); lenp->sz |= PREV_ALLOC_BIT; /* addition doesn't colide with flags since they are */ /* in the low order bits */ mb->mb_len.sz += MBSIZE(nmb); return mb2ptr(mb); } } /* at this point we need a completely new block and must copy */ nmem = dynmem_malloc(dm, newamt); if ( nmem ) { /* may copy more than the original alloc, but still in bounds */ memcpy(nmem, omem, MBSIZE(mb)); dynmem_free(dm, omem); } return nmem; } void dynmem_each_pool(struct dynmem *dm, apply_f f, void *ctx) { abort_unless(dm); l_apply(&dm->dm_pools, f, ctx); } void dynmem_each_block(struct dynmempool *pool, apply_f f, void *ctx) { union align_u *unitp, *endp; struct dynmem_block_fake blk; abort_unless(pool); abort_unless(f); unitp = pool->dmp_start; endp = (union align_u *)((char *)unitp + pool->dmp_useable_len); while ( unitp < endp ) { blk.ptr = unitp; blk.allocated = (unitp->sz & ALLOC_BIT) != 0; blk.prev_allocated = (unitp->sz & PREV_ALLOC_BIT) != 0; blk.size = MBSIZE(unitp); f(&blk, ctx); unitp = PTR2U(unitp, MBSIZE(unitp)); } } /* ----------------- Two-Layer Segregated Fit ----------------- */ STATIC_BUG_ON(bad_lg2_unitsize, ((1 << TLSF_LG2_UNITSIZE) != UNITSIZE)); #if CAT_DEBUG_LEVEL > 0 #define ASSERT(x) abort_unless(x) #else /* CAT_DEBUG_LEVEL > 0 */ #define ASSERT(x) #endif /* CAT_DEBUG_LEVEL > 0 */ static void tlsf_init_pool(struct tlsfpool *pool, struct tlsf *tlsf, size_t tlen, size_t ulen, union align_u *start); union tlsfpool_u { union align_u u; struct tlsfpool p; }; void tlsf_init(struct tlsf *tlsf) { int i; struct list *listp; struct tlsf_l2 *tl2; abort_unless((1 << TLSF_LG2_UNITSIZE) == UNITSIZE); abort_unless(tlsf); memset(tlsf, 0, sizeof(*tlsf)); l_init(&tlsf->tlsf_pools); for (i = 0; i < TLSF_NUMHEADS; i++) l_init(&tlsf->tlsf_lists[i]); listp = tlsf->tlsf_lists; /* NOTE, even though we initialize them, we never use bins */ /* for allocations of less that TLSF_MINSZ blocks. This will */ /* typically be about 3 lists wasted. But it makes the rest */ /* of the code cleaner. */ for (i = 0; i < TLSF_NUML2; i++) { tl2 = &tlsf->tlsf_l1[i]; tl2->tl2_blists = listp; if ( i < TLSF_NUMSMALL ) tl2->tl2_nblists = 1 << i; else tl2->tl2_nblists = TLSF_FULLBLLEN; listp += tl2->tl2_nblists; } abort_unless(listp - tlsf->tlsf_lists <= TLSF_NUMHEADS); } static int calc_tlsf_indices(struct tlsf *tlsf, size_t len) { int i, j, n; /* len must be a multiple of 4! */ ASSERT((len > 0) && (len & (UNITSIZE-1)) == 0); n = tlsf_nlz(len); ASSERT(n > 1 && n <= (TLSF_SZ_BITS - TLSF_LG2_UNITSIZE)); /* 1 << (i + LG2_UNITSIZE) is the first 1 bit in len */ i = (TLSF_SZ_BITS - 1 - TLSF_LG2_UNITSIZE) - n; /* subtract off the most significant bit */ j = len - (1 << (i + TLSF_LG2_UNITSIZE)); if ( len < (TLSF_FULLBLLEN * UNITSIZE) ) j /= UNITSIZE; else j >>= i - (TLSF_L2_LEN - TLSF_LG2_UNITSIZE); return (i << 8) + j; } static int round_next_tlsf_size(struct tlsf *tlsf, size_t amt, int idx) { int l1 = idx >> 8; int l2 = idx & 0xFF; size_t bktlen; ASSERT(tlsf && amt && idx > 0); /* the buffers up to including the first full-buffer list all */ /* have buckets that match the size of all requests exactly */ if ( l1 <= TLSF_L2_LEN ) return idx; bktlen = (1 << (l1 + TLSF_LG2_UNITSIZE)); bktlen += bktlen / TLSF_FULLBLLEN * l2; if ( amt <= bktlen ) return idx; l2 += 1; if ( l2 >= tlsf->tlsf_l1[l1].tl2_nblists ) { l1 += 1; l2 = 0; } if ( l1 >= TLSF_LG2_ALIM - TLSF_LG2_UNITSIZE ) return -1; return (l1 << 8) + l2; } static void tlsf_ins_blk(struct tlsf *tlsf, struct memblk *mb, int l1, int l2) { struct tlsf_l2 *tl2; ASSERT(tlsf); tlsf->tlsf_l1bm |= ((tlsf_sz_t)1 << l1); tl2 = &tlsf->tlsf_l1[l1]; tl2->tl2_bm |= ((tlsf_sz_t)1 << l2); l_ins(&tl2->tl2_blists[l2], &mb->mb_entry); } static void tlsf_ins_blk_c(struct tlsf *tlsf, struct memblk *mb) { int idx; idx = calc_tlsf_indices(tlsf, MBSIZE(mb)); tlsf_ins_blk(tlsf, mb, idx >> 8, idx & 0xFF); } static void tlsf_rem_blk(struct tlsf *tlsf, struct memblk *mb, int l1, int l2) { struct tlsf_l2 *tl2; l_rem(&mb->mb_entry); tl2 = &tlsf->tlsf_l1[l1]; if ( l_isempty(&tl2->tl2_blists[l2]) ) { tl2->tl2_bm &= ~((tlsf_sz_t)1 << l2); if ( tl2->tl2_bm == 0 ) tlsf->tlsf_l1bm &= ~((tlsf_sz_t)1 << l1); } } static void tlsf_rem_blk_c(struct tlsf *tlsf, struct memblk *mb) { int idx; idx = calc_tlsf_indices(tlsf, MBSIZE(mb)); tlsf_rem_blk(tlsf, mb, idx >> 8, idx & 0xFF); } /* remove a block, split a block in 2 and reinsert the second one, return */ /* the first block */ static struct memblk *tlsf_split_blk(struct tlsf *tlsf, struct memblk *mb, size_t amt) { struct memblk *nmb; size_t flags; /* caller must assure that amt is a multiple of UNITSIZE */ ASSERT(amt % UNITSIZE == 0); tlsf_rem_blk_c(tlsf, mb); flags = mb->mb_len.sz & CTLBMASK; nmb = (struct memblk *)PTR2U(mb, amt); set_free_mb(nmb, MBSIZE(mb) - amt, flags); set_free_mb(mb, amt, flags); tlsf_ins_blk_c(tlsf, nmb); return mb; } static void tlsf_coalesce_and_insert(struct tlsf *tlsf, struct memblk *mb) { struct memblk *nmb; union align_u *unitp; size_t sz; ASSERT(mb); /* mark the block free first */ sz = MBSIZE(mb); set_free_mb(mb, sz, mb->mb_len.sz & PREV_ALLOC_BIT); /* join with the previous block if it is free */ if ( !(mb->mb_len.sz & PREV_ALLOC_BIT) ) { unitp = (union align_u *)mb - 1; mb = (struct memblk *)((char *)mb - unitp->sz); sz += unitp->sz; tlsf_rem_blk_c(tlsf, mb); /* note that we are using aggressive coalescing, so this */ /* the prev alloc bit must always be set here: be safe */ /* in case we decide to do delayed coalescing some time later */ set_free_mb(mb, sz, PREV_ALLOC_BIT); } /* join with the next block if it is free */ unitp = PTR2U(mb, sz); if ( !(unitp->sz & ALLOC_BIT) ) { nmb = (struct memblk *)unitp; tlsf_rem_blk_c(tlsf, nmb); sz += MBSIZE(nmb); set_free_mb(mb, sz, PREV_ALLOC_BIT); } else { /* otherwise clear the next block's PREV_ALLOC_BIT */ unitp->sz &= ~PREV_ALLOC_BIT; } tlsf_ins_blk_c(tlsf, mb); } void tlsf_add_pool(struct tlsf *tlsf, void *mem, size_t len) { struct memblk *obj; union tlsfpool_u *pool_u; union align_u *unitp; size_t ulen; ulen = nutosize(len / UNITSIZE); /* round down to UNITSIZE */ ASSERT(ulen >= TLSF_MINPOOL + sizeof(*pool_u)); ASSERT((ulong)mem % UNITSIZE == 0); pool_u = mem; unitp = (union align_u *)(pool_u + 1); ulen -= sizeof(*pool_u) + UNITSIZE; tlsf_init_pool(&pool_u->p, tlsf, len, ulen, unitp); /* add sentiel at the end */ PTR2U(unitp, ulen)->sz = ALLOC_BIT; obj = (struct memblk *)unitp; obj->mb_len.sz = ulen | PREV_ALLOC_BIT | ALLOC_BIT; tlsf_free(tlsf, mb2ptr(obj)); } static void tlsf_init_pool(struct tlsfpool *pool, struct tlsf *tlsf, size_t tlen, size_t ulen, union align_u *start) { l_ins(tlsf->tlsf_pools.prev, &pool->tpl_entry); pool->tpl_total_len = tlen; pool->tpl_useable_len = ulen; pool->tpl_start = start; } static struct list *tlsf_find_blk(struct tlsf *tlsf, int *idx) { tlsf_sz_t n; int l1, l2; struct tlsf_l2 *tl2; ASSERT(tlsf && idx); l1 = (*idx) >> 8; l2 = (*idx) & 0xFF; /* first search for best fit within l2 bin */ tl2 = &tlsf->tlsf_l1[l1]; n = tl2->tl2_bm & ~(((tlsf_sz_t)1 << l2) - 1); if ( n == 0 ) { tlsf_sz_t tmp = (tlsf_sz_t)1 << l1; /* if there is no fit, search for the closest l1 */ /* rule out the current l1 */ n = tlsf->tlsf_l1bm & ~(tmp | (tmp - 1)); if ( n == 0 ) /* if still nothing, we're out of luck */ return NULL; l1 = tlsf_ntz(n); tl2 = &tlsf->tlsf_l1[l1]; l2 = tlsf_ntz(tl2->tl2_bm); } else { l2 = tlsf_ntz(n); } ASSERT(l2 < tl2->tl2_nblists); *idx = (l1 << 8) + l2; return &tl2->tl2_blists[l2]; } static void *tlsf_extract(struct tlsf *tlsf, struct list *head, size_t amt, int idx) { struct memblk *mb = container(l_head(head), struct memblk, mb_entry); union align_u *nextp; ASSERT(MBSIZE(mb) >= amt); if ( MBSIZE(mb) - amt >= TLSF_MINSZ ) { mb = tlsf_split_blk(tlsf, mb, amt); } else { tlsf_rem_blk(tlsf, mb, idx >> 8, idx & 0xFF); } mb->mb_len.sz |= ALLOC_BIT; nextp = PTR2U(mb, MBSIZE(mb)); nextp->sz |= PREV_ALLOC_BIT; return mb2ptr(mb); } void *tlsf_malloc(struct tlsf *tlsf, size_t req_size) { int idx; struct list *head; void *mm = NULL; size_t amt = req_size; ASSERT(tlsf); /* the first condition tests for overflow */ if ( amt < (TLSF_MINSZ - UNITSIZE) ) { amt = TLSF_MINSZ; } else { /* add in one UNIT and round up to UNITSIZE */ amt += (UNITSIZE << 1) - 1; amt &= ~(UNITSIZE - 1); /* check for overflow or size too big */ if ( amt >= TLSF_ALIM || amt < req_size ) return NULL; } idx = calc_tlsf_indices(tlsf, amt); idx = round_next_tlsf_size(tlsf, amt, idx); if ( idx < 0 ) return NULL; again: if ( (head = tlsf_find_blk(tlsf, &idx)) != NULL ) { return tlsf_extract(tlsf, head, amt, idx); } /* should not get here twice */ ASSERT(mm == NULL); if ( add_mem_func ) { size_t moreamt; /* add 2 units for boundary sentinels */ moreamt = amt + UNITSIZE + sizeof(union tlsfpool_u); if ( moreamt < CAT_MIN_MOREMEM ) moreamt = CAT_MIN_MOREMEM; mm = (*add_mem_func)(moreamt); if ( !mm ) return NULL; else tlsf_add_pool(tlsf, mm, moreamt); goto again; } return NULL; } void tlsf_free(struct tlsf *tlsf, void *mem) { ASSERT(tlsf); if ( mem == NULL ) return; tlsf_coalesce_and_insert(tlsf, ptr2mb(mem)); } static void tlsf_shrink_blk(struct tlsf *tlsf, struct memblk *mb, size_t sz) { size_t delta, nbsz; struct memblk *nmb; union align_u *unitp; /* caller should assure that sz is a multiple of UNITSIZE */ ASSERT(sz % UNITSIZE == 0); delta = nutosize((MBSIZE(mb) - sz) / UNITSIZE); if ( delta < TLSF_MINSZ ) return; unitp = PTR2U(mb, MBSIZE(mb)); if ( !(unitp->sz & ALLOC_BIT) ) { nmb = (struct memblk *)unitp; nbsz = MBSIZE(nmb); tlsf_rem_blk_c(tlsf, nmb); nbsz += delta; nmb = (struct memblk *)((char *)nmb - delta); } else if ( delta < CAT_MIN_ALLOC_SHRINK ) { /* only shrink current block if size savings is worth it */ return; } else { unitp->sz &= ~PREV_ALLOC_BIT; nbsz = delta; nmb = (struct memblk *)PTR2U(mb, sz); } set_free_mb(nmb, nbsz, PREV_ALLOC_BIT); tlsf_ins_blk_c(tlsf, nmb); mb->mb_len.sz = sz | (mb->mb_len.sz & CTLBMASK); } void *tlsf_realloc(struct tlsf *tlsf, void *omem, size_t newamt) { void *nmem = NULL; struct memblk *mb; union align_u *lenp; size_t tsz, osize; ASSERT(tlsf); if ( newamt == 0 ) { tlsf_free(tlsf, omem); return NULL; } if ( !omem ) return tlsf_malloc(tlsf, newamt); tsz = round2u(newamt); if ( (tsz < newamt) || (tsz > MAX_ALLOC - UNITSIZE) ) return NULL; newamt = tsz + UNITSIZE; mb = ptr2mb(omem); osize = MBSIZE(mb) - sizeof(union align_u); if ( mb->mb_len.sz >= newamt ) { tlsf_shrink_blk(tlsf, mb, newamt); return omem; } /* See if we can just add the next adjacent block */ lenp = PTR2U(mb, MBSIZE(mb)); if ( !(lenp->sz & ALLOC_BIT) ) { size_t delta = round2u(newamt - MBSIZE(mb)); size_t nextsz = MBSIZE(lenp); if ( delta <= nextsz ) { struct memblk *nmb = (struct memblk *)lenp; if ( nextsz > delta + TLSF_MINSZ ) nmb = tlsf_split_blk(tlsf, nmb, delta); else tlsf_rem_blk_c(tlsf, nmb); lenp = PTR2U(nmb, MBSIZE(nmb)); lenp->sz |= PREV_ALLOC_BIT; /* addition doesn't colide with flags since they are */ /* in the low order bits */ mb->mb_len.sz += MBSIZE(nmb); return mb2ptr(mb); } } /* at this point we need a completely new block and must copy */ nmem = tlsf_malloc(tlsf, newamt); if ( nmem ) { /* may copy more than the original alloc, but still in bounds */ memcpy(nmem, omem, osize); tlsf_free(tlsf, omem); } return nmem; } void tlsf_each_pool(struct tlsf *tlsf, apply_f f, void *ctx) { ASSERT(tlsf); ASSERT(f); l_apply(&tlsf->tlsf_pools, f, ctx); } void tlsf_each_block(struct tlsfpool *pool, apply_f f, void *ctx) { union align_u *unitp, *endp; struct tlsf_block_fake blk; ASSERT(pool); ASSERT(f); unitp = pool->tpl_start; endp = (union align_u *)((char *)unitp + pool->tpl_useable_len); while ( unitp < endp ) { blk.ptr = unitp; blk.allocated = (unitp->sz & ALLOC_BIT) != 0; blk.prev_allocated = (unitp->sz & PREV_ALLOC_BIT) != 0; blk.size = MBSIZE(unitp); f(&blk, ctx); unitp = PTR2U(unitp, MBSIZE(unitp)); } }
github188/catlib
src/net.c
/* * net.c -- Network functions * * <NAME> * * Copyright 1999-2012 -- see accompanying license * */ #include <cat/cat.h> #if CAT_HAS_POSIX #include <cat/net.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <sys/un.h> #include <errno.h> #include <fcntl.h> #ifndef CAT_HAS_ADDRINFO #define CAT_HAS_ADDRINFO 1 #endif #if CAT_HAS_ADDRINFO int net_resolv(const char *host, const char *serv, const char *proto, struct sockaddr_storage *sas) { struct addrinfo *res, *hintsp = NULL, hints; abort_unless(sas); if ( proto != NULL ) { hintsp = &hints; memset(hintsp, 0, sizeof(struct addrinfo)); hintsp->ai_family = AF_UNSPEC; if ( strcmp(proto, "tcp") == 0 ) { hintsp->ai_socktype = SOCK_STREAM; hintsp->ai_protocol = IPPROTO_TCP; } else if ( strcmp(proto, "udp") == 0 ) { hintsp->ai_socktype = SOCK_DGRAM; hintsp->ai_protocol = IPPROTO_UDP; } else { return -1; } } if ( getaddrinfo(host, serv, hintsp, &res) < 0 ) return -1; memcpy(sas, res->ai_addr, res->ai_addrlen); freeaddrinfo(res); return 0; } /* * This function is used to open a passive tcp socket. It uses hostname and * service to declare explicity which address and port to bind to if specified. * To for a connection from here do an accept()... */ int tcp_srv(const char *host, const char *serv) { int r, sock, set = 1; struct addrinfo hints, *res, *trav; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ( (r = getaddrinfo(host, serv, &hints, &res)) < 0 ) return -1; trav = res; do { sock = socket(trav->ai_family, trav->ai_socktype, trav->ai_protocol); if ( sock < 0 ) goto nextsock; if ( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set)) < 0 ) goto badsock; if ( !bind(sock, trav->ai_addr, trav->ai_addrlen) ) break; badsock: close(sock); nextsock: trav = trav->ai_next; } while (trav); if ( !trav ) return -3; listen(sock, 16); freeaddrinfo(res); return sock; } /* * This function opens a tcp connection to the address specified. It is * (theoretically) protocol independant. You can start reading and writing * from here. */ int tcp_cli(const char *host, const char *serv) { int r, sock; struct addrinfo hints, *res, *trav; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ( (r = getaddrinfo(host, serv, &hints, &res)) < 0 ) return -1; trav = res; do { sock = socket(trav->ai_family, trav->ai_socktype, trav->ai_protocol); if ( sock < 0 ) continue; if ( connect(sock, trav->ai_addr, trav->ai_addrlen) == 0 ) break; close(sock); trav = trav->ai_next; } while (trav); if ( !trav ) return -3; freeaddrinfo(res); return sock; } /* * This opens a passive udp socket on the system. The hostname and service * will specifiy the address and port if given. Addrlen returns the length * of the address (for protocol independence). */ int udp_sock(char *host, char *serv) { int r, sock, set = 1; struct addrinfo hints, *res, *trav; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_PASSIVE; hints.ai_socktype = SOCK_DGRAM; if ( (r = getaddrinfo(host, serv, &hints, &res)) < 0 ) return -1; trav = res; do { sock = socket(trav->ai_family, trav->ai_socktype, trav->ai_protocol); if ( sock < 0 ) goto nextsock; if ( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set)) < 0 ) goto badsock; if ( !bind(sock, trav->ai_addr, trav->ai_addrlen) ) break; badsock: close(sock); nextsock: trav = trav->ai_next; } while (trav); if ( !trav ) return -3; freeaddrinfo(res); return sock; } int tcp_cli_nb(const char *host, const char *serv) { int r, sock; int flags; struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ( (r = getaddrinfo(host, serv, &hints, &res)) < 0 ) return -1; sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if ( sock < 0 ) { r = -2; goto err; } flags = fcntl(sock, F_GETFL); if ( flags < 0 ) { r = -3; goto err; } flags |= O_NONBLOCK; if ( fcntl(sock, F_SETFL, flags) < 0 ) { goto err; } r = connect(sock, res->ai_addr, res->ai_addrlen); if ( (r == -1) && (errno == EINPROGRESS) ) r = 0; err: freeaddrinfo(res); return r; } #else /* CAT_HAS_ADDRINFO */ int net_resolv(const char *host, const char *serv, const char *proto, struct sockaddr_storage *sas) { struct hostent *hp; struct servent *sp; ulong portnum; char *cp; struct sockaddr_in *sin = (struct sockaddr_in *)sas; abort_unless(sas); memset(sas, 0, sizeof(struct sockaddr_in)); sin->sin_family = AF_INET; /* Look up the address */ if ( !host || !*host ) sin->sin_addr.s_addr = INADDR_ANY; else if ( inet_pton(AF_INET, host, &sin->sin_addr.s_addr) ) ; else if ( (hp = gethostbyname(host)) ) memcpy(&sin->sin_addr, hp->h_addr, hp->h_length); else return -1; /* now look up the service */ if (!serv || !*serv) { sin->sin_port = 0; goto skiplookup; } portnum = strtoul(serv, &cp, 0); if ( cp != serv ) { if ( portnum > 65535 ) return -1; sin->sin_port = htons(portnum); } else if ( (sp = getservbyname(serv, proto)) ) sin->sin_port = sp->s_port; else return -1; skiplookup: return 0; } /* * This function is used to open a passive tcp socket. It uses hostname and * service to declare explicity which address and port to bind to if specified. * The length of the address is returned in addrlen if addrlen != 0; To wait * for a connection from here do an Accept()... */ int tcp_srv(const char *host, const char *serv) { int sock, set = 1; struct sockaddr_storage sas; struct sockaddr_in *sin = (struct sockaddr_in *)&sas; if ( net_resolv(host, serv, "tcp", &sas) < 0 ) return -1; /* now we have the address to use */ if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) return -2; if ( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set))<0 ) { close(sock); return -3; } if ( bind(sock, (SA *)sin, sizeof(*sin)) < 0 ) { close(sock); return -4; } if ( listen(sock, CAT_LISTENQ) < 0 ) { close(sock); return -5; } return sock; } /* * This function opens a tcp connection to the address specified. It is * not protocol independant. You can start reading and writing * from here. */ int tcp_cli(const char *host, const char *serv) { int sock; struct sockaddr_storage sas; struct sockaddr_in *sin = (struct sockaddr_in *)&sas; if ( net_resolv(host, serv, "tcp", &sas) < 0 ) return -1; if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) return -2; if ( connect(sock, (SA *)sin, sizeof(*sin)) < 0 ) { close(sock); return -3; } return sock; } /* * This opens a passive udp socket on the system. The hostname and service * will specifiy the address and port if given. */ int udp_sock(char *host, char *serv) { int sock, set = 1; struct sockaddr_storage sas; struct sockaddr_in *sin = (struct sockaddr_in *)&sas; if ( net_resolv(host, serv, "udp", &sas) < 0 ) return -1; if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) return -2; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set)) < 0) { close(sock); return -3; } if ( bind(sock, (SA *)sin, sizeof(*sin)) < 0 ) { close(sock); return -4; } return sock; } int tcp_cli_nb(const char *host, const char *serv) { int sock; struct sockaddr_storage sas; int flags; struct sockaddr_in *sin = (struct sockaddr_in *)&sas; if ( net_resolv(host, serv, "tcp", &sas) < 0 ) return -1; if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) return -2; flags = fcntl(sock, F_GETFL); if ( flags < 0 ) return -3; flags |= O_NONBLOCK; if ( fcntl(sock, F_SETFL, flags) < 0 ) return -4; if ( connect(sock, (SA *)sin, sizeof(*sin)) < 0 ) { close(sock); return -5; } return sock; } #endif /* CAT_HAS_ADDRINFO */ char * net_tostr(struct sockaddr *sa, char *buf, size_t len) { abort_unless(len > 0); abort_unless(buf); switch ( sa->sa_family ) { case AF_INET : { struct sockaddr_in sin; uchar *p; /* XXX.XXX.XXX.XXX.XXXXX0 */ if ( len < 22 ) return NULL; sin = *(struct sockaddr_in *)sa; p = (uchar *)&sin.sin_addr; len = snprintf(buf, len, "%u.%u.%u.%u:%u", p[0], p[1], p[2], p[3], ntohs(sin.sin_port)); return buf; } break; #ifdef AF_INET6 case AF_INET6 : { char *p, *ap; char *off; ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; /* deliberately discard constant qualifier */ p = (char *)inet_ntop(sa->sa_family, ap, buf, len); if ( p == NULL ) return NULL; off = p + strlen(p); if ( (len - (off - p)) < 6 ) return NULL; snprintf(off, len - (off - p), ".%u", ntohs(((struct sockaddr_in6 *)sa)->sin6_port)); return p; } break; #endif /* IPV6 */ #ifdef AF_UNIX case AF_UNIX: { char *path = ((struct sockaddr_un *)sa)->sun_path; size_t plen = strlen(path) + 1; if ( len < plen ) return NULL; memcpy(buf, path, plen); return buf; } break; #endif /* AF_UNIX */ default: return NULL; } } int tcp_cli_nb_completion(int fd) { int err; socklen_t size = sizeof(err); abort_unless(fd < 0); if ( getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &size) < 0 ) return -1; return err; } #endif /* CAT_HAS_POSIX */
github188/catlib
src/io.c
/* * io.c -- Input/Output functions * * <NAME> * * Copyright 1999 - 2015 -- see accompanying license * */ #include <cat/cat.h> #if CAT_HAS_POSIX #include <cat/io.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/select.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> ssize_t io_read(int fd, void *buf, ssize_t nb) { byte_t *p = buf; ssize_t nr = 0; ssize_t n; abort_unless(fd >= 0); abort_unless(buf != NULL); abort_unless(nb >= 0); while (nr < nb) { if ( (n = read(fd, p, nb - nr)) < 0) { if ( (errno == EINTR) || (errno == EAGAIN) ) continue; else return -1; } else if (n == 0) break; nr += n; p += n; } return nr; } ssize_t io_write(int fd, void *buf, ssize_t nb) { byte_t *p = buf; ssize_t nw = 0; ssize_t n; abort_unless(fd >= 0); abort_unless(buf != NULL); abort_unless(nb >= 0); while ( nw < nb ) { if ( (n = write(fd, p, nb - nw)) < 0) { if ( (errno == EINTR) || (errno == EAGAIN) ) continue; else return -1; } else if ( n == 0 ) break; nw += n; p += n; } return nw; } ssize_t io_read_upto(int fd, void *buf, ssize_t nb) { byte_t *p = buf; ssize_t n; abort_unless(fd >= 0); abort_unless(buf != NULL); abort_unless(nb >= 0); while ( ((n = read(fd, p, nb)) == -1) && (errno == EINTR) ) ; return n; } ssize_t io_write_upto(int fd, void *buf, ssize_t nb) { byte_t *p = buf; ssize_t n; abort_unless(fd >= 0); abort_unless(buf != NULL); abort_unless(nb >= 0); while ( ((n = write(fd, p, nb)) == -1) && (errno == EINTR) ) ; return n; } int io_check_ready(int fd, int type, double timeout) { fd_set set, *rp = NULL, *wp = NULL, *ep = NULL; struct timeval tv, tvcopy = { 0 }, *tvp = NULL; abort_unless(fd >= 0); FD_ZERO(&set); FD_SET(fd, &set); if ( timeout > 0 ) { tvcopy.tv_sec = (long)timeout; timeout -= (long)timeout; tvcopy.tv_usec = (long)(timeout * 1000000.0); tvp = &tv; } if ( type == CAT_IOT_READ ) rp = &set; else if ( type == CAT_IOT_WRITE ) wp = &set; else if ( type == CAT_IOT_EXCEPT ) ep = &set; else { errno = EINVAL; return -1; } again: tv = tvcopy; if ( select(fd + 1, rp, wp, ep, tvp) < 0 ) { if ( errno == EINTR ) goto again; else return -1; } return FD_ISSET(fd, &set) ? 1 : 0; } int io_setnblk(int fd) { int flags; abort_unless(fd >= 0); flags = fcntl(fd, F_GETFL); if ( flags < 0 ) return -1; flags |= O_NONBLOCK; if ( fcntl(fd, F_SETFL, flags) < 0 ) return -1; else return 0; } int io_clrnblk(int fd) { int flags; abort_unless(fd >= 0); flags = fcntl(fd, F_GETFL); if ( flags < 0 ) return -1; flags &= ~O_NONBLOCK; if ( fcntl(fd, F_SETFL, flags) < 0 ) return -1; else return 0; } #endif /* CAT_HAS_POSIX */
github188/catlib
include/cat/cat.h
/* * cat/cat.h -- Info needed by most or all modules * * by <NAME> * * Copyright 2007-2015 -- See accompanying license * */ #ifndef __cat_cat_h #define __cat_cat_h #include <stddef.h> #include <cat/config.h> #ifndef CAT_USE_STDLIB #define CAT_USE_STDLIB 1 #endif /* CAT_USE_STDLIB */ #ifndef CAT_HAS_POSIX #define CAT_HAS_POSIX 1 #endif /* CAT_HAS_POSIX */ #ifndef CAT_ANSI89 #define CAT_ANSI89 0 #endif /* CAT_ANSI89 */ #ifndef CAT_USE_INLINE #define CAT_USE_INLINE 1 #endif /* CAT_USE_INLINE */ #if !defined(CAT_HAS_LONGLONG) || CAT_ANSI89 #undef CAT_HAS_LONGLONG #define CAT_HAS_LONGLONG 0 #endif /* CAT_HAS_LONGLONG */ #ifndef CAT_HAS_DIV #define CAT_HAS_DIV 1 #endif /* CAT_HAS_DIV */ #ifndef CAT_HAS_FLOAT #define CAT_HAS_FLOAT 1 #endif /* CAT_HAS_FLOAT */ #ifndef CAT_64BIT #define CAT_64BIT 0 #endif /* CAT_64BIT */ #ifndef CAT_DIE_DUMP #define CAT_DIE_DUMP 0 #endif /* CAT_DIE_DUMP */ #ifndef CAT_DEBUG_LEVEL #define CAT_DEBUG_LEVEL 0 #endif /* CAT_DEBUG_LEVEL */ #if CAT_USE_STDLIB #define CAT_USE_STDINT_TYPES 1 #endif /* CAT_USE_STDLIB */ /* Compile time assertions */ #define __STATIC_BUGNAME(name, line) __bug_on_##name##_##line #define STATIC_BUGNAME(name, line) __STATIC_BUGNAME(name, line) #define STATIC_BUG_ON(name, test) \ enum { STATIC_BUGNAME(name, __LINE__) = 1 / !(test) } typedef unsigned char byte_t; typedef signed char schar; #if CAT_HAS_LONGLONG typedef long long llong; #endif /* CAT_HAS_LONGLONG */ #ifndef CAT_NEED_UTYPEDEFS #define CAT_NEED_UTYPEDEFS 1 #endif /* CAT_NEED_UTYPEDEFS */ #if CAT_NEED_UTYPEDEFS typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; #if CAT_HAS_LONGLONG typedef unsigned long long ullong; #endif /* CAT_HAS_LONGLONG */ #endif /* CAT_NEED_UTYPEDEFS */ #ifdef CAT_USE_STDINT_TYPES #include <stdint.h> #elif CAT_USE_POSIX_TYPES #include <sys/types.h> #else /* no defined headers: take guess */ /* Reasonable guesses for a 8, 16, 32 or some 64 bit architectures. */ /* While these will always be at least wide enough, they may be too wide. */ /* Allow overrides during compilation */ #ifndef CAT_S8_T #define CAT_S8_T signed char #endif /* CAT_S8_T */ #ifndef CAT_U8_T #define CAT_U8_T unsigned char #endif /* CAT_U8_T */ #ifndef CAT_S16_T #define CAT_S16_T short #endif /* CAT_S16_T */ #ifndef CAT_U16_T #define CAT_U16_T unsigned short #endif /* CAT_U16_T */ #ifndef CAT_S32_T #define CAT_S32_T long #endif /* CAT_S32_T */ #ifndef CAT_U32_T #define CAT_U32_T unsigned long #endif /* CAT_U32_T */ /* * Define 64-bit types -- * If CAT_64BIT is true, that means our compiler supports some 64-bit type. * It _could_ be "long" or even "char". If CAT_HAS_LONGLONG is set, then * it is safe to set the 64-bit type to 'long long'. But if this isn't * set then set it to 'long'. The problem being that ANSI 89 compilers * don't need to support 'long long', but do need to support 'long'. */ #if CAT_64BIT #if CAT_HAS_LONGLONG #ifndef CAT_U64_T #define CAT_U64_T unsigned long long #endif /* CAT_U64_T */ #ifndef CAT_S64_T #define CAT_S64_T long long #endif /* CAT_S64_T */ #else /* CAT_HAS_LONGLONG */ #ifndef CAT_U64_T #define CAT_U64_T unsigned long #endif /* CAT_U64_T */ #ifndef CAT_S64_T #define CAT_S64_T long #endif /* CAT_S64_T */ #endif /* CAT_HAS_LONGLONG */ #endif /* CAT_64BIT */ typedef CAT_S8_T int8_t; typedef CAT_U8_T uint8_t; typedef CAT_S16_T int16_t; typedef CAT_U16_T uint16_t; typedef CAT_S32_T int32_t; typedef CAT_U32_T uint32_t; #if CAT_64BIT typedef CAT_S64_T int64_t; typedef CAT_U64_T uint64_t; #endif /* CAT_64BIT */ #endif /* no defined headers: take guess */ #if !CAT_HAS_INTPTR_T || (!CAT_USE_STDINT_TYPES && !CAT_USE_POSIX_TYPES) #if CAT_64BIT typedef CAT_S64_T intptr_t; #else /* CAT_64BIT */ typedef CAT_S32_T intptr_t; #endif /* CAT_64BIT */ #endif /* !CAT_HAS_INTPTR_T */ #if !CAT_HAS_UINTPTR_T || (!CAT_USE_STDINT_TYPES && !CAT_USE_POSIX_TYPES) #if CAT_64BIT typedef CAT_U64_T uintptr_t; #else /* CAT_64BIT */ typedef CAT_U32_T uintptr_t; #endif /* CAT_64BIT */ #endif /* !CAT_HAS_UINTPTR_T */ STATIC_BUG_ON(int8_t_size_not_equal_to_1, sizeof(int8_t) != 1); STATIC_BUG_ON(uint8_t_size_not_equal_to_1, sizeof(uint8_t) != 1); STATIC_BUG_ON(int16_t_size_not_equal_to_2, sizeof(int16_t) != 2); STATIC_BUG_ON(uint16_t_size_not_equal_to_2, sizeof(uint16_t) != 2); STATIC_BUG_ON(int32_t_size_not_equal_to_4, sizeof(int32_t) != 4); STATIC_BUG_ON(uint32_t_size_not_equal_to_4, sizeof(uint32_t) != 4); #if CAT_64BIT STATIC_BUG_ON(int64_t_size_not_equal_to_8, sizeof(int64_t) != 8); STATIC_BUG_ON(uint64_t_size_not_equal_to_8, sizeof(uint64_t) != 8); #endif /* CAT_64BIT */ STATIC_BUG_ON(intptr_t_lt_sizeof_voidptr, sizeof(intptr_t) < sizeof(void *)); STATIC_BUG_ON(uintptr_t_lt_sizeof_voidptr, sizeof(uintptr_t) < sizeof(void *)); /* CAT_ALIGN is a union representing the most restrictive alignment type */ #ifndef CAT_ALIGN typedef union { long l; void * p; double d; #if CAT_HAS_LONGLONG long long ll; #endif /* CAT_HAS_LONGLONG */ } cat_align_t; #define CAT_ALIGN cat_align_t #else /* CAT_ALIGN */ typedef CAT_ALIGN cat_align_t; #endif /* CAT_ALIGN */ /* ASSUMPTION: * all types in cat_align_t are worst case alignments: (e.g. ll is on 8-byte * boundaries). This does not generally hold but is safer than guessing * incorrectly. If a programmer knows specifically otherwise the coder can * #define CAT_ALIGN. */ #define CAT_ALIGN_SIZE(_x) \ (((_x)+(sizeof(cat_align_t)-1))/sizeof(cat_align_t)*sizeof(cat_align_t)) #define CAT_ALIGN_PTR_OFF(_p, _off) \ ((void *)((byte_t *)(_p) + CAT_ALIGN_SIZE(_off))) #define CAT_DECLARE_ALIGNED_DATA(_name, _len) \ CAT_DECLARE_ALIGNED_DATA_Q(,_name,_len) /* qual - (e.g. static volatile), name - variable name, len - in bytes */ #define CAT_DECLARE_ALIGNED_DATA_Q(_qual, _name, _len) \ qual CAT_ALIGN name[CAT_ALIGN_SIZE(_len) / sizeof(CAT_ALIGN)] /* We redefined this here because we might be including a c89 stddef.h */ #ifndef offsetof #define offsetof(type, field) ((ulong)&((type *)0)->field) #endif #define container(ptr, type, field) \ ((type *)((char*)(ptr)-offsetof(type,field))) #define array_length(arr) (sizeof(arr) / sizeof(arr[0])) #define ptr2int(p) ((intptr_t)(void *)(p)) #define ptr2uint(p) ((uintptr_t)(void *)(p)) #define int2ptr(i) ((void *)(uintptr_t)(i)) /* Preprocessor LOG2() operations */ #define FLOG2(x) ((x) < 1 ? -1 : \ (x) < 2 ? 0 : \ (x) < 4 ? 1 : \ (x) < 8 ? 2 : \ (x) < 16 ? 3 : \ (x) < 32 ? 4 : \ (x) < 64 ? 5 : \ (x) < 128 ? 6 : \ (x) < 256 ? 7 : \ (x) < 512 ? 8 : \ (x) < 1024 ? 9 : \ (x) <= 2 * 1024 ? 10 : \ (x) <= 4 * 1024 ? 11 : \ (x) <= 8 * 1024 ? 12 : \ (x) <= 16 * 1024 ? 13 : \ (x) <= 32 * 1024 ? 14 : \ (x) <= 64 * 1024 ? 15 : \ (x) <= 128 * 1024 ? 16 : \ (x) <= 256 * 1024 ? 17 : \ (x) <= 512 * 1024 ? 18 : \ (x) <= 1024 * 1024 ? 19 : \ (x) <= 2 * 1024 * 1024 ? 20 : \ (x) <= 4 * 1024 * 1024 ? 21 : \ (x) <= 8 * 1024 * 1024 ? 22 : \ (x) <= 16 * 1024 * 1024 ? 23 : \ (x) <= 32 * 1024 * 1024 ? 24 : \ (x) <= 64 * 1024 * 1024 ? 25 : \ (x) <= 128 * 1024 * 1024 ? 26 : \ (x) <= 256 * 1024 * 1024 ? 27 : \ (x) <= 512 * 1024 * 1024 ? 28 : \ (x) <= 1024 * 1024 * 1024 ? 29 : \ (x) <= 2 * 1024 * 1024 * 1024 ? 30 : \ 31) #define CLOG2(x) ((x) < 1 ? -1 : \ (x) == 1 ? 0 : \ (x) <= 2 ? 1 : \ (x) <= 4 ? 2 : \ (x) <= 8 ? 3 : \ (x) <= 16 ? 4 : \ (x) <= 32 ? 5 : \ (x) <= 64 ? 6 : \ (x) <= 128 ? 7 : \ (x) <= 256 ? 8 : \ (x) <= 512 ? 9 : \ (x) <= 1024 ? 10 : \ (x) <= 2 * 1024 ? 11 : \ (x) <= 4 * 1024 ? 12 : \ (x) <= 8 * 1024 ? 13 : \ (x) <= 16 * 1024 ? 14 : \ (x) <= 32 * 1024 ? 15 : \ (x) <= 64 * 1024 ? 16 : \ (x) <= 128 * 1024 ? 17 : \ (x) <= 256 * 1024 ? 18 : \ (x) <= 512 * 1024 ? 19 : \ (x) <= 1024 * 1024 ? 20 : \ (x) <= 2 * 1024 * 1024 ? 21 : \ (x) <= 4 * 1024 * 1024 ? 22 : \ (x) <= 8 * 1024 * 1024 ? 23 : \ (x) <= 16 * 1024 * 1024 ? 24 : \ (x) <= 32 * 1024 * 1024 ? 25 : \ (x) <= 64 * 1024 * 1024 ? 26 : \ (x) <= 128 * 1024 * 1024 ? 27 : \ (x) <= 256 * 1024 * 1024 ? 28 : \ (x) <= 512 * 1024 * 1024 ? 29 : \ (x) <= 1024 * 1024 * 1024 ? 30 : \ (x) <= 2 * 1024 * 1024 * 1024 ? 31 : \ 32) /* generic binary data container */ struct raw { size_t len; byte_t * data; } ; /* Generic scalar value union */ union attrib_u { int int_val; unsigned int uint_val; void * ptr_val; char * str_val; #if CAT_HAS_LONG_LONG long long llong_val; unsigned long long ullong_val; #endif /* CAT_HAS_LONG_LONG */ long long_val; unsigned long ulong_val; short short_val; unsigned short ushort_val; signed char sch_val; unsigned char uch_val; long double ldbl_val; double dbl_val; float float_val; struct raw raw_val; byte_t bytes[1]; cat_align_t align[1]; }; typedef union attrib_u attrib_t; #define attrib_csize(type, afld, asize) \ (offsetof(type, afld) + \ ((((asize) <= 1) ? 1 : (asize)) + sizeof(attrib_t) - 1) \ / sizeof(attrib_t) * sizeof(attrib_t)) /* Special function types */ typedef int (*cmp_f)(const void *v1, const void *v2); typedef void (*apply_f)(void *data, void *ctx); typedef int (*copy_f)(void *dst, void *src, void *ctx); extern void cat_abort(const char *fn, unsigned ln, const char *expr); #define abort_unless(x) \ do { if (!(x)) { cat_abort(__FILE__, __LINE__, #x); } } while (0) #endif /* __cat_cat_h */
github188/catlib
test/testhw.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <sys/time.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #define NREPS 10000 int nreps = NREPS; #define TEST(op) \ { \ struct timeval start, stop; \ double usec, nspo; \ int i; \ \ a = (a + 1) % NREPS; \ b = (b + 1) % NREPS; \ c = ((c + 1) % NREPS) + 1; \ gettimeofday(&start, NULL); \ for ( i = 1 ; i <= nreps; ++i ) \ { op; } \ gettimeofday(&stop, NULL); \ usec = (stop.tv_sec - start.tv_sec) * 1000000 + \ (stop.tv_usec - start.tv_usec);\ nspo = 1000 * usec / nreps; \ printf("%-40s\t%f\n", #op, nspo); \ fflush(stdout); \ } #define HEAD printf("%-40s\tnanoseconds\n", "Op"); \ printf("%-40s\t-----------\n", "--"); void f() { } struct obj { int (*opf)(volatile struct obj *, int); }; int op(volatile struct obj *op, int i) { return i; } int main(int argc, char *argv[]) { volatile int a, b=2, c=1, *ip; volatile float f1, f2, f3 = 1; volatile double d1, d2, d3 = 1; volatile struct { int a, b; char c; double d; } st, *stp = &st; volatile struct obj obj = { op }, *objp = &obj; volatile int arr[NREPS*2]; st.b = 1; if ( argc > 1 ) nreps = atoi(argv[1]); printf("Type: Size:\n"); printf("char %3u\n", (uint)sizeof(char)); printf("short %3u\n", (uint)sizeof(short)); printf("int %3u\n", (uint)sizeof(int)); printf("long %3u\n", (uint)sizeof(long)); printf("long long %3u\n", (uint)sizeof(long long)); printf("char * %3u\n", (uint)sizeof(char *)); printf("size_t %3u\n", (uint)sizeof(size_t)); printf("ssize_t %3u\n", (uint)sizeof(ssize_t)); printf("ptrdiff_t %3u\n", (uint)sizeof(ptrdiff_t)); printf("float %3u\n", (uint)sizeof(float)); printf("double %3u\n", (uint)sizeof(double)); printf("long double %3u\n", (uint)sizeof(long double)); printf("\nInteger operations\n"); HEAD TEST({}) TEST(a = 1) TEST(a = a + i) TEST(a = a - i) TEST(a = a * i) TEST(a = a / i) TEST(a = a % i) TEST(a = a << i) TEST(a = a >> i) TEST(a = a & i) TEST(a = a | i) TEST(a = a ^ i) TEST(a = ~i) TEST(a = !i) printf("\nFloating point operations\n"); HEAD TEST(f1 = 1) TEST(f1 = f2 + (float)i) TEST(f1 = f2 - (float)i) TEST(f1 = f2 * (float)i) TEST(f1 = f2 / (float)i) printf("\nDouble precision floating point operations\n"); HEAD TEST(d1 = 1) TEST(d1 = d2 + (double)i) TEST(d1 = d2 - (double)i) TEST(d1 = d2 * (double)i) TEST(d1 = d2 / (double)i) printf("\nArray operations\n"); HEAD TEST(arr[0] = 1) TEST(arr[c] = 1) TEST(a = arr[i] + a) TEST(a = a + arr[i]) TEST(arr[i] = arr[i] + arr[i>>1]) printf("\nPointers\n"); HEAD TEST(ip = &a) TEST(*ip = 1) TEST(*ip = b) TEST(stp = &st) TEST(stp->a = 5) TEST(stp->a = b) TEST(obj.opf(&obj, 3)) TEST(objp->opf(objp, 5)) printf("\nOther Statements\n"); HEAD TEST(if ( a < 5 ) b = 2) TEST(if ( arr[c] < 0 ) b = 2) TEST(a = (b < c) ? b : c) TEST(st.a = 1) TEST(a = b & st.b) TEST(if ( st.b ) a = b & st.b; else a = b % st.b) TEST(if (stp->b) a = b&stp->b; else a=b%stp->b) TEST(if ( !st.b ) a = b & st.b; else a = b % st.b) TEST(if (!stp->b) a = b&stp->b; else a=b%stp->b) TEST(f()) TEST(op(&obj, 10)) TEST(free(malloc(16))) TEST(free(malloc(200))) TEST(free(malloc(550))) TEST(free(malloc(65536))) TEST(free(malloc(65586))) return 0; }
github188/catlib
include/cat/str.h
/* * str.h -- string manipulation routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_str_h #define __cat_str_h #include <cat/cat.h> #include <stdarg.h> uchar chnval(char digit); size_t str_copy(char *dst, const char *src, size_t dlen); size_t str_cat(char *dst, const char *src, size_t dlen); int str_fmt(char *s, size_t len, const char *fmt, ...); int str_vfmt(char *s, size_t len, const char *fmt, va_list ap); void cset_clear(byte_t set[32]); void cset_fill(byte_t set[32]); void cset_init_accept(byte_t set[32], const char *accept); void cset_init_reject(byte_t set[32], const char *reject); void cset_add(byte_t set[32], uchar ch); void cset_rem(byte_t set[32], uchar ch); int cset_contains(byte_t set[32], uchar ch); size_t str_spn(const char *src, byte_t set[32]); size_t str_copy_spn(char *dst, const char *src, size_t dlen, byte_t set[32]); size_t str_cat_spn(char *dst, const char *src, size_t dlen, byte_t set[32]); struct path_walker { const char *path; const char *next; byte_t acc[32]; byte_t rej[32]; char dsep; }; void pwalk_init(struct path_walker *pw, const char *path, const char *psep, char dsep); void pwalk_reset(struct path_walker *pw); char *pwalk_next(struct path_walker *pw, const char *sfx, char *out, size_t osize); /* * Useful parsing function since v6 addresses have zero-compression, etc. * The return value goes in 'addr'. It must refer to 16 bytes. * Returns the index of the first character after the address in the string * or -1 if there is an error. The address is stored in network byte order * (MSB first). */ int str_parse_ip6a(void *addr, const char *src); /* UTF conversion routines */ extern const signed char utf8_lentab[256]; #define utf8_nbytes(c) (utf8_lentab[(uchar)(c)]) int utf8_find_nbytes(const uchar firstc); char * utf8_findc(const char *s, const char *c); size_t utf8_span(const char *s, const char *accept); size_t utf8_cspan(const char *s, const char *reject); int utf8_validate_char(const char *str, size_t max); int utf8_validate_str(const char *str, char const **errp); int utf8_validate(const char *str, size_t slen, char const **errp, int term); size_t utf8_nchars(const char *str, size_t slen, int *maxlen); int utf8_to_utf32(ulong *dst, size_t dlen, const char *s, size_t slen); int utf8_to_utf16(ushort *dst, size_t dlen, const char *s, size_t slen); int utf32_to_utf8(char *dst, size_t dlen, const ulong *s, size_t slen); int utf16_to_utf8(char *dst, size_t dlen, const ushort *src, size_t sl); char * utf8_skip(char *start, size_t nchar); char * utf8_skip_tck(char *start, size_t nchar); #endif /* __cat_str_h */
github188/catlib
src/str.c
<gh_stars>1-10 /* * str.c -- String manipulation routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/str.h> #include <cat/emit_format.h> #include <stdarg.h> #include <limits.h> #include <string.h> #include <ctype.h> STATIC_BUG_ON(cat_str_bad_size_char, CHAR_BIT != 8); #ifndef va_copy #ifndef __va_copy #error "No va_copy() or __va_copy() macros!" #else /* __va_copy */ #define va_copy(dst, src) __va_copy(dst, src) #endif /* __va_copy */ #endif /* va_copy */ const signed char utf8_lentab[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,-1,-1, }; uchar chnval(char d) { return isdigit(d) ? (d) - '0' : (isalpha(d) ? 10 + toupper(d) - 'A' : 0); } size_t str_copy(char *dst, const char *src, size_t dlen) { const char *osrc = src; while ( dlen > 0 && ((*dst = *src) != '\0') ) { --dlen; ++src; ++dst; } if ( dlen == 0 ) { if ( src != osrc ) *(dst - 1) = '\0'; while ( *src != '\0' ) src++; } return src - osrc; } size_t str_cat(char *dst, const char *src, size_t dlen) { size_t copylen; size_t dstoff; char *odst = dst; while ( dlen > 0 && *dst != '\0' ) { --dlen; ++dst; } copylen = str_copy(dst, src, dlen); dstoff = dst - odst; abort_unless(copylen <= (size_t)~0 - dstoff); return copylen + dstoff; } int str_vfmt(char *buf, size_t len, const char *fmt, va_list ap) { struct string_emitter se; int rlen; char tbuf[1] = { '\0' }; abort_unless(fmt); if ( len <= 1 ) buf = NULL; if ( buf ) string_emitter_init(&se, buf, len); else string_emitter_init(&se, tbuf, 1); rlen = emit_vformat(&se.se_emitter, fmt, ap); string_emitter_terminate(&se); return rlen; } int str_fmt(char *buf, size_t len, const char *fmt, ...) { va_list ap; int rv; va_start(ap, fmt); rv = str_vfmt(buf, len, fmt, ap); va_end(ap); return rv; } void cset_clear(byte_t set[32]) { memset(set, 0, 32); } void cset_fill(byte_t set[32]) { memset(set, 0xFF, 32); } void cset_add(byte_t set[32], uchar ch) { set[ch >> 3] |= 1 << (ch & 0x7); } void cset_rem(byte_t set[32], uchar ch) { set[ch >> 3] &= ~(1 << (ch & 0x7)); } int cset_contains(byte_t set[32], uchar ch) { return set[ch >> 3] & (1 << (ch & 7)); } void cset_init_accept(byte_t set[32], const char *accept) { uchar ch; const uchar *s = (const uchar *)accept; cset_clear(set); while ( (ch = *s++) != '\0' ) cset_add(set, ch); } void cset_init_reject(byte_t set[32], const char *reject) { const uchar *s = (const uchar *)reject; cset_fill(set); do { cset_rem(set, *s); } while ( *s++ != '\0' ); } size_t str_spn(const char *src, byte_t set[32]) { const char *osrc = src; while ( cset_contains(set, *src) ) ++src; return src - osrc; } size_t str_copy_spn(char *dst, const char *src, size_t dlen, byte_t set[32]) { const char *osrc = src; uchar ch; while ( dlen > 0 ) { --dlen; ch = *src; if ( cset_contains(set, ch) ) { *dst++ = ch; } else { *dst = '\0'; return src - osrc; } ++src; } if ( src != osrc ) *(dst - 1) = '\0'; while ( cset_contains(set, *src) ) src++; return src - osrc; } size_t str_cat_spn(char *dst, const char *src, size_t dlen, byte_t set[32]) { size_t copylen; size_t dstoff; char *odst = dst; while ( dlen > 0 && *dst != '\0' ) { --dlen; ++dst; } copylen = str_copy_spn(dst, src, dlen, set); dstoff = dst - odst; abort_unless(copylen <= (size_t)~0 - dstoff); return copylen + dstoff; } void pwalk_init(struct path_walker *pw, const char *path, const char *psep, char dsep) { pw->path = path; pw->next = path; cset_init_accept(pw->acc, psep); cset_init_reject(pw->rej, psep); pw->dsep = dsep; } void pwalk_reset(struct path_walker *pw) { pw->next = pw->path; } char *pwalk_next(struct path_walker *pw, const char *sfx, char *out, size_t osize) { size_t pl; if ( pw == NULL || sfx == NULL || osize < 1 || pw->next == NULL ) return NULL; pl = str_copy_spn(out, pw->next, osize, pw->rej); if ( pl >= osize - 1 ) return NULL; out[pl] = pw->dsep; osize -= pl + 1; if ( str_copy(out + pl + 1, sfx, osize) >= osize ) return NULL; if ( pw->next[pl] == '\0' ) { pw->next = NULL; } else { pw->next += pl + 1; pw->next += str_spn(pw->next, pw->acc); if ( *pw->next == '\0' ) pw->next = NULL; } return out; } int str_parse_ip6a(void *ap, const char *src) { size_t spn; int i; int plen = 0; int slen = 0; int zcomp = 0; const char *p = src; byte_t *addr = ap; byte_t suffix[16]; byte_t ip6a_set[32]; byte_t hex_set[32]; cset_init_accept(hex_set, "abcdefABCDEF0123456789"); memcpy(ip6a_set, hex_set, sizeof(hex_set)); cset_add(ip6a_set, ':'); spn = str_spn(p, ip6a_set); if ( spn < 2 || spn > 39 || src[spn] != '\0' ) return -1; if ( src[0] == ':' && src[1] != ':' ) return -1; memset(ap, 0, 16); while ( (spn = str_spn(p, hex_set)) > 0) { if ( plen >= 16 ) return -1; switch (spn) { case 1: addr[plen+1] = chnval(p[0]); break; case 2: addr[plen+1] = chnval(p[0]) << 4 | chnval(p[1]); break; case 3: addr[plen] = chnval(p[0]); addr[plen+1] = chnval(p[1]) << 4 | chnval(p[2]); break; case 4: addr[plen] = chnval(p[0]) << 4 | chnval(p[1]); addr[plen+1] = chnval(p[2]) << 4 | chnval(p[3]); break; default: return -1; } plen += 2; if ( p[spn] == ':' ) { p += spn + 1; } else { abort_unless(p[spn] == '\0'); p += spn; break; } } if ( *p != '\0' ) { if ( plen == 16 ) return -1; p += (p == src) + 1; zcomp = 2; } while ( (spn = str_spn(p, hex_set)) > 0 ) { if ( plen + zcomp + slen >= 16 ) return -1; switch (spn) { case 1: suffix[slen] = 0; suffix[slen+1] = chnval(p[0]); break; case 2: suffix[slen] = 0; suffix[slen+1] = chnval(p[0]) << 4 | chnval(p[1]); break; case 3: suffix[slen] = chnval(p[0]); suffix[slen+1] = chnval(p[1]) << 4 | chnval(p[2]); break; case 4: suffix[slen] = chnval(p[0]) << 4 | chnval(p[1]); suffix[slen+1] = chnval(p[2]) << 4 | chnval(p[3]); break; default: return -1; } slen += 2; if ( p[spn] == ':' ) { p += spn + 1; } else { abort_unless(p[spn] == '\0'); p += spn; break; } } abort_unless(slen >= 0 && slen <= 14); for ( i = 0 ; i < slen ; ++i ) addr[16 - slen + i] = suffix[i]; i = (int)(p - src); abort_unless(2 <= i && i <= 39); return i; } /* UTF8 Functions */ int utf8_find_nbytes(const uchar c) { int hibit = 0x80; int firstz = 0; while ( c & hibit ) { ++firstz; hibit >>= 1; } if ( firstz == 0 ) return 1; else if ( firstz == 1 ) return -1; else if ( firstz >= 7 ) return -1; return firstz; } char * utf8_findc(const char *sprm, const char *cprm) { int clen, slen; int i; const uchar *s = (const uchar *)sprm; const uchar *c = (const uchar *)cprm; /* could do boyer-moore, simple is faster for 1 char */ clen = utf8_validate_char((const char *)c, 0); abort_unless(clen > 0); while ( *s != '\0' ) { /* common case */ if ( (clen == 1) && ((*s & 0x80) == 0) ) { if ( *s == *c ) return (char *)s; ++s; continue; } /* multi-length utf8-char */ slen = utf8_nbytes(*s); abort_unless(slen > 0); if ( slen == clen ) { for ( i = 0; i < slen ; ++i ) if ( s[i] != c[i] ) break; if ( i == slen ) return (char *)s; } s += slen; } return NULL; } static int utf8_char_is_in(const uchar *c, int cnb, const uchar *set) { int snb, i; while ( *set != '\0' ) { snb = utf8_nbytes(*set); abort_unless(snb > 0); if ( cnb == snb ) { for ( i = 0; i < snb ; ++i ) if ( set[i] != c[i] ) break; if ( i == snb ) return 1; } set += snb; } return 0; } size_t utf8_span(const char *s, const char *accept) { size_t off = 0; int len; while ( *s != '\0' ) { len = utf8_nbytes(*s); abort_unless(len > 0); if ( !utf8_char_is_in((uchar *)s, len, (uchar *)accept) ) return off; s += len; off += len; } return off; } size_t utf8_cspan(const char *s, const char *reject) { size_t off = 0; int len; while ( *s != '\0' ) { len = utf8_nbytes(*s); abort_unless(len > 0); if ( utf8_char_is_in((uchar *)s, len, (uchar *)reject) ) return off; s += len; off += len; } return off; } int utf8_validate_char(const char *strprm, size_t max) { int i, nb; const uchar *str = (const uchar *)strprm; const uchar *ostr; if ( ((nb = utf8_nbytes(*str)) < 0) || ((max > 0) && (nb > max)) ) return -1; ostr = str++; for ( i = 1 ; i < nb ; ++i, ++str ) if ( (*str & 0xC0) != 0x80 ) return -1; switch ( nb ) { case 2: if ( (ostr[0] & 0xFE) == 0xC0 ) return -1; break; case 3: if ( (ostr[0] == 0xE0) && ((ostr[1] & 0xE0) == 0x80) ) return -1; break; case 4: if ( (ostr[0] == 0xF0) && ((ostr[1] & 0xF0) == 0x80) ) return -1; break; case 5: if ( (ostr[0] == 0xF8) && ((ostr[1] & 0xF8) == 0x80) ) return -1; break; case 6: if ( (ostr[0] == 0xFC) && ((ostr[1] & 0xFC) == 0x80) ) return -1; break; } abort_unless(nb > 0); return nb; } int utf8_validate(const char *str, size_t slen, const char **epos, int term) { int len; while ( slen > 0 ) { if ( term && *str == '\0' ) return 0; if ( (len = utf8_validate_char(str, slen)) < 0 ) { if ( epos ) *epos = str; return -1; } str += len; slen -= len; } if ( epos ) *epos = NULL; return 0; } size_t utf8_nchars(const char *str, size_t slen, int *maxlen) { size_t nc = 0; int len; int max = 0; while ( slen > 0 ) { nc++; len = utf8_nbytes(*str); abort_unless(len > 0); if ( len > max ) max = len; slen -= len; str += len; } if ( maxlen != NULL ) *maxlen = max; return nc; } static struct utf8_chardesc { int hishift; ulong mask; } utf8_cdtab[7] = { { 0, 0 }, /* dummy */ { 0, 0x7F }, { 6, 0x1F }, { 12, 0x0F }, { 18, 0x07 }, { 24, 0x03 }, { 30, 0x01 }, }; int utf8_to_utf32(ulong *dst, size_t dlen, const char *sprm, size_t slen) { int clen, i; ulong v; struct utf8_chardesc *cd; size_t nconv = 0; const uchar *src = (const uchar *)sprm; while ( slen > 0 ) { if ( (clen = utf8_validate_char((const char *)src, slen)) < 0 ) return -1; if ( nconv < dlen ) { cd = &utf8_cdtab[clen]; v = ((ulong)src[0] & cd->mask) << cd->hishift; for ( i = 1 ; i < clen ; ++i ) v |= ((ulong)src[i] & 0x3F) << (6 * (clen - 1 - i)); *dst++ = v; } ++nconv; src += clen; slen -= clen; } return nconv; } int utf8_to_utf16(ushort *dst, size_t dlen, const char *sprm, size_t slen) { int clen, i; ulong v; struct utf8_chardesc *cd; size_t nconv = 0; const uchar *src = (const uchar *)sprm; while ( slen > 0 ) { clen = utf8_validate_char((const char *)src, slen); if ( clen < 0 || clen > 3 ) return -1; if ( nconv < dlen ) { cd = &utf8_cdtab[clen]; v = ((ushort)src[0] & cd->mask) << cd->hishift; for ( i = 1 ; i < clen ; ++i ) v |= ((ushort)src[i] & 0x3F) << (6 * (clen - 1 - i)); /* Check whether we need to encode this as a */ /* surrogate pair */ if ( v > 0xFFFF ) { if ( v > 0x10FFFF ) return -1; ++nconv; if ( nconv < dlen ) { v -= 0x10000; *dst++ = 0xD800 | (v & 0xFFC00) >> 10; *dst++ = 0xDC00 | (v & 0x3FF); } } else { *dst++ = v; } } ++nconv; src += clen; slen -= clen; } return nconv; } static int utf8_enc_len(ulong val) { if ( val & 0x80000000 ) return -1; if ( (val & 0xFFFFFF80) == 0 ) /* 7 bit ascii */ return 1; if ( (val & 0xFFFFF800) == 0 ) /* 11 bits */ return 2; if ( (val & 0xFFFF0000) == 0 ) /* 16 bits */ return 3; if ( (val & 0xFFE00000) == 0 ) /* 21 bits */ return 4; if ( (val & 0xFC000000) == 0 ) /* 26 bits */ return 5; return 6; /* 31 bits */ } static void utf8_encode(uchar *dp, ulong v, int enclen) { switch(enclen) { case 1: /* 7 bit ascii */ *dp = v; break; case 2: /* lower 11 bits */ *dp++ = 0xC0 | ((v & 0x000007C0) >> 6); *dp++ = 0x80 | (v & 0x0000003F); break; case 3: /* lower 16 bits */ *dp++ = 0xE0 | ((v & 0x0000F000) >> 12); *dp++ = 0x80 | ((v & 0x00000FC0) >> 6); *dp++ = 0x80 | (v & 0x0000003F); break; case 4: /* lower 21 bits */ *dp++ = 0xF0 | ((v & 0x001C0000) >> 18); *dp++ = 0x80 | ((v & 0x0003F000) >> 12); *dp++ = 0x80 | ((v & 0x00000FC0) >> 6); *dp++ = 0x80 | (v & 0x0000003F); break; case 5: /* lower 26 bits */ *dp++ = 0xF8 | ((v & 0x03000000) >> 24); *dp++ = 0x80 | ((v & 0x00FC0000) >> 18); *dp++ = 0x80 | ((v & 0x0003F000) >> 12); *dp++ = 0x80 | ((v & 0x00000FC0) >> 6); *dp++ = 0x80 | (v & 0x0000003F); break; case 6: /* lower 31 bits */ *dp++ = 0xFC | ((v & 0x40000000) >> 30); *dp++ = 0x80 | ((v & 0x3F000000) >> 24); *dp++ = 0x80 | ((v & 0x00FC0000) >> 18); *dp++ = 0x80 | ((v & 0x0003F000) >> 12); *dp++ = 0x80 | ((v & 0x00000FC0) >> 6); *dp++ = 0x80 | (v & 0x0000003F); break; default: abort_unless(0); } } int utf32_to_utf8(char *dprm, size_t dlen, const ulong *src, size_t slen) { size_t tlen = 0; int enclen; ulong v; uchar *dst = (uchar *)dprm; abort_unless(src); if ( slen >= INT_MAX ) return -1; while ( slen > 0 ) { if ( (enclen = utf8_enc_len(v = *src)) < 0 ) return -1; abort_unless(enclen >= 1 && enclen <= 6); if ( dst != NULL && dlen >= enclen ) { utf8_encode(dst, v, enclen); dst += enclen; dlen -= enclen; } if ( INT_MAX - tlen < enclen ) return -1; tlen += enclen; src++; slen--; } return tlen; } int utf16_to_utf8(char *dprm, size_t dlen, const ushort *src, size_t slen) { size_t tlen = 0; int enclen; ulong v; uchar *dst = (uchar *)dprm; abort_unless(src); if ( slen >= INT_MAX ) return -1; while ( slen > 0 ) { /* Check for surrogate pairs */ v = *src; if ( (v >= 0xDC00) && (v <= 0xDFFF) ) return -1; if ( (v & 0xFC00) == 0xD800 ) { if ( (slen < 2) || ((src[1] & 0xFC00) != 0xDC00) ) return -1; v = ((src[0] & 0x3FF) << 10) | (src[1] & 0x3FF); src += 2; slen -= 2;; } else { ++src; --slen; } if ( (enclen = utf8_enc_len(v)) < 0 ) return -1; abort_unless(enclen >= 1 && enclen <= 3); if ( dst != NULL && dlen >= enclen ) { utf8_encode(dst, v, enclen); dst += enclen; dlen -= enclen; } if ( INT_MAX - tlen < enclen ) return -1; tlen += enclen; } return tlen; } static char * utf8_skip_help(char *str, size_t nchar, int tc) { int clen; abort_unless(str); while ( nchar > 0 ) { clen = utf8_nbytes(*str); if ( (clen < 0) || (tc && (clen == 1) && (*str == '\0')) ) return NULL; str += clen; --nchar; } return str; } char * utf8_skip(char *str, size_t nchar) { return utf8_skip_help(str, nchar, 0); } char * utf8_skip_tck(char *str, size_t nchar) { return utf8_skip_help(str, nchar, 1); }
github188/catlib
test/testbitops.c
<filename>test/testbitops.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/bitops.h> #include <stdlib.h> #include <time.h> #include <stdio.h> void print_bits32(uint32_t x) { int i; for ( i = 31; i >= 0; i-- ) { printf("%u", (uint)((x >> i) & 1)); if ( i == 0 ) printf("\n"); else if ( i % 4 == 0 ) printf(" "); } } #if CAT_64BIT void print_bits64(uint64_t x) { int i; for ( i = 63; i >= 0; i-- ) { printf("%u", (uint)((x >> i) & 1)); if ( i == 0 ) printf("\n"); else if ( i % 4 == 0 ) printf(" "); } } #endif #define PROUND(x, p2, func) \ printf("0x%08lx rounded with " #func " to 2**%u is %08lx\n", \ (unsigned long)x, p2, \ (unsigned long)func(x, p2)) #define PROUND64(x, p2, func) \ printf("0x%016llx rounded with " #func " to 2**%u is %016llx\n", \ (unsigned long long)x, p2, \ (unsigned long long)func(x, p2)) void test_round() { printf("Testing round to powers of 2\n"); PROUND(0xdeadbeef, 0, rup2_32); PROUND(0xdeadbeef, 0, rdp2_32); PROUND(0xdeadbeef, 4, rup2_32); PROUND(0xdeadbeef, 4, rdp2_32); PROUND(0xdeadbeef, 16, rup2_32); PROUND(0xdeadbeef, 16, rdp2_32); PROUND(0xdeadbeef, 32, rup2_32); PROUND(0xdeadbeef, 32, rdp2_32); PROUND(0xdeadbeef, 31, rup2_32); PROUND(0xdeadbeef, 31, rdp2_32); printf("\n"); #if CAT_64BIT PROUND64(0xdeadbeeffeedf00dllu, 0, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 0, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 4, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 4, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 16, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 16, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 32, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 32, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 31, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 31, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 64, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 64, rdp2_64); PROUND64(0xdeadbeeffeedf00dllu, 63, rup2_64); PROUND64(0xdeadbeeffeedf00dllu, 63, rdp2_64); printf("\n"); printf("\n"); #endif } void test_compress() { uint32_t word32 = (uint32_t)rand(); uint32_t cl32, cr32; uint32_t sag32; #if CAT_64BIT uint64_t word64 = (uint64_t)rand() | ((uint64_t)rand() << 32); uint64_t cl64, cr64; #endif /* CAT_64BIT */ printf("Testing compress\n"); cl32 = compress_l32(word32, word32); cr32 = compress_r32(word32, word32); printf("Word 32 (%d bits):\n", pop_32(word32)); print_bits32(word32); printf("compress left:\n"); print_bits32(cl32); printf("compress right:\n"); print_bits32(cr32); printf("\n"); cl32 = compress_l32(0x0000FF00, 0x00FFFF00); printf("compress left of 0xff00ff00/00ffff00: "); print_bits32(cl32); printf("\n"); sag32 = SAG32(0xff00ff00, 0x00ffff00); printf("SAG32 of 0xff00ff00 mask = 0x00ffff00:\n"); print_bits32(sag32); printf("\n"); #if CAT_64BIT cl64 = compress_l64(word64, word64); cr64 = compress_r64(word64, word64); printf("Word 64 (%d bits):\n", pop_64(word64)); print_bits64(word64); printf("compress left:\n"); print_bits64(cl64); printf("compress right:\n"); print_bits64(cr64); printf("\n"); #endif /* CAT_64BIT */ } void print_perm32(uint32_t x, uint8_t p[32]) { int i; for ( i = 31; i >= 0; i-- ) { printf("%u", (uint)((x >> p[i]) & 1)); if ( i == 0 ) printf("\n"); else if ( i % 4 == 0 ) printf(" "); } } #if CAT_64BIT void print_perm64(uint64_t x, uint8_t p[64]) { int i; for ( i = 63; i >= 0; i-- ) { printf("%u", (uint)((x >> p[i]) & 1)); if ( i == 0 ) printf("\n"); else if ( i % 4 == 0 ) printf(" "); } } #endif /* CAT_64BIT */ void random_permutation(uint8_t arr[], size_t len) { int i; uint8_t t, p; for ( i = 0; i < len; i++ ) arr[i] = i; /* for each position randomly swap it with another position */ for ( i = len - 1; i > 0; --i ) { p = (rand() & 0x7fff) % len; t = arr[p]; arr[p] = arr[i]; arr[i] = t; } printf("perm%d: ", (int)len); for ( i = 0; i < len; i++ ) { printf("%3u", arr[i]); if (i != len -1) { putchar(','); if (i % 16 == 15) printf("\n\t"); } } printf("\n\n"); } void reverse(uint8_t src[], uint8_t dst[], size_t len) { int i; for ( i = 0; i < len; ++i ) dst[src[i]] = i; printf("perm%dr:", (int)len); for ( i = 0; i < len; i++ ) { printf("%3u", dst[i]); if (i != len -1) { putchar(','); if (i % 16 == 15) printf("\n\t"); } } printf("\n\n"); } int main(int argc, char *argv[]) { int i; uint32_t word32, p32_sag, p32_bg; uint8_t perm32[32]; /* comes from */ uint8_t perm32_SAG[32]; /* goes-to rather than comes-from */ uint32_t sagpv32[5]; #if CAT_64BIT uint64_t word64, p64_sag, p64_bg; uint8_t perm64[64]; /* comes from */ uint8_t perm64_SAG[64]; /* goes-to rather than comes-from */ uint64_t sagpv64[6]; #endif /* CAT_64BIT */ srand(time(NULL)); test_round(); test_compress(); word32 = (uint32_t)rand(); random_permutation(perm32, 32); reverse(perm32, perm32_SAG, 32); if (arr_to_SAG_permvec32(perm32_SAG, sagpv32) < 0) { printf("Error in SAG32 permutation vector\n"); return -1; } p32_sag = permute32_SAG(word32, sagpv32); p32_bg = bitgather32(word32, perm32); #if CAT_64BIT word64 = (uint64_t)rand() | ((uint64_t)rand() << 32); random_permutation(perm64, 64); reverse(perm64, perm64_SAG, 64); if (arr_to_SAG_permvec64(perm64_SAG, sagpv64) < 0) { printf("Error in SAG64 permutation vector\n"); return -1; } p64_sag = permute64_SAG(word64, sagpv64); p64_bg = bitgather64(word64, perm64); #endif /* CAT_64BIT */ printf("Original 32 bits:\n"); print_bits32(word32); printf("Local Perm 32 bits:\n"); print_perm32(word32, perm32); printf("SAG32 result:\n"); print_bits32(p32_sag); printf("BG-32 result:\n"); print_bits32(p32_bg); if ( p32_sag == p32_bg ) { printf("32-bit SAG and 32-bit bit gather perms agree\n"); } else { printf("32-bit SAG and 32-bit bit gather perms disagree\n"); } for ( i = 0; i < 32; i++ ) { uint8_t b1 = (word32 >> perm32[i]) & 1; uint8_t b2 = (p32_sag >> i) & 1; if ( b1 != b2 ) { printf("32-bit SAG value is wrong "); printf("at position %d: %d vs %d. Perm[%d] = %d\n", i, b1, b2, i, perm32[i]); break; } } for ( i = 0; i < 32; i++ ) { uint8_t b1 = (word32 >> perm32[i]) & 1; uint8_t b2 = (p32_bg >> i) & 1; if ( b1 != b2 ) { printf("32-bit bit gather value is wrong "); printf("at position %d: %d vs %d. Perm[%d] = %d\n", i, b1, b2, i, perm32[i]); break; } } printf("\n"); #if CAT_64BIT printf("Original 64 bits:\n"); print_bits64(word64); printf("Local Perm 64 bits:\n"); print_perm64(word64, perm64); printf("SAG64 result:\n"); print_bits64(p64_sag); printf("BG-64 result:\n"); print_bits64(p64_bg); if ( p64_sag == p64_bg ) { printf("64-bit SAG and 64-bit bit gather perms agree\n"); } else { printf("64-bit SAG and 64-bit bit gather perms disagree\n"); } for ( i = 0; i < 64; i++ ) { uint8_t b1 = (word64 >> perm64[i]) & 1; uint8_t b2 = (p64_sag >> i) & 1; if ( b1 != b2 ) { printf("64-bit SAG value is wrong "); printf("at position %d: %d vs %d. Perm[%d] = %d\n", i, b1, b2, i, perm64[i]); break; } } for ( i = 0; i < 64; i++ ) { uint8_t b1 = (word64 >> perm64[i]) & 1; uint8_t b2 = (p64_bg >> i) & 1; if ( b1 != b2 ) { printf("64-bit bit gather value is wrong "); printf("at position %d: %d vs %d. Perm[%d] = %d\n", i, b1, b2, i, perm64[i]); break; } } printf("\n"); #endif /* CAT_64BIT */ return 0; }
github188/catlib
include/cat/stdclio.h
/* * stdclio.h -- stdio interface matched to emit API. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_stdclio_h #define __cat_stdclio_h #include <cat/cat.h> #include <cat/emit.h> #include <cat/inport.h> #include <stdio.h> struct file_emitter { struct emitter fe_emitter; FILE * fe_file; }; void file_emitter_init(struct file_emitter *fe, FILE *file); int file_emitter_open(struct file_emitter *fe, const char *fname, int append); int file_emitter_close(struct file_emitter *fe); /* normally we wouldn't expose this. I do it here so we can wrap it in err.c. */ int file_emit_func(struct emitter *em, const void *buf, size_t len); #if CAT_HAS_POSIX /* File Descriptor Emitter - emit to a Posix file descriptor */ struct fd_emitter { struct emitter fde_emitter; int fde_fd; }; void fd_emitter_init(struct fd_emitter *fde, int fd); #endif /* CAT_HAS_POSIX */ struct dynstr_emitter { struct emitter ds_emitter; struct raw ds_str; size_t ds_fill; size_t ds_max; }; /* initialize an emitter that resizes its string buffer. */ void dynstr_emitter_init(struct dynstr_emitter *dse, size_t max); /* reset the string output, but don't release memory */ void dynstr_emitter_reset(struct dynstr_emitter *dse); /* release memory and clear so subsequent calls with will not send to string */ void dynstr_emitter_clear(struct dynstr_emitter *dse); struct file_inport { struct inport in; FILE * file; }; void finp_init(struct file_inport *fin, FILE *fp); #if CAT_HAS_POSIX struct fd_inport { struct inport in; int fd; }; void fdinp_init(struct fd_inport *fdin, int fd); #endif /* CAT_HAS_POSIX */ #endif /* __cat_stdclio_h */
github188/catlib
test/testprintf.c
<reponame>github188/catlib<filename>test/testprintf.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/emit.h> #include <cat/emit_format.h> #include <cat/str.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <sys/time.h> int ntests = 0, npassed = 0; void test_printf(const char *fmt, ...) { va_list ap, ap2; char buf1[256]; char buf2[256]; int rv1, rv2, passed; printf("format = |%s|\n", fmt); va_start(ap, fmt); rv1 = vsnprintf(buf1, sizeof(buf1), fmt, ap); va_end(ap); printf("native: rv = %d, val = |%s|\n", rv1, buf1); fflush(stdout); va_start(ap2, fmt); rv2 = str_vfmt(buf2, sizeof(buf2), fmt, ap2); va_end(ap2); printf("catlib: rv = %d, val = |%s|\n", rv2, buf2); fflush(stdout); ++ntests; passed = ((strcmp(buf1, buf2) == 0) && (rv1 == rv2)); if ( passed ) ++npassed; printf("result -> %s\n\n", passed ? "match!" : "no match" ); } void test_extension(const char *fmt, ...) { va_list ap; char buf[256]; int rv; printf("format = |%s|\n", fmt); va_start(ap, fmt); rv = str_vfmt(buf, sizeof(buf), fmt, ap); va_end(ap); printf("catlib: rv = %d, val = |%s|\n\n", rv, buf); fflush(stdout); } #define NREPS 100000 void speed_test(const char *fmt, ...) { va_list ap, ap2; char buf1[256]; char buf2[256]; int rv1, rv2, passed, i; struct timeval start, end; double delta; gettimeofday(&start, NULL); for (i = 0; i < NREPS; i++) { va_start(ap, fmt); rv1 = vsnprintf(buf1, sizeof(buf1), fmt, ap); va_end(ap); } gettimeofday(&end, NULL); delta = (end.tv_sec - start.tv_sec) * 1000000.0 + end.tv_usec - start.tv_usec; delta *= 1000.0; printf("vsnprintf(\"%s\",...); -> %f nanoseconds\n", fmt, delta / (double)NREPS); gettimeofday(&start, NULL); for (i = 0; i < NREPS; i++) { va_start(ap2, fmt); rv2 = str_vfmt(buf2, sizeof(buf2), fmt, ap2); va_end(ap2); } gettimeofday(&end, NULL); delta = (end.tv_sec - start.tv_sec) * 1000000.0 + end.tv_usec - start.tv_usec; delta *= 1000.0; printf("str_vfmt(\"%s\",...); -> %f nanoseconds\n", fmt, delta / (double)NREPS); } #define CKFMT(l, s, p, np) { \ if ( l emit_format_ckprm(s, p, np) ) \ fprintf(stderr, "Error validating %s\n", s); \ else \ printf("%s correctly validates (%strue)\n",s,#l);\ } void check_formats() { uchar p[4]; printf("Starting format check tests\n"); p[0] = FMT_INTVAL; CKFMT(, "%d", p, 1); CKFMT(, "%17d", p, 1); CKFMT(, "%u", p, 1); CKFMT(, "%-17b", p, 1); CKFMT(!, "%e", p, 1); CKFMT(!, "%17f", p, 1); CKFMT(!, "%g", p, 1); CKFMT(!, "%-17G", p, 1); CKFMT(!, "%-17Lg", p, 1); p[0] = FMT_DBLVAL; CKFMT(!, "%d", p, 1); CKFMT(!, "%17d", p, 1); CKFMT(!, "%u", p, 1); CKFMT(!, "%-17b", p, 1); CKFMT(, "%e", p, 1); CKFMT(, "%17f", p, 1); CKFMT(, "%g", p, 1); CKFMT(, "%-17G", p, 1); p[0] = FMT_INTVAL | FMT_LONGSIZE; CKFMT(!, "%d", p, 1); CKFMT(!, "%17d", p, 1); CKFMT(!, "%u", p, 1); CKFMT(!, "%-17b", p, 1); CKFMT(!, "%Ld", p, 1); CKFMT(, "%ld", p, 1); CKFMT(, "%17ld", p, 1); CKFMT(, "%lu", p, 1); CKFMT(, "%-17lb", p, 1); CKFMT(, "%-17lx", p, 1); p[0] = FMT_STRVAL; CKFMT(!, "%d", p, 1); CKFMT(!, "%17d", p, 1); CKFMT(!, "%u", p, 1); CKFMT(!, "%e", p, 1); CKFMT(, "%300s", p, 1); p[1] = FMT_INTVAL; CKFMT(!, "%300s", p, 2); CKFMT(!, "%300s", p, 0); CKFMT(, "%s hello %20d", p, 2); } int main(int argc, char *argv[]) { test_printf("hi"); test_printf("%d", 5); test_printf("%3d", 5); test_printf("%-3d", 5); test_printf("abc - %s - def", "goodbye"); test_printf("pointer %p", (void *)&argc); test_printf("null pointer %p", NULL); test_printf("%f", 1.0); test_printf("%+f", 1.01); test_printf("%f", .01); test_printf("% f", .01); test_printf("%0f", .01); test_printf("%7.3f", .01); test_printf("%7.3f", .0123); test_printf("%07.3f", .0123); test_printf("%7.3e", .0123); test_printf("%.3e", 123000.25); test_printf("%.10E", 123000.25); test_printf("%f", 1.0 / 0.0); test_printf("%f", -1.0 / 0.0); test_printf("hell%c w%crld", 'o', 'o'); test_printf("%o", 0765); test_printf("%X", 0xcafebabe); test_printf("%x", 0xdeadbeef); test_printf("%u", 82); test_printf("%u", -10); test_printf("%7.3g", .01); test_printf("%7.3G", .0123); test_printf("%.3g", 123000.25); test_printf("%.0g", 123000.25); printf("Extensions\n"); test_extension("%032b", 0xabcdef38); test_extension("%032b", 0x58); test_extension("%b", 0x58); printf("%d / %d tests passed\n", npassed, ntests); printf("\nSpeed Tests\n"); speed_test("Hello World"); speed_test("hell%c w%crld", 'o', 'o'); speed_test("abc - %s - def", "goodbye"); speed_test("%7.3e", .0123); speed_test("%17d", 12345678); check_formats(); return npassed == ntests ? 0 : ntests; }
github188/catlib
include/cat/emit_format.h
<reponame>github188/catlib /* * emit_format.h -- Formatted output over the emit interface. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_emit_format_h #define __cat_emit_format_h #include <cat/cat.h> #include <cat/emit.h> #include <stdarg.h> int emit_format(struct emitter *em, const char *fmt, ...); int emit_vformat(struct emitter *em, const char *fmt, va_list ap); enum { FMT_INTVAL = 0x0, FMT_DBLVAL = 0x1, FMT_STRVAL = 0x2, FMT_PTRVAL = 0x3, FMT_REGSIZE = 0x00, FMT_HALFSIZE = 0x10, FMT_BYTESIZE = 0x20, FMT_LONGSIZE = 0x30, FMT_LONGLONGSIZE = 0x40 }; #define FMT_BASETYPE(type) ((type) & 0x0F) #define FMT_SIZETYPE(type) ((type) & 0xF0) int emit_format_getprm(const char *fmt, uchar ptypes[], int maxpt); int emit_format_ckprm(const char *fmt, uchar ptypes[], int npt); #endif /* __cat_emit_format_h */
github188/catlib
include/cat/cds.h
/* * cat/cds.h -- Container data structure macros. * Macros for creating simple container nodes for different data types. * * by <NAME> * * Copyright 2009-2012 -- See accompanying license * */ #ifndef __cat_cds_h #define __cat_cds_h #include <cat/cat.h> #include <stdlib.h> #define CDS_NEWSTRUCT(_ds, _dt, _name) \ typedef struct { \ _ds node; \ _dt data; \ } _name #define CDS_NEW0(_pvar) \ do { \ (_pvar) = calloc(1, sizeof(*_pvar)); \ } while (0) #define CDS_NEW(_pvar, _val) \ do { \ (_pvar) = calloc(1, sizeof(*_pvar)); \ (_pvar)->data = (_val); \ } while (0) #define CDS_FREE(_pvar) \ do { \ free(_pvar); \ } while (0) #define CDS_DATA(_np, _name) (((_name *)(_np))->data) #define CDS_DPTR(_np, _name) (&((_name *)(_np))->data) #define CDS_NODE(_np, _name) (((_name *)(_np))->node) #define CDS_NPTR(_np, _name) (&((_name *)(_np))->node) #endif /* __cat_cds_h */
github188/catlib
attic/str.c
<gh_stars>1-10 /* * str.c -- String manipulation functions * * by <NAME> * * Copyright 2003, See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> #include <cat/grow.h> #include <cat/str.h> #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <string.h> #else #include <cat/catstdlib.h> #endif struct raw *str2raw(struct raw *r, char *s) { r->data = s; r->len = strlen(s)+1; return r; } void str_clear(struct cstring *s) { Assert(s && s->buf.data && s->buf.len); s->slen = 0; } void str_init(struct cstring *s, char *buf, long blen, struct memctl *m, int bufisstring) { long slen; Assert(s); Assert(buf); Assert(blen > 0); s->buf.data = buf; s->buf.len = blen; s->slen = 0; s->memctl = m; if ( bufisstring ) { slen = strlen(buf) + 1; Assert(slen <= blen); s->slen = slen; } } struct cstring *str_new(const char *src, long len, struct memctl *m) { struct cstring *s; long alen; Assert(src || len >= 0); Assert(m); if ( len < 0 ) len = strlen(src) + 1; alen = len; if ( len == 0 ) alen = 1; s = m->mc_alloc(m, alen + sizeof(struct cstring)); if ( !s ) return NULL; s->buf.data = (char *)(s + 1); s->buf.len = alen; s->memctl = m; if ( src ) { memcpy(s->buf.data, src, len); s->slen = len; } else { s->buf.data[0] = '\0'; s->slen = 0; } return s; } void str_free(struct cstring *s) { Assert(s && s->buf.data && s->buf.len && s->memctl && s->memctl->mc_free && s->slen >= 0 && s->slen <= s->buf.len); s->memctl->mc_free(s->memctl, s); } void str_set(struct cstring *s, const void *d, long l) { Assert(s && s->buf.data && s->buf.len && s->slen >= 0 && s->slen <= s->buf.len); Assert(l >= 0 && l <= s->buf.len); memcpy(s->buf.data, d, l); s->slen = l; } void str_scopy(struct cstring *s, const char *cp) { long i; char *dp; Assert(s && s->buf.data && s->buf.len && s->slen >= 0 && s->slen <= s->buf.len); dp = s->buf.data; for ( i = 0 ; i < s->buf.len && *cp ; ++i ) *dp++ = *cp++; if ( i >= s->buf.len ) { dp -= 1; i -= 1; } *dp = '\0'; s->slen = i; } struct cstring *str_copy(struct cstring *s) { struct cstring *news; struct memctl *m; long alen; Assert(s && s->buf.data && s->buf.len && s->memctl && s->memctl->mc_alloc && s->slen >= 0 && s->slen <= s->buf.len); m = s->memctl; alen = s->slen; if ( !alen ) alen = 1; news = m->mc_alloc(m, alen + sizeof(struct cstring)); if ( !news ) return NULL; news->buf.data = (char *)(news + 1); news->buf.len = alen; news->slen = s->slen; news->memctl = m; memcpy(news->buf.data, s->buf.data, s->slen); return news; } int str_grow(struct cstring **sp, long size) { struct cstring *s; struct memctl *m; unsigned long curlen; Assert(sp); s = *sp; Assert(s && s->buf.data && s->buf.len && s->memctl && s->slen >= 0 && s->slen <= s->buf.len); m = s->memctl; if ( size <= s->buf.len ) return 0; curlen = s->buf.len + sizeof(struct cstring); if ( mc_grow(m, (char **)&s, &curlen, size+sizeof(struct cstring)) < 0 ) return -1; s->buf.data = (char *)(s + 1); s->buf.len = curlen - sizeof(struct cstring); *sp = s; return 0; } struct cstring *str_slice(struct cstring *s, long start, long end, int nulterm) { struct cstring *ns; long len, addnull = 0; Assert(s && s->buf.data && s->buf.len && s->slen >= 0 && s->slen <= s->buf.len); if ( start < 0 ) start = -start >= s->slen ? 0 : s->slen + start + 1; if ( end < 0 ) end = -end >= s->slen ? 0 : s->slen + end + 1; if ( end > s->slen ) end = s->slen; if ( end <= start ) { ns = str_new(NULL, 0, s->memctl); /* empty string */ if ( ! ns ) return NULL; if ( nulterm ) ns->buf.data[0] = '\0'; } else { len = end - start; if ( nulterm && s->buf.data[end - 1] != '\0' ) addnull = 1; ns = str_new(NULL, (addnull ? len + 1 : len), s->memctl); if ( ! ns ) return NULL; memcpy(ns->buf.data, s->buf.data + start, len); ns->slen = len; if ( addnull ) { ns->buf.data[len] = '\0'; ns->slen++; } } return ns; } struct cstring *str_splice(struct cstring *s, long start, long end, struct cstring *is, int nullstrings) { int addnull; long len, islen; struct cstring *ns; Assert(s && s->buf.data && s->buf.len && s->slen >= 0 && s->slen <= s->buf.len); Assert(!is || (is->buf.data && is->buf.len && is->slen >= 0 && is->slen <= is->buf.len)); if ( start < 0 ) start = -start >= s->slen ? 0 : s->slen + start + 1; else if ( start > s->slen ) start = s->slen; if ( end < 0 ) end = -end >= s->slen ? 0 : s->slen + end + 1; else if ( end > s->slen ) end = s->slen; if ( is ) islen = is->slen; else islen = 0; if ( nullstrings ) { if ( is && islen && is->buf.data[islen - 1] == '\0' ) islen -= 1; if ( end == s->slen || s->buf.data[s->slen - 1] != '\0' ) addnull = 1; } len = s->slen - (end - start) + islen + (addnull ? 1 : 0); ns = str_new(NULL, len, s->memctl); if ( ! ns ) return NULL; memcpy(ns->buf.data, s->buf.data, start); if ( is && islen ) memcpy(ns->buf.data + start, is->buf.data, islen); memcpy(ns->buf.data + start + islen, s->buf.data + end, s->slen - end); if ( addnull ) ns->buf.data[len-1] = '\0'; ns->slen = len; return ns; } int str_cmp(void *s1p, void *s2p) { long len, rv; struct cstring *s1 = s1p, *s2 = s2p; Assert(s1 && s1->buf.data && s1->buf.len && s1->slen >= 0 && s1->slen <= s1->buf.len); Assert(s2 && s2->buf.data && s2->buf.len && s2->slen >= 0 && s2->slen <= s2->buf.len); len = s1->slen < s2->slen ? s1->slen : s2->slen; rv = memcmp(s1->buf.data, s2->buf.data, len); if ( rv == 0 && s1->slen != s2->slen ) return s1->slen < s2->slen ? -1 : 1; else return rv; } long str_find(struct cstring *s, const char *pat, long len) { long i, j; if ( len == 0 ) return 0; if ( len < 0 ) len = strlen(pat); for ( i = 0 ; i <= s->slen - len ; ++i ) { for ( j = 0 ; j < len ; ++j ) if ( s->buf.data[i + j] != pat[j] ) break; if ( j == len ) return i; } return -1; } #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <stdio.h> #include <stdarg.h> #include <string.h> #include <cat/mem.h> #include <cat/err.h> char *str_fmt(const char *fmt, ...) { char *s = NULL; va_list ap; unsigned long len = 0; int r = 0; Assert(fmt); while ( 1 ) { if ( grow(&s, &len, r) < 0 ) errsys("str_fmt: "); va_start(ap, fmt); r = vsnprintf(s, len, fmt, ap); va_end(ap); if ( r < 0 ) /* SUSv4 return value */ r = 0; else if ( r >= len ) /* C99 return value */ r += 1; else /* Success */ break; } return s; } char *str_dup(const char *s) { int len; char *ns; Assert(s); if ( ! s ) return NULL; len = strlen(s) + 1; ns = xmalloc(len); memcpy(ns, s, len-1); ns[len-1] = '\0'; return ns; } char *str_tok(char *s, const char *d, unsigned *len) { char *start; Assert(s); Assert(d); Assert(len); start = s + strspn(s, d); if ( !*start ) return NULL; if ( len ) *len = strcspn(start, d); return start; } struct cstring *str_fnew(struct memctl *m, const char *fmt, ...) { struct cstring *s; char tstr[4]; va_list ap; int r = 0; va_start(ap, fmt); r = vsnprintf(tstr, sizeof(tstr), fmt, ap); va_end(ap); if ( r < 0 ) return NULL; s = str_new(NULL, r + 1, m); va_start(ap, fmt); vsnprintf(s->buf.data, s->buf.len, fmt, ap); va_end(ap); s->slen = r + 1; return s; } #endif /* CAT_USE_STDLIB */
github188/catlib
test/testtime.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/time.h> #include <stdio.h> int main(int argc, char *argv[]) { cat_time_t start, last, delta; start = last = tm_uget(); printf("sec = %ld, nsec = %ld\n", tm_sec(start), tm_nsec(start)); sleep(1); delta = tm_mark(&last, tm_uget()); printf("sec delta = %ld, nsec delta = %ld, new time = %ld.%09ld\n", delta.sec, delta.nsec, last.sec, last.nsec); printf("Step 1 took %f seconds\n", tm_2dbl(delta)); sleep(2); printf("Step 2 took %f seconds\n", tm_2dbl(tm_mark(&last, tm_uget()))); sleep(3); printf("Last was %f seconds\n", tm_2dbl(tm_mark(&last, tm_uget()))); printf("Total time was %f seconds\n", tm_2dbl(tm_sub(last, start))); last = tm_dset(tm_2dbl(last) * 3.0); printf("Multiplied by 3 : %f\n", tm_2dbl(last)); last = tm_dset(tm_2dbl(last) / 3.0); printf("Divided by 3 : %f\n", tm_2dbl(last)); last = tm_dset(tm_2dbl(last) / 0.3); printf("Divided by .3 : %f\n", tm_2dbl(last)); last = tm_dset(tm_2dbl(last) * 0.3); printf("Multiplied by .3 : %f\n", tm_2dbl(last)); last = tm_dset(tm_2dbl(last) / 7.5); printf("Divided by 7.5 : %f\n", tm_2dbl(last)); last = tm_dset(tm_2dbl(last) * 7.5); printf("Multiplied by 7.5 : %f\n", tm_2dbl(last)); return 0; }
github188/catlib
src/bitops.c
/* * bitops.c -- bit manipulation operations. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/bitops.h> char num_bits_array[256] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, }; char num_leading_zeros_array[256] = { 8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; uint32_t rup2_32(uint32_t x, uint lg2p) { uint32_t p2 = ((uint32_t)1 << lg2p) - 1; return (lg2p > 31) ? 0 : (x + p2) & ~p2; } uint32_t rdp2_32(uint32_t x, uint lg2p) { return (lg2p > 31) ? 0 : (x & ~(((uint32_t)1 << lg2p) - 1)); } #if CAT_64BIT uint64_t rup2_64(uint64_t x, uint lg2p) { uint64_t p2 = ((uint64_t)1 << lg2p) - 1; return (lg2p > 63) ? 0 : (x + p2) & ~p2; } uint64_t rdp2_64(uint64_t x, uint lg2p) { return (lg2p > 63) ? 0 : (x & ~(((uint64_t)1 << lg2p) - 1)); } #endif /* CAT_64BIT */ uint32_t compress_l32(uint32_t x, uint32_t m) { uint32_t t, mp, mv, mk; int i; x &= m; mk = ~m >> 1; for ( i = 0; i < 5; ++i ) { mp = mk ^ (mk >> 1); mp = mp ^ (mp >> 2); mp = mp ^ (mp >> 4); mp = mp ^ (mp >> 8); mp = mp ^ (mp >> 16); mv = m & mp; m = (m ^ mv) | (mv << ((uint32_t)1 << i)); t = x & mv; x = (x ^ t) | (t << ((uint32_t)1 << i)); mk = mk & ~mp; } return x; } /* HD p. 119 */ uint32_t compress_r32(uint32_t x, uint32_t m) { uint32_t t, mp, mv, mk; int i; x &= m; mk = ~m << 1; for ( i = 0; i < 5; ++i ) { mp = mk ^ (mk << 1); mp = mp ^ (mp << 2); mp = mp ^ (mp << 4); mp = mp ^ (mp << 8); mp = mp ^ (mp << 16); mv = m & mp; m = (m ^ mv) | (mv >> ((uint32_t)1 << i)); t = x & mv; x = (x ^ t) | (t >> ((uint32_t)1 << i)); mk = mk & ~mp; } return x; } #if CAT_64BIT uint64_t compress_l64(uint64_t x, uint64_t m) { uint64_t t, mp, mv, mk; int i; x &= m; mk = ~m >> 1; for ( i = 0; i < 6; ++i ) { mp = mk ^ (mk >> 1); mp = mp ^ (mp >> 2); mp = mp ^ (mp >> 4); mp = mp ^ (mp >> 8); mp = mp ^ (mp >> 16); mp = mp ^ (mp >> 32); mv = m & mp; m = (m ^ mv) | (mv << ((uint64_t)1 << i)); t = x & mv; x = (x ^ t) | (t << ((uint64_t)1 << i)); mk = mk & ~mp; } return x; } uint64_t compress_r64(uint64_t x, uint64_t m) { uint64_t t, mp, mv, mk; int i; x &= m; mk = ~m << 1; for ( i = 0; i < 6; ++i ) { mp = mk ^ (mk << 1); mp = mp ^ (mp << 2); mp = mp ^ (mp << 4); mp = mp ^ (mp << 8); mp = mp ^ (mp << 16); mp = mp ^ (mp << 32); mv = m & mp; m = (m ^ mv) | (mv >> ((uint64_t)1 << i)); t = x & mv; x = (x ^ t) | (t >> ((uint64_t)1 << i)); mk = mk & ~mp; } return x; } #endif /* CAT_64BIT */ uint32_t SAG32(uint32_t x, uint32_t mask) { return compress_l32(x, mask) | compress_r32(x, ~mask); } #if CAT_64BIT uint64_t SAG64(uint64_t x, uint64_t mask) { return compress_l64(x, mask) | compress_r64(x, ~mask); } #endif /* CAT_64BIT */ /* converts an array of bit positions to a permutation vector used to permute */ /* the bits of a 32-bit word usinv the permute32() function */ int arr_to_SAG_permvec32(uint8_t arr[32], uint32_t pv[5]) { int i, j; uint32_t t = 0, bit; /* ensures that arr[] represents a real permutation */ for ( i = 0; i < 32; ++i ) { if ( arr[i] & ~0x1f ) return -1; bit = (uint32_t)1 << arr[i]; if ( t & bit ) return -1; t |= bit; } /* Each bit k (low order bit is 0) in pv[i] contains the ith bit */ /* of k's position in the final permutation. */ for ( i = 0; i < 5; ++i ) { pv[i] = 0; for ( j = 0; j < 32; ++j ) pv[i] |= ((arr[j] >> i) & 1) << j; } /* now permute each bit of p[x] for x > 1 so it lines up with */ /* the permuted bit during shuffle x */ pv[1] = SAG32(pv[1], pv[0]); pv[2] = SAG32(SAG32(pv[2], pv[0]), pv[1]); pv[3] = SAG32(SAG32(SAG32(pv[3], pv[0]), pv[1]), pv[2]); pv[4] = SAG32(SAG32(SAG32(SAG32(pv[4], pv[0]), pv[1]), pv[2]), pv[3]); return 0; } /* Performs a stable base-2 radix sort of the bits in "bits" ascribing a */ /* value to each bit position equal its final position (as a number). */ /* The SAG32() operation does the actual moving of bits */ uint32_t permute32_SAG(uint32_t bits, uint32_t pv[5]) { bits = SAG32(bits, pv[0]); bits = SAG32(bits, pv[1]); bits = SAG32(bits, pv[2]); bits = SAG32(bits, pv[3]); bits = SAG32(bits, pv[4]); return bits; } #if CAT_64BIT /* converts an array of bit positions to a permutation vector used to permute */ /* the bits of a 64-bit word usinv the permute64() function */ int arr_to_SAG_permvec64(uint8_t arr[64], uint64_t pv[6]) { int i, j; uint64_t t = 0, bit; /* ensures that arr[] represents a real permutation */ for ( i = 0; i < 64; ++i ) { if ( arr[i] & ~0x3f ) return -1; bit = (uint64_t)1 << arr[i]; if ( t & bit ) return -1; t |= bit; } /* Each bit k (low order bit is 0) in pv[i] contains the ith bit */ /* of k's position in the final permutation. */ for ( i = 0; i < 6; ++i ) { pv[i] = 0; for ( j = 0; j < 64; ++j ) pv[i] |= (uint64_t)((arr[j] >> i) & 1) << j; } /* now permute each bit of p[x] for x > 1 so it lines up with */ /* the permuted bit during shuffle x */ pv[1] = SAG64(pv[1], pv[0]); pv[2] = SAG64(SAG64(pv[2], pv[0]), pv[1]); pv[3] = SAG64(SAG64(SAG64(pv[3], pv[0]), pv[1]), pv[2]); pv[4] = SAG64(SAG64(SAG64(SAG64(pv[4], pv[0]), pv[1]), pv[2]), pv[3]); pv[5] = SAG64(SAG64(SAG64(SAG64(SAG64(pv[5], pv[0]), pv[1]), pv[2]), pv[3]), pv[4]); return 0; } /* Performs a stable base-2 radix sort of the bits in "bits" ascribing a */ /* value to each bit position equal its final position (as a number). */ /* The SAG64() operation does the actual moving of bits. */ uint64_t permute64_SAG(uint64_t bits, uint64_t pv[6]) { bits = SAG64(bits, pv[0]); bits = SAG64(bits, pv[1]); bits = SAG64(bits, pv[2]); bits = SAG64(bits, pv[3]); bits = SAG64(bits, pv[4]); bits = SAG64(bits, pv[5]); return bits; } #endif /* CAT_64BIT */ uint32_t bitgather32(uint32_t bits, uint8_t pos[32]) { int i; uint32_t x = 0; for ( i = 0; i < 32; ++i ) x |= ((bits >> (pos[i] & 0x1f)) & 1) << i; return x; } #if CAT_64BIT uint64_t bitgather64(uint64_t bits, uint8_t pos[64]) { int i; uint64_t x = 0; for ( i = 0; i < 64; ++i ) x |= ((bits >> (pos[i] & 0x3f)) & 1) << i; return x; } #endif /* CAT_64BIT */
github188/catlib
include/cat/csv.h
/* * csv.h -- Routines for manipulating comma separated values files. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_csv_h #define __cat_csv_h #include <cat/cat.h> enum { CSV_ERR = -1, CSV_EOF = 0, CSV_OK = 1, CSV_FLD = 2, CSV_REC = 3, CSV_CNT = 4, CSV_GETC_EOF = -1, CSV_GETC_ERR = -2 }; typedef int (*getchar_f)(void *aux); struct csv_state { getchar_f csv_getc; void * csv_gcctx; int csv_done; int csv_inquote; int csv_sawquote; int csv_last; }; void csv_init(struct csv_state *csv, getchar_f gc, void *gcctx); int csv_next(struct csv_state *csv, char *buf, size_t len, size_t *rlen); int csv_clear_field(struct csv_state *csv); #endif /* __cat_csv_h */
github188/catlib
src/dbgmem.c
/* * dbgmem.c -- memory manager instrumented for debugging. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cat.h> #include <cat/dbgmem.h> #include <cat/err.h> #include <cat/hash.h> /* TODO: Make thread safe */ #include <stdlib.h> #ifndef CAT_DBGMEM_NBUCKETS #define CAT_DBGMEM_NBUCKETS 4096 #endif /* CAT_DBGMEM_NBUCKETS */ struct memmgr dbgmem = { dbg_mem_get, dbg_mem_resize, dbg_mem_free, NULL }; static ulong dbg_alloc_amt = 0; static ulong dbg_num_alloc = 0; static struct hnode *dbg_ht_buckets[CAT_DBGMEM_NBUCKETS]; static struct htab dbg_htab = { dbg_ht_buckets, CAT_DBGMEM_NBUCKETS, CAT_DBGMEM_NBUCKETS - 1, cmp_ptr, ht_phash, NULL }; struct dbg_header { struct hnode dh_hnode; size_t dh_amt; }; union dbg_header_u { cat_align_t dhu_align; struct hnode dhu_hnode; }; #define ROUNDUP(amt) ((((amt) + sizeof(union dbg_header_u)-1) / \ sizeof(union dbg_header_u)) * sizeof(union dbg_header_u)) #define TOMEM(dh) ((void *)((union dbg_header_u *)(dh) + 1)) void *dbg_mem_get(struct memmgr *mm, size_t amt) { size_t ramt; struct dbg_header *dh; void *p; abort_unless(mm == &dbgmem); ramt = ROUNDUP(amt); abort_unless(ramt >= amt); dh = malloc(ramt); if ( dh == NULL ) return NULL; ++dbg_num_alloc; dbg_alloc_amt += amt; dh->dh_amt = amt; p = TOMEM(dh); ht_ninit(&dh->dh_hnode, p); ht_ins_h(&dbg_htab, &dh->dh_hnode); return p; } void *dbg_mem_resize(struct memmgr *mm, void *p, size_t newsize) { size_t ramt; struct dbg_header *dh; struct hnode *hn; void *p2; size_t osize; abort_unless(mm == &dbgmem); hn = ht_lkup(&dbg_htab, p, NULL); if ( hn == NULL ) errsys("dbg_mem_resize: attempt to reallocate non dynamic" "pointer: %p", p); dh = container(hn, struct dbg_header, dh_hnode); osize = dh->dh_amt; if ( newsize > 0 ) { ramt = ROUNDUP(newsize); abort_unless(ramt >= newsize); } else { ramt = 0; } p2 = realloc(dh, ramt); if ( p2 == NULL || ramt == 0 ) { if ( ramt == 0 ) { dbg_alloc_amt -= osize; --dbg_num_alloc; } return NULL; } dbg_alloc_amt = dbg_alloc_amt - osize + newsize; dh = p2; dh->dh_amt = newsize; p = TOMEM(dh); ht_ninit(&dh->dh_hnode, p); ht_ins_h(&dbg_htab, &dh->dh_hnode); return p; } void dbg_mem_free(struct memmgr *mm, void *p) { struct hnode *hn; struct dbg_header *dh; abort_unless(mm == &dbgmem); hn = ht_lkup(&dbg_htab, p, NULL); if ( hn == NULL ) errsys("dbg_mem_free: attempt to free non-dynamic pointer: %p", p); dh = container(hn, struct dbg_header, dh_hnode); dbg_alloc_amt -= dh->dh_amt; --dbg_num_alloc; free(dh); } ulong dbg_get_num_alloc(void) { return dbg_num_alloc; } ulong dbg_get_alloc_amt(void) { return dbg_alloc_amt; } int dbg_is_dyn_mem(void *p) { return ht_lkup(&dbg_htab, p, NULL) != NULL; } void dbg_mem_reset(void) { struct hnode **bkt, **bend; dbg_alloc_amt = 0; dbg_num_alloc = 0; for ( bkt = dbg_htab.bkts, bend = bkt + dbg_htab.nbkts ; bkt < bend ; ++bkt ) while ( *bkt ) ht_rem(*bkt); }
github188/catlib
include/cc/limits.h
<gh_stars>1-10 /* * limits.h -- C standard limits.h file * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __catlimits_h #define __catlimits_h /* * These are best guesses that you can substitute on your own machine if * need be. */ #define CHAR_BIT 8 #define UCHAR_MAX ((uchar)~0) #define UINT_MAX ((uint)~0) #define USHRT_MAX ((ushort)~0) #define ULONG_MAX ((ulong)~0) #define SCHAR_MAX ((signed char)(UCHAR_MAX >> 1)) #define SCHAR_MIN ((signed char)-SCHAR_MAX) #define SHRT_MAX ((short)(USHRT_MAX >> 1)) #define SHRT_MIN ((short)-SHRT_MAX) #define INT_MAX ((int)(UINT_MAX >> 1)) #define INT_MIN ((int)-INT_MAX) #define LONG_MAX ((long)(ULONG_MAX >> 1)) #define LONG_MIN ((long)-LONG_MAX) #endif /* __catlimits_h */
github188/catlib
include/cat/buffer.h
<reponame>github188/catlib<filename>include/cat/buffer.h /* * cat/dynbuf.h -- A generic resizeable byte buffer; * * by <NAME> * * Copyright 2012, See accompanying license * */ #ifndef __cat_buffer_h #define __cat_buffer_h #include <cat/cat.h> #include <cat/mem.h> struct dynbuf { ulong size; byte_t * data; ulong off; ulong len; struct memmgr * mm; }; #define dyb_last(b) ((b)->off + (b)->len) /* all of the below functions will return a -1 if the offset/length */ /* parameters will cause an overflow of ulong */ /* initialize a fresh dynbuf */ void dyb_init(struct dynbuf *b, struct memmgr *mm); /* ensure that the buffer has at least sz bytes */ /* if not, try to allocate it. Return 0 on success and */ /* -1 if unable to allocate the space. */ int dyb_resv(struct dynbuf *b, ulong sz); /* free the memory associated with a dynbuf and re-initialize */ void dyb_clear(struct dynbuf *b); /* re-initialize the dynamic buffer and return the memory it held */ void *dyb_release(struct dynbuf *b); /* reset offset and length pointers for a buffer but keep memory */ void dyb_empty(struct dynbuf *b); /* concatenate 'len' bytes from 'p' to 'b'. Return 0 on success or */ /* -1 if not enough space. */ int dyb_cat(struct dynbuf *b, void *p, ulong len); /* concatenate 'len' bytes from 'p' to 'b'. If 'b' lacks space, try */ /* to allocate it. Return 0 on success and -1 on failure. */ int dyb_cat_a(struct dynbuf *b, void *p, ulong len); /* Set the data in the buffer to 'len' bytes of data starting at 'off' */ /* bytes from the start of the dynbuf. Copy the data from 'p'. Returns 0 */ /* on success, and -1 if not enough space. */ int dyb_set(struct dynbuf *b, ulong off, void *p, ulong len); /* Set the data in the buffer to 'len' bytes of data starting at 'off' */ /* bytes from the start of the dynbuf. Copy the data from 'p'. If 'b' lacks */ /* the space, try to allocate it. Return 0 on success and -1 on failure */ int dyb_set_a(struct dynbuf *b, ulong off, void *p, ulong len); /* copy the 'sb' into 'db'. Returns 0 on success, or -1 if unable to */ /* allocate the necessary space in 'db'. Offsets are preserved and */ /* the 'db' is sized to at least 'sb->size' */ int dyb_copy(struct dynbuf *db, struct dynbuf *sb); #endif /* __cat_dynbuf_h */
github188/catlib
test/testtlsf.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <cat/cat.h> #include <cat/dynmem.h> #include <cat/err.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define NWORDS (1024 * 1024 * 2) #define MAXALLOCS 32 #define NITER 128 #define PRINTPERIOD 1 unsigned long Memory[NWORDS]; struct tlsf Tlsf; void printblock(void *obj, void *ctx) { struct tlsf_block_fake *block = obj; printf("\t%c%c: %u : %p\n", (block->allocated ? 'A' : '-'), (block->prev_allocated ? 'P' : '-'), (uint)block->size, block->ptr); } void printpool(void *obj, void *ctx) { struct tlsfpool *pool = obj; int *poolno = ctx; *poolno += 1; printf("Pool %d\n", *poolno); tlsf_each_block(pool, printblock, NULL); } void printmem(struct tlsf *tlsf, const char *title) { int poolno = 0; printf("-- %s --\n", title); tlsf_each_pool(tlsf, printpool, &poolno); printf("\n"); } void getmem(struct tlsf *tlsf, struct raw *r, size_t len) { if (r->data) tlsf_free(tlsf, r->data); r->data = tlsf_malloc(tlsf, len); if (r->data) r->len = len; } void freemem(struct tlsf *tlsf, struct raw *r) { tlsf_free(tlsf, r->data); r->data = NULL; r->len = 0; } void resizemem(struct tlsf *tlsf, struct raw *r, size_t len) { void *d = tlsf_realloc(tlsf, r->data, len); if (len == 0) { r->data = NULL; len = 0; } else if (d != NULL) { r->data = d; r->len = len; } } void freeallmem(struct tlsf *tlsf, struct raw *rarr, size_t ralen) { size_t i; for ( i = 0; i < ralen; i++ ) freemem(tlsf, rarr + i); } void printraw(struct raw *r, size_t ralen) { unsigned int i; printf("Allocated slots\n"); for ( i = 0; i < ralen; i++ ) if (r[i].data != NULL) printf("\tSlot %d: %p:%u\n", i, r[i].data, (uint)r[i].len); } void doit() { struct raw allocs[MAXALLOCS] = { 0 }; printmem(&Tlsf, "Initial state"); getmem(&Tlsf, &allocs[0], 128); printmem(&Tlsf, "First alloc"); getmem(&Tlsf, &allocs[1], 7); getmem(&Tlsf, &allocs[2], 7); printmem(&Tlsf, "Some more allocs"); freemem(&Tlsf, &allocs[1]); printmem(&Tlsf, "First free"); getmem(&Tlsf, &allocs[3], 48); printmem(&Tlsf, "Another alloc"); freemem(&Tlsf, &allocs[2]); printmem(&Tlsf, "more free"); freeallmem(&Tlsf, allocs, array_length(allocs)); printmem(&Tlsf, "freed all"); } void doit2() { int i, nops, len, idx, op; struct raw allocs[MAXALLOCS] = { 0 }; printmem(&Tlsf, "Initial state"); char str[256]; for (i = 1; i <= NITER; i++) { idx = abs(rand()) % MAXALLOCS; op = abs(rand()) % 2; sprintf(str, "Iter %d -> %s %d, (%u)", i, op ? "free" : (allocs[idx].data ? "free/alloc" : "alloc"), idx, len); if (op == 0) { /* alloc */ len = abs(rand()) % 8192; getmem(&Tlsf, &allocs[idx], len); } else { len = 0; freemem(&Tlsf, &allocs[idx]); } printraw(allocs, array_length(allocs)); printmem(&Tlsf, str); } printmem(&Tlsf, "Final before clear"); freeallmem(&Tlsf, allocs, array_length(allocs)); printmem(&Tlsf, "Final"); } void doit3() /* realloc tests */ { struct raw allocs[MAXALLOCS] = { 0 }; printmem(&Tlsf, "Initial state for realloc tests"); getmem(&Tlsf, &allocs[0], 280); printmem(&Tlsf, "init -> 280"); resizemem(&Tlsf, &allocs[0], 290); printmem(&Tlsf, "resize -> 290"); resizemem(&Tlsf, &allocs[0], 270); printmem(&Tlsf, "resize -> 270"); resizemem(&Tlsf, &allocs[0], 310); printmem(&Tlsf, "resize -> 310"); freeallmem(&Tlsf, allocs, array_length(allocs)); printmem(&Tlsf, "freed all"); getmem(&Tlsf, &allocs[0], 12); getmem(&Tlsf, &allocs[1], 12); getmem(&Tlsf, &allocs[2], 12); freemem(&Tlsf, &allocs[1]); printmem(&Tlsf, "After 3 allocations & 1 free"); printraw(allocs, array_length(allocs)); resizemem(&Tlsf, &allocs[0], 28); printmem(&Tlsf, "After resize"); printraw(allocs, array_length(allocs)); freeallmem(&Tlsf, allocs, array_length(allocs)); printmem(&Tlsf, "freed all"); getmem(&Tlsf, &allocs[0], 12); printmem(&Tlsf, "After 1 allocations: should split next block"); printraw(allocs, array_length(allocs)); resizemem(&Tlsf, &allocs[0], 28); printmem(&Tlsf, "After resize"); freeallmem(&Tlsf, allocs, array_length(allocs)); printmem(&Tlsf, "freed all"); } int main(int argc, char *argv[]) { srand(time(NULL)); tlsf_init(&Tlsf); tlsf_add_pool(&Tlsf, Memory, sizeof(Memory)); doit(); doit2(); doit3(); return 0; }
github188/catlib
include/cat/time.h
/* * cat/time.h -- Functions for timing events * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_time_h #define __cat_time_h #include <cat/cat.h> #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_TIME_DO_DECL 1 #define LDECL static inline #else /* CAT_USE_INLINE */ #define DECL #define LDECL static #endif /* CAT_USE_INLINE */ struct cat_time_s { long sec; long nsec; }; typedef struct cat_time_s cat_time_t; #if defined(CAT_USE_INLINE) && CAT_USE_INLINE static cat_time_t tm_zero = { 0, 0 }; #else extern cat_time_t tm_zero; #endif DECL cat_time_t tm_add(cat_time_t t1, cat_time_t t2); DECL cat_time_t tm_sub(cat_time_t t1, cat_time_t t2); DECL int tm_cmp(cat_time_t t1, cat_time_t t2); DECL int tm_eqz(cat_time_t t); DECL int tm_ltz(cat_time_t t); DECL int tm_gtz(cat_time_t t); DECL int tm_lez(cat_time_t t); DECL int tm_gez(cat_time_t t); DECL int tm_cmpf(void *t1, void *t2); DECL double tm_2dbl(cat_time_t t); DECL long tm_sec(cat_time_t t); DECL long tm_nsec(cat_time_t t); DECL cat_time_t tm_lset(long sec, long nsec); DECL cat_time_t tm_dset(double d); #define TM_LONG_INITIALIZER(_sec, _nsec) { (_sec), (_nsec) } /* start = end ; returns end - (original) start */ DECL cat_time_t tm_mark(cat_time_t *start, cat_time_t end); #if CAT_USE_STDLIB #include <time.h> DECL cat_time_t tm_cget(); #if CAT_HAS_POSIX #include <sys/time.h> DECL cat_time_t tm_uget(); #endif /* CAT_HAS_POSIX */ #endif /* CAT_USE_STDLIB */ #if defined(CAT_TIME_DO_DECL) && CAT_TIME_DO_DECL #if !defined(CAT_USE_INLINE) || CAT_USE_INLINE == 0 cat_time_t tm_zero = { 0, 0 }; #endif LDECL void tm_normalize(cat_time_t *t) { (void)tm_zero; abort_unless(t); while ( t->nsec > 1000000000L || (t->sec < 0 && t->nsec > 0) ) { t->nsec -= 1000000000L; ++t->sec; } while ( t->nsec < -1000000000L || (t->sec > 0 && t->nsec < 0) ) { t->nsec += 1000000000L; --t->sec; } } DECL cat_time_t tm_add(cat_time_t t1, cat_time_t t2) { tm_normalize(&t1); tm_normalize(&t2); t1.sec += t2.sec; t1.nsec += t2.nsec; tm_normalize(&t2); return t1; } DECL cat_time_t tm_sub(cat_time_t t1, cat_time_t t2) { tm_normalize(&t1); tm_normalize(&t2); t1.sec -= t2.sec; t1.nsec -= t2.nsec; tm_normalize(&t1); return t1; } DECL int tm_eqz(cat_time_t t) { return t.sec == 0 && t.nsec == 0; } DECL int tm_ltz(cat_time_t t) { tm_normalize(&t); return t.sec < 0 || t.nsec < 0; } DECL int tm_gtz(cat_time_t t) { tm_normalize(&t); return t.sec > 0 || t.nsec > 0; } DECL int tm_lez(cat_time_t t) { return !tm_gtz(t); } DECL int tm_gez(cat_time_t t) { return !tm_ltz(t); } DECL int tm_cmp(cat_time_t t1, cat_time_t t2) { long d; tm_normalize(&t1); tm_normalize(&t2); if ( (d = t1.sec - t2.sec) == 0 ) d = t1.nsec - t2.nsec; return (d < 0) ? -1 : ((d > 0) ? 1 : 0) ; } DECL int tm_cmpf(void *t1p, void *t2p) { abort_unless(t1p); abort_unless(t2p); return tm_cmp(*(cat_time_t *)t1p, *(cat_time_t *)t2p); } DECL double tm_2dbl(cat_time_t t) { return t.sec + (double)t.nsec / (double)1000000000; } DECL long tm_sec(cat_time_t t) { tm_normalize(&t); return t.sec; } DECL long tm_nsec(cat_time_t t) { tm_normalize(&t); return t.nsec; } DECL cat_time_t tm_dset(double d) { cat_time_t t; t.sec = (long)d; t.nsec = (long)((d - t.sec) * 1000000000L); return t; } DECL cat_time_t tm_lset(long sec, long nsec) { cat_time_t t; t.sec = sec; t.nsec = nsec; tm_normalize(&t); return t; } DECL cat_time_t tm_mark(cat_time_t *old, cat_time_t tnew) { cat_time_t hold; abort_unless(old); hold = tm_sub(tnew, *old); *old = tnew; return hold; } #if CAT_USE_STDLIB DECL cat_time_t tm_cget() { cat_time_t t; clock_t cur; cur = clock(); t.sec = cur / CLOCKS_PER_SEC; t.nsec = (long)((double)(cur - t.sec) / (double)CLOCKS_PER_SEC * 1000000000L); return t; } #if CAT_HAS_POSIX /* Get Posix system time */ DECL cat_time_t tm_uget() { cat_time_t t; struct timeval cur; gettimeofday(&cur, NULL); t.sec = cur.tv_sec; t.nsec = cur.tv_usec * 1000; return t; } #endif /* CAT_HAS_POSIX */ #endif /* CAT_USE_STDLIB */ #endif /* defined(CAT_TIME_DO_DECL) && CAT_TIME_DO_DECL */ #undef DECL #undef LDECL #undef CAT_TIME_DO_DECL #endif /* __cat_time_h */
github188/catlib
test/testlist.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <cat/list.h> #include <cat/stduse.h> #include <cat/mem.h> #define NT 100000000 #define LLEN 100 #define NT2 1000000 int main(int argc, char *argv[]) { struct list list, elem, *node; struct clist *cl; struct timeval tv, tv2; double usec; int i, x; l_init(&list); l_init(&elem); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) { l_ins(&list, &elem); l_rem(&elem); } gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for l_ins(),l_rem()\n", usec * 1000); printf("loading %u elements\n", LLEN); for ( i = 0 ; i < LLEN ; ++i ) l_ins(&list, emalloc(sizeof(struct list))); printf("The l_length(&list) is %lu\n", l_length(&list)); gettimeofday(&tv, 0); for ( i = 0 ; i < NT2 ; ++i ) for ( node = list.next ; node != &list ; node = node->next ) ; gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT2; printf("Roughly %f nanoseconds for %d element traversal\n", usec * 1000, LLEN); while ( l_isempty(&list) ) free(l_deq(&list)); cl = cl_new(NULL, 1); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) { cl_enq(cl, int2ptr(i)); x = ptr2int(cl_deq(cl)); } gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; cl_free(cl); printf("Roughly %f nanoseconds for cl_enq(),cl_deq()\n", usec * 1000); return 0; }
github188/catlib
test/testudps.c
<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <unistd.h> #include <stdio.h> #include <cat/err.h> #include <cat/net.h> int main(int argc, char *argv[]) { int fd, n=1; char recvbuf[255], aname[255]; struct sockaddr_storage sas; socklen_t addrsiz = 255, slen = sizeof(sas); ERRCK(fd = udp_sock(NULL, "10000")); ERRCK(getsockname(fd, (SA *)&sas, &slen)); fprintf(stderr, "listening on %s\n", net_tostr((SA *)&sas, aname, 255)); while ( 1 ) { n = recvfrom(fd, recvbuf, 255, 0, (SA *)&sas, &addrsiz); fprintf(stderr, "Received connection from %s\n", net_tostr((SA *)&sas, aname, 255)); sendto(fd, recvbuf, n, 0, (SA *)&sas, addrsiz); } close(fd); return 0; }
github188/catlib
include/std/stdlib.h
<gh_stars>1-10 /* * stdlib.h -- Standard C library routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_stdlib_h #define __cat_stdlib_h #include <cat/cat.h> #include <stdarg.h> /* We use the mem* functions even if we don't use the standard library */ #if !CAT_USE_STDLIB long strtol(const char *start, char **cp, int base); ulong strtoul(const char *start, char **cp, int base); double strtod(const char *start, char **cp); void *malloc(size_t len); void *calloc(size_t nmem, size_t ilen); void *realloc(void *omem, size_t len); void free(void *mem); /* TODO: in the near future * errno */ void exit(int status); void abort(void); #endif /* !CAT_USE_STDLIB */ #endif /* __cat_stdlib_h */
github188/catlib
test/markov.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> #include <cat/ring.h> #include <cat/hash.h> #include <cat/list.h> #include <cat/err.h> #include <cat/stduse.h> #include <cat/cds.h> #include <sys/time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> CDS_NEWSTRUCT(struct list, char *, strent_s); #define NPREF 2 #define NONWORD "\n" #define END "\t" #define MAXGEN 10000 #define HTSIZ 4096 #define WORDLEN 79 #define BUFLEN ((WORDLEN + 1) * NPREF + 1) char *Prefixes[NPREF]; struct ring Buffer; struct chtab *Table; static void print_tablist(void *nodep, void *aux) { struct chnode *n = nodep; struct list *t, *l = n->data; printf("*%s* : *%s* ", (char *)n->node.key, CDS_DATA(l, strent_s)); for ( t = l->next ; t != l ; t = t->next ) printf(" *%s*", CDS_DATA(t, strent_s)); printf("\n"); } void printall(struct chtab *t) { cht_apply(t, print_tablist, NULL); } void add(char *word) { struct hnode *node; struct list *ol; strent_s *w; char *s; int i; ring_reset(&Buffer); ring_fmt(&Buffer, "%s", Prefixes[0]); for ( i = 1 ; i < NPREF ; ++i ) ring_fmt(&Buffer, " %s", Prefixes[i]); s = estrdup(word); abort_unless(s != NULL); CDS_NEW(w, s); l_init(CDS_NPTR(w, strent_s)); ol = cht_get(Table, Buffer.data); if ( ! ol ) cht_put(Table, Buffer.data, CDS_NPTR(w, strent_s)); else l_ins(ol->prev, CDS_NPTR(w, strent_s)); memmove(Prefixes, Prefixes + 1, (NPREF-1) * sizeof(char *)); Prefixes[NPREF-1] = s; } void generate(void) { int i, j, n; struct hnode *node; struct list *s, *t, *h; char *word; for ( i = 0 ; i < MAXGEN ; ++i ) { ring_reset(&Buffer); ring_fmt(&Buffer, "%s", Prefixes[0]); for ( j = 1 ; j < NPREF ; ++j ) ring_fmt(&Buffer, " %s", Prefixes[j]); h = s = cht_get(Table, Buffer.data); n = 1; for ( t = s->next ; t != s ; t = t->next ) if ( (random() % ++n) == 0 ) h = t; word = CDS_DATA(h, strent_s); if ( strcmp(word, END) == 0 ) return; memmove(Prefixes, Prefixes + 1, (NPREF-1) * sizeof(char *)); Prefixes[NPREF-1] = word; printf("%s\n", word); } } int main(int argc, char **argv) { int i; char word[WORDLEN+1], fmt[10], *cur = NULL; struct timeval tv; gettimeofday(&tv, NULL); srandom(tv.tv_usec); for ( i = 0 ; i < NPREF ; ++i ) Prefixes[i] = NONWORD; Table = cht_new(HTSIZ, NULL, NULL, 1); ring_init(&Buffer, emalloc(BUFLEN), BUFLEN); sprintf(fmt, "%%%ds", (int)sizeof(word)-1); while ( scanf(fmt, word) > 0 ) add(word); add(END); /* printall(Table); */ for ( i = 0 ; i < NPREF ; ++i ) Prefixes[i] = NONWORD; generate(); return 0; }
github188/catlib
test/testtcpc.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <cat/err.h> #include <cat/net.h> #include <cat/io.h> int main(int argc, char *argv[]) { int fd, n, n2; char recvbuf[255]; char sendbuf[255]; char *host = "localhost"; if ( argc > 1 ) host = argv[1]; ERRCK(fd = tcp_cli(host, "10000")); for ( ; ; ) { if (fgets(sendbuf, 255, stdin) == NULL ) {close(fd); return 0; } n = strlen(sendbuf); ERRCK(io_write(fd, sendbuf, n)); ERRCK(n2 = io_read(fd, recvbuf, n)); recvbuf[n2] = '\0'; fprintf(stdout, "Got back %d bytes : %s", n2, recvbuf); } return 0; }
github188/catlib
test/testhash.c
<reponame>github188/catlib<filename>test/testhash.c /* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <cat/hash.h> #include <cat/stduse.h> #define NUMSTR 4 #define NOPS 65536 #define NITER (128 * NOPS) struct htab t; struct hnode *buckets[128 * 1024]; void timeit() { struct hnode nodes[NOPS], *node; uint hashes[NOPS]; int i, j; char *key; struct timeval start, end; double usec; uint h; ht_init(&t, buckets, array_length(buckets), cmp_str, ht_shash, NULL); for (i = 0; i < NOPS; i++) { key = str_fmt_a("node%d", i); ht_ninit(&nodes[i], key); hashes[i] = ht_hash(&t, key); } gettimeofday(&start, NULL); for (j = 0; j < NITER / NOPS; j++) { for (i = 0; i < NOPS; i++) ht_ins(&t, &nodes[i], hashes[i]); for (i = 0; i < NOPS; i++) ht_rem(&nodes[i]); } gettimeofday(&end, NULL); usec = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; usec /= NITER; printf("Roughly %f nsec for ht_ins(),ht_rem() w/%d elem\n", usec * 1000, NOPS); fflush(stdout); gettimeofday(&start, NULL); for (j = 0; j < NITER / NOPS; j++) { for (i = 0; i < NOPS; i++) { if (ht_lkup(&t, nodes[i].key, &h)) err("iteration %d: duplicate node for key %d found\n", j, i); ht_ins(&t, &nodes[i], h); } for (i = 0; i < NOPS; i++) ht_rem(&nodes[i]); } gettimeofday(&end, NULL); usec = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; usec /= NITER; printf("Roughly %f nsec for ht_lkup(),ht_ins(),ht_rem() w/%d elem\n", usec * 1000, NOPS); fflush(stdout); gettimeofday(&start, NULL); for ( i = 0 ; i < NITER ; ++i ) { ht_ins(&t, &nodes[0], hashes[0]); ht_rem(&nodes[0]); } gettimeofday(&end, NULL); usec = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; usec /= NITER; printf("Roughly %f nsec for ht_ins(),ht_rem() with empty table\n", usec * 1000); fflush(stdout); gettimeofday(&start, NULL); for ( i = 0 ; i < NITER ; ++i ) { if (ht_lkup(&t, nodes[0].key, &h)) err("duplicate node for key %d found", i); ht_ins(&t, &nodes[0], h); ht_rem(&nodes[0]); } gettimeofday(&end, NULL); usec = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; usec /= NITER; printf("Roughly %f nsec for ht_ins(),ht_lkup(),ht_rem() with empty table\n", usec * 1000); fflush(stdout); for (i = 0; i < NOPS; i++) free(nodes[i].key); } int main() { int i; char *strs[NUMSTR][2] = { {"key 1", "Hi there!" }, {"key2", "String 2!"}, {"Key 3!", "By now! this is over."}, {"key 1", "Overwrite."} }; struct chtab *table; char *s; table = cht_new(128, NULL, NULL, 1); for (i = 0; i < NUMSTR; i++) { cht_put(table, strs[i][0], strs[i][1]); s = cht_get(table, strs[i][0]); printf("Put (%s) at key (%s): %p\n", strs[i][1], strs[i][0], s); } if (cht_get(table, "bye")) printf("found something I shouldn't have!\n"); s = cht_get(table, strs[1][0]); printf("Under key %s is the string %s\n", strs[1][0], s); printf("address is %p\n\n", s); s = cht_get(table, strs[2][0]); printf("Under key %s is the string %s\n", strs[2][0], s); printf("address is %p\n\n", s); s = cht_get(table, strs[0][0]); printf("Under key %s is the string %s\n", strs[0][0], s); printf("address is %p\n\n", s); s = cht_get(table, strs[1][0]); cht_del(table, strs[1][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); s = cht_del(table, strs[2][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); if (cht_get(table, strs[1][0])) printf("Error! Thing not deleted! : %s\n", (char *)cht_get(table, strs[1][0])); cht_free(table); timeit(); return 0; }
github188/catlib
src/buffer.c
<filename>src/buffer.c<gh_stars>1-10 /* * buffer.c -- growable data buffers. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include "cat/buffer.h" #include <stdlib.h> #include <string.h> #if CAT_USE_INLINE #define INLINE inline #else #define INLINE #endif static INLINE void dyb_sanity(struct dynbuf *b) { abort_unless(b && b->mm != NULL && (b->off <= b->size) && (b->size - b->off >= b->len) && (b->data != NULL || b->size == 0)); } void dyb_init(struct dynbuf *b, struct memmgr *mm) { b->size = 0; b->data = NULL; b->off = 0; b->len = 0; if ( mm == NULL ) b->mm = &stdmm; else b->mm = mm; } int dyb_resv(struct dynbuf *b, ulong sz) { byte_t *p; dyb_sanity(b); if ( sz <= b->size ) return 0; /* always at least double size if possible to */ /* make the max # of allocations the ceiling of lg2 of SIZE_MAX */ if ( (b->size < ((ulong)-1) / 2) && (sz < b->size * 2) ) sz = b->size * 2; p = mem_resize(b->mm, b->data, sz); if ( p == NULL ) return -1; b->data = p; b->size = sz; return 0; } void dyb_clear(struct dynbuf *b) { dyb_sanity(b); mem_free(b->mm, b->data); dyb_init(b, b->mm); } void *dyb_release(struct dynbuf *b) { void *p; dyb_sanity(b); p = b->data; b->data = NULL; b->size = 0; b->len = 0; b->off = 0; return p; } void dyb_empty(struct dynbuf *b) { dyb_sanity(b); b->len = 0; b->off = 0; } int dyb_cat(struct dynbuf *b, void *p, ulong len) { dyb_sanity(b); if ( b->size - b->off - b->len < len ) return -1; memmove(b->data + b->off + b->len, p, len); b->len += len; return 0; } int dyb_cat_a(struct dynbuf *b, void *p, ulong len) { dyb_sanity(b); if ( b->size - b->off - b->len < len ) { if ( ((ulong)-1) - b->off - b->len < len ) return -1; if ( dyb_resv(b, b->off + b->len + len) < 0 ) return -1; } memmove(b->data + b->off + b->len, p, len); b->len += len; return 0; } int dyb_set(struct dynbuf *b, ulong off, void *p, ulong len) { dyb_sanity(b); if ( b->size < off || b->size - off < len ) return -1; b->off = off; b->len = len; memmove(b->data + off, p, len); return 0; } int dyb_set_a(struct dynbuf *b, ulong off, void *p, ulong len) { ulong tlen; dyb_sanity(b); if ( ((ulong)-1) - off > len ) return -1; tlen = off + len; if ( b->size < tlen ) { if ( dyb_resv(b, tlen) < 0 ) return -1; } b->off = off; b->len = len; memmove(b->data + off, p, len); return 0; } int dyb_copy(struct dynbuf *db, struct dynbuf *sb) { dyb_sanity(db); dyb_sanity(sb); if ( dyb_resv(db, db->size) < 0 ) return -1; db->off = sb->off; db->len = sb->len; memmove(db->data + db->off, sb->data + sb->off, sb->len); return 0; }
github188/catlib
attic/regex.h
/* * cat/regex.h -- simplified UNIX regular expressions * * by <NAME> * * Copyright 2003, See accompanying license * */ #ifndef __CAT_REGEX_H #define __CAT_REGEX_H #include <sys/types.h> #include <cat/cat.h> #include <regex.h> int re_find(const char *s, const char *p, regmatch_t *m, int nm); int re_lastrep(const char *r); int re_replen(const char *s, const char *r, regmatch_t *m); int re_replace(const char *s, const char *r, const regmatch_t *m, char *d); #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #ifndef CAT_RE_MAXSUB #define CAT_RE_MAXSUB 20 #endif /* CAT_RE_MAXSUB */ char * re_sr(const char *s, const char *p, const char *r); #endif /* CAT_USE_STDLIB */ #endif /* __CAT_REGEX_H */
github188/catlib
src/uevent.c
/* * cat/uevent.c -- UNIX event dispatch * * by <NAME> * * Copyright 2008-2012 -- See accompanying license * */ #include <cat/cat.h> #if CAT_HAS_POSIX #include <sys/types.h> #include <sys/select.h> #include <sys/time.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <errno.h> #include <cat/mem.h> #include <cat/aux.h> #include <cat/uevent.h> #include <cat/err.h> #include <cat/stduse.h> static int fdmax(struct cavltree *a); static void disable_signals(sigset_t *save); static void restore_signals(sigset_t *save); static void tdispatch(void *lp, void *muxp); static void iorun(void *ioep, void *param); static void run_sig_handlers(struct uemux *mux, sigset_t *ss, int maxsig); static sigset_t uemux_sset; static int uemux_maxsig; static int uemux_initialized = 0; #define IKEY(_i) (int2ptr((_i) + 1)) static int fdmax(struct cavltree *a) { struct anode *n = avl_getmax(&a->tree); struct ue_ioevent *io; if ( !n ) return -1; io = cavl_data(n); return io->fd; } static void disable_signals(sigset_t *save) { sigset_t block; abort_unless(save); sigfillset(&block); if ( sigprocmask(SIG_BLOCK, &block, save) < 0 ) errsys("disabling signals in sigprocmask(): "); } static void restore_signals(sigset_t *save) { abort_unless(save); if ( sigprocmask(SIG_SETMASK, save, NULL) < 0 ) errsys("restoring signals in sigprocmask(): "); } void ue_init(struct uemux *mux, struct memmgr *mm) { abort_unless(mux); if ( !uemux_initialized ) { uemux_initialized = 1; sigemptyset(&uemux_sset); uemux_maxsig = -1; } mux->mm = mm; mux->done = 0; mux->maxfd = -1; mux->fdtab = cavl_new(&cavl_std_attr_pkey, 0); dl_init(&mux->timers, tm_zero); l_init(&mux->iolist); FD_ZERO(&mux->rset); FD_ZERO(&mux->wset); FD_ZERO(&mux->eset); mux->sigtab = cavl_new(&cavl_std_attr_pkey, 0); } static void free_io(void *iop, void *mmp) { ue_io_del(iop); } static void free_sigevent(void *sep, void *mmp) { ue_sig_del(sep); } void ue_fini(struct uemux *mux) { struct ue_timer *t; abort_unless(mux); if ( mux->mm ) l_apply(&mux->iolist, free_io, NULL); cavl_free(mux->fdtab); if ( mux->mm ) cavl_apply(mux->sigtab, free_sigevent, NULL); cavl_free(mux->sigtab); while ( !dl_isempty(&mux->timers) ) { t = container(dl_head(&mux->timers), struct ue_timer, entry); ue_tm_del(t); } } void ue_stop(struct uemux *mux) { mux->done = 1; } static void tdispatch(void *lp, void *muxp) { struct list *l = lp; struct uemux *m = muxp; struct ue_timer *t; cat_time_t tout; if ( m->done ) return; l_rem(l); t = container(container(l, struct dlist, entry), struct ue_timer,entry); if ( t->flags & UE_PERIODIC ) { tout = tm_lset(t->orig / 1000, (t->orig % 1000) * 1000000); dl_init(&t->entry, tout); dl_ins(&m->timers, &t->entry); } cb_call(&t->cb, NULL); } void ue_tm_init(struct ue_timer *t, int flags, ulong ttl, callback_f func, void *ctx) { cat_time_t tout; abort_unless(t); abort_unless(func); t->flags = flags; t->orig = ttl; cb_init(&t->cb, func, ctx); tout = tm_lset(t->orig / 1000, (t->orig % 1000) * 1000000); dl_init(&t->entry, tout); t->mm = NULL; } int ue_tm_reg(struct uemux *mux, struct ue_timer *t) { abort_unless(t); abort_unless(mux); dl_ins(&mux->timers, &t->entry); t->flags |= UE_TREG; return 0; } void ue_tm_cancel(struct ue_timer *t) { abort_unless(t); if ( !(t->flags & UE_TREG) ) return; dl_rem(&t->entry); t->flags &= ~UE_TREG; } void ue_io_init(struct ue_ioevent *io, int type, int fd, callback_f f, void *a) { cb_init(&io->cb, f, a); l_init(&io->fdlist); io->fd = fd; io->type = type; io->mux = NULL; io->mm = NULL; } int ue_io_reg(struct uemux *mux, struct ue_ioevent *io) { struct list *list; abort_unless(mux); abort_unless(io); abort_unless(io->type == UE_RD || io->type == UE_WR || io->type == UE_EX); abort_unless(io->fd >= 0); if ( (list = cavl_get(mux->fdtab, IKEY(io->fd))) == NULL ) { list = mem_get(mux->mm, sizeof(struct list)); if ( list == NULL ) return -1; l_init(list); if ( cavl_put(mux->fdtab, IKEY(io->fd), list) < 0 ) { mem_free(mux->mm, list); return -1; } } l_ins(list, &io->fdlist); cb_reg(&mux->iolist, &io->cb); switch(io->type) { case UE_RD: FD_SET(io->fd, &mux->rset); break; case UE_WR: FD_SET(io->fd, &mux->wset); break; case UE_EX: FD_SET(io->fd, &mux->eset); break; } /* check if we have a new high fd */ if ( io->fd > mux->maxfd ) mux->maxfd = io->fd; io->mux = mux; return 0; } void ue_io_cancel(struct ue_ioevent *io) { struct uemux *mux; struct list *list, *trav; struct ue_ioevent *io2; abort_unless(io); if ( !(mux = io->mux) ) return; io->mux = NULL; cb_unreg(&io->cb); l_rem(&io->fdlist); list = cavl_get(mux->fdtab, IKEY(io->fd)); abort_unless(list); l_for_each(trav, list) { io2 = container(trav, struct ue_ioevent, fdlist); if ( io2->type == io->type ) break; } if ( trav == l_end(list) ) { switch(io->type) { case UE_RD: FD_CLR(io->fd, &mux->rset); break; case UE_WR: FD_CLR(io->fd, &mux->wset); break; case UE_EX: FD_CLR(io->fd, &mux->eset); break; } } if ( l_isempty(list) ) { cavl_del(mux->fdtab, IKEY(io->fd)); if ( io->fd == mux->maxfd ) mux->maxfd = fdmax(mux->fdtab); mem_free(mux->mm, list); } } void ue_sig_init(struct ue_sigevent *se, int signum, callback_f f, void *x) { l_init(&se->cb.entry); se->mm = NULL; se->cb.func = f; se->cb.ctx = x; se->signum = signum; se->mux = NULL; } static void ue_handler(int signum) { sigaddset(&uemux_sset, signum); if ( signum > uemux_maxsig ) uemux_maxsig = signum; } int ue_sig_reg(struct uemux *mux, struct ue_sigevent *se) { struct list *list; sigset_t save; struct sigaction sa; disable_signals(&save); se->mux = mux; l_init(&se->cb.entry); if ( (list = cavl_get(mux->sigtab, IKEY(se->signum))) == NULL ) { list = mem_get(mux->mm, sizeof(struct list)); if ( list == NULL ) { restore_signals(&save); return -1; } l_init(list); if ( cavl_put(mux->sigtab, IKEY(se->signum), list) < 0 ) { mem_free(mux->mm, list); restore_signals(&save); return -1; } /* ADD the signal to the list to watch */ /* TODO: is this necessary? Why did I put this here*/ memset(&sa, 0, sizeof(sa)); sa.sa_handler = ue_handler; sigfillset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if ( sigaction(se->signum, &sa, NULL) < 0 ) { cavl_del(mux->sigtab, IKEY(se->signum)); mem_free(mux->mm, list); restore_signals(&save); return -1; } } cb_reg(list, &se->cb); restore_signals(&save); return 0; } void ue_sig_cancel(struct ue_sigevent *se) { struct uemux *mux; struct list *list; sigset_t save; abort_unless(se); disable_signals(&save); if ( !(mux = se->mux) ) { restore_signals(&save); return; } se->mux = NULL; cb_unreg(&se->cb); list = cavl_get(mux->sigtab, IKEY(se->signum)); abort_unless(list); if ( l_isempty(list) ) { cavl_del(mux->sigtab, IKEY(se->signum)); mem_free(mux->mm, list); /* TODO could add code to remove handler */ /* would need to save the old sigaction entry */ } restore_signals(&save); } void ue_sig_clear(void) { sigset_t save; disable_signals(&save); sigemptyset(&uemux_sset); uemux_maxsig = -1; restore_signals(&save); } static void run_sig_handlers(struct uemux *mux, sigset_t *ss, int maxsig) { int i; struct list *list; for ( i = 0; i <= maxsig ; ++i ) { if ( mux->done ) return; if ( !sigismember(ss, i) ) continue; if ( (list = cavl_get(mux->sigtab, IKEY(i))) == NULL ) continue; abort_unless(list); /* TODO, fix this int2ptr */ cb_run(list, int2ptr(i)); } } struct ue_iorun_prm { struct uemux * mux; fd_set * rset; fd_set * wset; fd_set * eset; }; static void iorun(void *ioep, void *param) { struct ue_ioevent *io = container(container(ioep, struct callback, entry), struct ue_ioevent, cb); struct ue_iorun_prm *iorp = param; fd_set *set = NULL; if ( iorp->mux->done ) return; switch(io->type) { case UE_RD: set = iorp->rset; break; case UE_WR: set = iorp->wset; break; case UE_EX: set = iorp->eset; break; } if ( FD_ISSET(io->fd, set) ) cb_call(&io->cb, int2ptr(io->fd)); } void ue_next(struct uemux *mux) { int i, maxsig; fd_set rset, wset, eset; struct timeval cur, delta, tv, *tvp; struct ue_iorun_prm iorp; struct list l; cat_time_t ct; sigset_t save, fired; abort_unless(mux); if ( mux->done ) return; tvp = NULL; rset = mux->rset; wset = mux->wset; eset = mux->eset; dl_first(&mux->timers, &ct); if ( tm_gez(ct) ) { delta.tv_sec = tm_sec(ct); delta.tv_usec = tm_nsec(ct) / 1000; gettimeofday(&cur, NULL); tvp = &delta; } i = select(mux->maxfd + 1, &rset, &wset, &eset, tvp); if ( i < 0 && errno != EINTR ) { errsys("ue_next (select): "); } disable_signals(&save); maxsig = uemux_maxsig; uemux_maxsig = -1; if ( maxsig >= 0 ) { fired = uemux_sset; restore_signals(&save); run_sig_handlers(mux, &fired, maxsig); } else { restore_signals(&save); } /* possible if a signal fired */ if ( i < 0 ) return; if ( tvp ) { gettimeofday(&tv, NULL); delta.tv_sec = tv.tv_sec - cur.tv_sec; delta.tv_usec = tv.tv_usec - cur.tv_usec; if (delta.tv_usec < 0) { delta.tv_sec -= 1; delta.tv_usec += 1000000; } ct = tm_lset(delta.tv_sec, delta.tv_usec * 1000); l_init(&l); dl_adv(&mux->timers, ct, &l); l_apply(&l, tdispatch, mux); } iorp.mux = mux; iorp.rset = &rset; iorp.wset = &wset; iorp.eset = &eset; l_apply(&mux->iolist, iorun, &iorp); } void ue_run(struct uemux *mux) { abort_unless(mux); while ( (!dl_isempty(&mux->timers) || (mux->maxfd >= 0)) && !mux->done ) ue_next(mux); } static int done(void *arg, struct callback *cb) { int *ip = cb->ctx; *ip = 1; return 0; } void ue_runfor(struct uemux *mux, ulong msec) { int timeout = 0; struct ue_timer timer; abort_unless(mux); ue_tm_init(&timer, UE_TIMEOUT, msec, done, &timeout); ue_tm_reg(mux, &timer); while ( !timeout && !mux->done ) ue_next(mux); } struct ue_ioevent * ue_io_new(struct uemux *m, int type, int fd, callback_f f, void *ctx) { struct ue_ioevent *io; abort_unless(m); abort_unless(m->mm); if ( (io = mem_get(m->mm, (sizeof(*io)))) == NULL ) return NULL; ue_io_init(io, type, fd, f, ctx); io->mm = m->mm; ue_io_reg(m, io); return io; } void ue_io_del(struct ue_ioevent *io) { abort_unless(io); ue_io_cancel(io); if ( io->mm ) mem_free(io->mm, io); } struct ue_timer * ue_tm_new(struct uemux *m, int flags, ulong ttl, callback_f f, void *ctx) { struct ue_timer *t; abort_unless(m && m->mm); if ( (t = mem_get(m->mm, sizeof(*t))) == NULL ) return NULL; ue_tm_init(t, flags, ttl, f, ctx); t->mm = m->mm; ue_tm_reg(m, t); return t; } void ue_tm_del(struct ue_timer *t) { abort_unless(t); ue_tm_cancel(t); if ( t->mm ) mem_free(t->mm, t); } struct ue_sigevent * ue_sig_new(struct uemux *m, int signum, callback_f f, void *ctx) { struct ue_sigevent *se; abort_unless(m && m->mm); if ( (se = mem_get(m->mm, sizeof(*se))) == NULL ) return NULL; ue_sig_init(se, signum, f, ctx); se->mm = m->mm; ue_sig_reg(m, se); return se; } void ue_sig_del(struct ue_sigevent *se) { abort_unless(se); ue_sig_cancel(se); if ( se->mm ) mem_free(se->mm, se); } #endif /* CAT_HAS_POSIX */
github188/catlib
src/bitset.c
<gh_stars>1-10 /* * bitset.c -- Bit array-based set * * by <NAME> * * Copyright 2007 - 2012 See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_BITSET_DO_DECL #define CAT_USE_INLINE 0 #define CAT_BITSET_DO_DECL 1 #include <cat/bitset.h>
github188/catlib
include/cat/hash.h
/* * cat/hash.h -- Hash table implementation * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_hash_h #define __cat_hash_h #include <cat/cat.h> #include <cat/aux.h> /* pointer to a hash function: takes a 'key' and context */ typedef uint (*hash_f)(const void *key, void *ctx); /* A hash table data structure */ struct htab { struct hnode ** bkts; /* pointer to an array of node buckets */ uint nbkts; /* number of node buckets */ uint po2mask; /* mask to apply to get bucket from hash */ cmp_f cmp; /* key comparison function */ hash_f hash; /* hash function */ void * hctx; /* context for the hash function */ } ; /* Structure for a node in a hash table */ struct hnode { struct hnode * next; /* next entry in the bucket */ struct hnode ** prevp; /* pointer pointer of the previous entry */ void * key; /* pointer to the key of the node */ } ; #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define PTRDECL static #define STATIC_DECL DECL #define CAT_HASH_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #define PTRDECL #define STATIC_DECL static #endif /* CAT_USE_INLINE */ /* * Initialize hash table 't' with 'bkts' pointing to an array of 'nbkts' * hash node pointers, 'cmp' pointing to a comparison function, 'hashf' * pointing to a hash function and 'hctx' pointing to context for hashf. */ DECL void ht_init(struct htab *t, struct hnode **bkts, uint nbkts, cmp_f cmpf, hash_f hashf, void *hctx); /* Initialize a hash node 'node' with 'key' as its key. */ DECL void ht_ninit(struct hnode *node, void *key); /* Return the hash value for 'key' using the hash function and context in 't' */ DECL uint ht_hash(struct htab *t, const void *key); /* * Find the node in the hash table 't' with key 'key'. If found return it, * otherwise return NULL. Either way, if 'hash' is non-NULL, store the hash * of 'key' in it to allow for fast insertion with ht_ins(). */ DECL struct hnode * ht_lkup(struct htab *t, const void *key, uint *hash); /* * Insert 'node' into 't' with hash 'hash'. Assumes 'hash' was calculated * by ht_hash() or returned through the third parameter of ht_lkup(); */ DECL void ht_ins(struct htab *t, struct hnode *node, uint hash); /* Insert 'node' into 't' computing the hash for 'node's key first */ DECL void ht_ins_h(struct htab *t, struct hnode *node); /* Remove 'node' from its hash table */ DECL void ht_rem(struct hnode *node); /* Apply 'func' to every node in 't' passing 'ctx' as state to 'func' */ DECL void ht_apply(struct htab *t, apply_f func, void * ctx); /* A hash function that hashes a NULL terminated string */ PTRDECL uint ht_shash(const void *key, void *unused); /* * A hash function that hashes the pointer value 'key'. Note, 'key' * does not point to the pointer to be hashed; it is the value to * hash. */ PTRDECL uint ht_phash(const void *key, void *unused); /* A hash function over a 'struct raw'; ie. key points to a struct raw */ PTRDECL uint ht_rhash(const void *key, void *unused); /* A hash function that treats 'key' as an integer */ PTRDECL uint ht_ihash(const void *key, void *unused); /* ----- Implementation ----- */ #if defined(CAT_HASH_DO_DECL) && CAT_HASH_DO_DECL DECL void ht_init(struct htab *t, struct hnode **bkts, uint nbkts, cmp_f cmp, hash_f hash, void *hctx) { uint i; /* XXX useless code to silence the compiler about unused funcs */ (void)ht_shash; (void)ht_phash; (void)ht_rhash; (void)ht_ihash; abort_unless(t != NULL); abort_unless(bkts != NULL); abort_unless(nbkts > 0); t->nbkts = nbkts; t->bkts = bkts; for ( i = 0 ; i < nbkts ; ++i ) bkts[i] = NULL; /* check if size is a power of 2 */ if ( (nbkts & (nbkts - 1)) == 0 ) t->po2mask = nbkts - 1; else t->po2mask = 0; t->cmp = cmp; t->hash = hash; t->hctx = hctx; } DECL void ht_ninit(struct hnode *node, void *key) { abort_unless(node != NULL); abort_unless(key != NULL); node->next = NULL; node->prevp = NULL; node->key = key; } #if !CAT_HAS_DIV STATIC_DECL uint _modulo(uint dend, uint dsor) { uint r = 0; int i; if ( dsor == 0 ) return (uint)-1; for ( i = 0; i < sizeof(uint)*8 ; ++i ) { r = (r << 1) | (dend >> (sizeof(uint) * 8 - 1)); dend = dend << 1; if ( r >= dsor ) { r -= dsor; dend += 1; } } return r; } #endif /* !CAT_HAS_DIV */ DECL struct hnode * ht_lkup(struct htab *t, const void *key, uint *hp) { struct hnode *node; uint h; abort_unless(t != NULL); abort_unless(key != NULL); h = (*t->hash)(key, t->hctx); if ( hp != NULL ) *hp = h; if ( t->po2mask ) { node = t->bkts[h & t->po2mask]; } else { #if CAT_HAS_DIV node = t->bkts[h % t->nbkts]; #else /* CAT_HAS_DIV */ h = _modulo(h, t->nbkts); node = t->bkts[h]; #endif /* CAT_HAS_DIV */ } while ( node != NULL ) { if ( !(*t->cmp)(node->key, key) ) return node; node = node->next; } return NULL; } DECL void ht_ins(struct htab *t, struct hnode *node, uint hash) { struct hnode **trav; abort_unless(t != NULL); abort_unless(node != NULL); if ( t->po2mask ) { trav = t->bkts + (hash & t->po2mask); } else { #if CAT_HAS_DIV trav = t->bkts + (hash % t->nbkts); #else /* CAT_HAS_DIV */ hash = _modulo(hash, t->nbkts); trav = t->bkts + hash; #endif /* CAT_HAS_DIV */ } node->prevp = trav; node->next = *trav; if ( *trav != NULL ) (*trav)->prevp = &node->next; *trav = node; } DECL void ht_ins_h(struct htab *t, struct hnode *node) { abort_unless(node != NULL); ht_ins(t, node, ht_hash(t, node->key)); } DECL void ht_rem(struct hnode *node) { struct hnode **prevp; abort_unless(node != NULL); prevp = node->prevp; if ( prevp != NULL ) { if ( (*prevp = node->next) != NULL ) (*prevp)->prevp = prevp; node->prevp = NULL; } node->next = NULL; } DECL uint ht_hash(struct htab *t, const void *key) { abort_unless(t != NULL); return (*t->hash)(key, t->hctx); } DECL void ht_apply(struct htab *t, apply_f func, void *ctx) { uint num; struct hnode **bkt, *node, *next; abort_unless(t != NULL); abort_unless(func != NULL); for ( num = t->nbkts, bkt = t->bkts ; num ; --num, ++bkt ) { for ( node = *bkt ; node ; node = next ) { next = node->next; (*func)(node, ctx); } } } PTRDECL uint ht_shash(const void *key, void *unused) { const uchar *p = key; uint h = 0, g; abort_unless(p != NULL); while ( *p ) { h = (h << 4) + (uint)(*p++); if ( (g = h & 0xf000000) ) { h ^= g >> 24; h ^= g; } } return h; } PTRDECL uint ht_rhash(const void *key, void *unused) { const uchar *p; uint h = 0, g, l; struct raw const *r = key; abort_unless(key != NULL); l = r->len; p = (const uchar *)r->data; abort_unless(l != 0); abort_unless(l <= (uint)-1); abort_unless(p != NULL); while ( l-- ) { h = (h << 4) + (*p++); if ( (g = h & 0xf000000) ) { h ^= g >> 24; h ^= g; } } return h; } PTRDECL uint ht_phash(const void *key, void *unused) { return (uint)(ptr2uint(key) >> 2); } PTRDECL uint ht_ihash(const void *key, void *unused) { uintptr_t v = ptr2uint(key); return (v * (v >> 7) + (v >> 25)) | (v << 18); } struct hash_iter { struct hnode **bucket; struct hnode *node; }; #define ht_for_each(n, i, t) \ for ( (i).bucket = (t).bkts; \ (i).bucket < (t).bkts + (t).nbkts; \ ++(i).bucket ) \ for ( (n) = *(i).bucket ; \ (i).node = (((n) != NULL) ? (n)->next : NULL),\ (n) != NULL ; \ (n) = (i).node ) #endif /* CAT_HASH_DO_DECL */ #undef PTRDECL #undef DECL #undef CAT_HASH_DO_DECL #endif /* __cat_hash_h */
github188/catlib
attic/mem.c
<reponame>github188/catlib /* * mem.c -- funtions needed by most or all modules * * by <NAME> * * Copyright 2003, 2004 See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> void *mem_get(struct memsys *m, unsigned long len) { if ( !m || !m->ms_alloc ) return NULL; return m->ms_alloc(m, len); } void *mem_resize(struct memsys *m, void *mem, unsigned long len) { if ( !m || !m->ms_resize ) return NULL; return m->ms_resize(m, mem, len); } void mem_free(struct memsys *m, void *mem) { if ( !m || !m->ms_free ) return; return m->ms_free(m, mem); } void applyfree(void *data, void *mp) { struct memsys *m = mp; m->ms_free(m, data); } #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <stdlib.h> #include <string.h> #include <cat/err.h> void * std_alloc(struct memsys *m, unsigned size) { assert(m && size > 0); return malloc(size); } void * std_resize(struct memsys *m, void *old, unsigned newsize) { assert(m && newsize > 0); return realloc(old, newsize); } void std_free(struct memsys *m, void *old) { assert(m); return free(old); } struct memsys stdmem = { std_alloc, std_resize, std_free, &stdmem }; void * emalloc(size_t size) { void *m; if ( !(m = malloc(size)) ) errsys("emalloc: "); return m; } void * erealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) ) errsys("erealloc: "); return m; } void * std_ealloc(struct memsys *mc, unsigned size) { void *m; assert(mc && size > 0); if ( !(m = malloc(size)) ) errsys("malloc: "); return m; } void * std_eresize(struct memsys *mc, void *old, unsigned newsize) { void *m; assert(mc && newsize >= 0); if ( !(m = realloc(old, newsize)) ) errsys("realloc: "); return m; } struct memsys estdmem = { std_ealloc, std_eresize, std_free, &xstdmem }; #include <cat/ex.h> const char *XMemErr = "Memory Error"; void *xmalloc(size_t size) { void *m; if ( !(m = malloc(size)) ) ex_throw((void *)XMemErr); return m; } void *xrealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) ) ex_throw((void *)XMemErr); return m; } void *std_xalloc(struct memsys *msys, unsigned size) { assert(msys); return xmalloc(size); } void *std_xresize(struct memsys *msys, void *old, unsigned size) { assert(msys); return xrealloc(old, size); } struct memsys xstdmem = { std_xalloc, std_xresize, std_free, &xstdmem }; #endif /* CAT_USE_STDLIB */
github188/catlib
include/cat/emit.h
/* * emit.h -- generic output stream API * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_emit_h #define __cat_emit_h #include <cat/cat.h> enum { EMIT_OK = 0, EMIT_EOS = 1, EMIT_ERR = -1 }; struct emitter; typedef int (*emit_f)(struct emitter *ectx, const void *buf, size_t len); struct emitter { int emit_state; emit_f emit_func; }; int emit_raw(struct emitter *em, const void *buf, size_t len); int emit_char(struct emitter *em, char ch); int emit_string(struct emitter *em, const char *s); /* A pseudo-emitter that just consumes characters */ extern struct emitter null_emitter; void null_emitter_init(struct emitter *em); /* String Emitter - emit to a fixed length string */ struct string_emitter { struct emitter se_emitter; struct raw se_raw; size_t se_fill; }; void string_emitter_init(struct string_emitter *se, char *buf, size_t len); void string_emitter_terminate(struct string_emitter *se); #endif /* __cat_emit_h */
github188/catlib
utils/netpipe.c
<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/net.h> #include <cat/uevent.h> #include <cat/io.h> #include <cat/err.h> #include <cat/ring.h> #include <cat/stduse.h> #include <limits.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int lfd, sfd, cfd, crdone = 0, srdone = 0, cwdone = 0, swdone = 0; unsigned bsiz = 4096; char *ourname; char *laddr = "0.0.0.0", *lport, *raddr, *rport; struct uemux mux; struct ring c2s, s2c; struct ue_ioevent c2sr, c2sw, s2cr, s2cw; int writer(void *arg, struct callback *cb); int reader(void *arg, struct callback *cb); int reader(void *arg, struct callback *cb) { struct ring *r = cb->ctx; struct ue_ioevent *io = (struct ue_ioevent *)cb; int fd = io->fd, rv; ulong last, toend, olen; last = ring_last(r); toend = r->alloc - last; if ( ring_avail(r) < toend ) toend = ring_avail(r); if ( toend > SSIZE_MAX ) toend = SSIZE_MAX; rv = io_read_upto(fd, r->data + last, toend); if ( rv < 0 ) { if ( rv == -2 ) return 0; errsys("input error: "); } else if ( rv == 0 ) { if ( fd == cfd ) crdone = 1; else srdone = 1; ue_io_cancel(io); } else { olen = r->len; ring_put(r, NULL, rv, 0); if ( !ring_avail(r) ) ue_io_cancel(io); if ( fd == cfd ) { if ( !olen && !swdone ) ue_io_reg(&mux, &c2sw); } else { if ( !olen && !cwdone ) ue_io_reg(&mux, &s2cw); } } return 0; } int writer(void *arg, struct callback *cb) { struct ring *r = cb->ctx; struct ue_ioevent *io = (struct ue_ioevent *)cb; int fd = io->fd, rv; ulong toend, oavail; toend = r->alloc - r->start; if ( r->len < toend ) toend = r->len; if ( toend > SSIZE_MAX ) toend = SSIZE_MAX; rv = io_write_upto(fd, r->data + r->start, toend); if ( rv < 0 ) { if ( rv == -2 ) return 0; errsys("input error: "); } else if ( rv == 0 ) { if ( fd == cfd ) cwdone = 1; else swdone = 1; ue_io_cancel(io); } else { oavail = ring_avail(r); ring_get(r, NULL, rv); if ( !r->len ) ue_io_cancel(io); if ( fd == cfd ) { if ( !oavail && !srdone ) ue_io_reg(&mux, &s2cr); } else { if ( !oavail && !crdone ) ue_io_reg(&mux, &c2sr); } } return 0; } void usage(char *str) { err("%s\n" "usage: %s [-b bufsize] [-l loc addr]\n" "\t<loc port> <rem addr> <rem port>\n", str, ourname); } void getopts(int argc, char *argv[]) { int c; if ( argc < 4 ) usage("too few arguments"); while ( (c = getopt(argc, argv, "b:l:")) >= 0 ) { switch(c) { case 'b': bsiz = atoi(optarg); break; case 'l': laddr = optarg; break; case '?': default: usage("Unknown option"); } } argc -= optind; argv += optind; lport = argv[0]; raddr = argv[1]; rport = argv[2]; } int main(int argc, char *argv[]) { struct sockaddr_storage ss; socklen_t alen = sizeof(ss); char *c2sbuf, *s2cbuf; ourname = argv[0]; getopts(argc, argv); printf("listening on %s:%s\n", laddr, lport); if ( (lfd = tcp_srv(laddr, lport)) < 0 ) err("Couldn't open server address to %s:%s", laddr, lport); if ( (sfd = accept(lfd, (struct sockaddr *)&ss, &alen)) < 0 ) errsys("Accepting: "); printf("Got Connection!\nConnecting to %s:%s\n", raddr, rport); if ( (cfd = tcp_cli(raddr, rport)) < 0 ) err("Couldn't open socket to %s:%s", raddr, rport); close(lfd); if ( io_setnblk(sfd) < 0 ) errsys("Couldn't set server to non-blocking mode"); if ( io_setnblk(cfd) < 0 ) errsys("Couldn't set client to non-blocking mode"); ue_init(&mux, &estdmm); c2sbuf = emalloc(bsiz); s2cbuf = emalloc(bsiz); ring_init(&c2s, c2sbuf, bsiz); ring_init(&s2c, s2cbuf, bsiz); ue_io_init(&c2sr, UE_RD, cfd, reader, &c2s); ue_io_init(&s2cr, UE_RD, sfd, reader, &s2c); ue_io_init(&c2sw, UE_WR, sfd, writer, &c2s); ue_io_init(&s2cw, UE_WR, cfd, writer, &s2c); ue_io_reg(&mux, &c2sr); ue_io_reg(&mux, &s2cr); ue_run(&mux); free(c2sbuf); free(s2cbuf); close(sfd); close(cfd); return 0; }
github188/catlib
include/cat/mem.h
<reponame>github188/catlib<filename>include/cat/mem.h /* * mem.h -- memory management API * * by <NAME> * * Copyright 2003-2017 -- See accompanying license * */ #ifndef __cat_mem_h #define __cat_mem_h #include <cat/cat.h> #include <cat/aux.h> struct memmgr; typedef void *(*alloc_f)(struct memmgr *mm, size_t size); typedef void *(*resize_f)(struct memmgr *mm, void *old, size_t size); typedef void (*free_f)(struct memmgr *mm, void * tofree); /* Base structure for a memory manager */ struct memmgr { alloc_f mm_alloc; resize_f mm_resize; free_f mm_free; void * mm_ctx; }; /* * Allocate 'len' bytes of memory from 'm'. Returns a pointer * to the allocated memory or NULL if no memory is available. */ void *mem_get(struct memmgr *m, size_t len); /* * Resize a block of memory 'mem' that 'm' allocated to length * 'len'. Returns a pointer to the new memory or NULL if there * was an error allocating it. If 'len' is 0, this is equivalent * to 'free(mem)' and returns NULL. If 'mem' is NULL, this is * equivalent to mem_get(m, len). */ void *mem_resize(struct memmgr *m, void *mem, size_t len); /* * Free a block of memory 'mem' allocated using 'm'. */ void mem_free(struct memmgr *m, void *mem); /* * This function is useful as an 'apply function' that gets * invoked over every element in some data structure. It frees * each element as it gets invoked. */ extern void applyfree(void *data, void *memmgr); /* * This is a memory manager that operates by allocating linearly from * some array. Freeing memory with this manager does not release it * for future use and resizing memory is unimplemented. */ struct arraymm { struct memmgr mm; byte_t * mem; size_t mlen; size_t fill; int alignp2; int hi2lo; }; /* * Initialize an array memory manager 'amm' to allocate memory out of 'mem' * linearly either front to back (hi2lo is 0) or back to front (if * hi2lo is 1). 'mlen' holds the length of 'mem'. The 'alg' parameter * specifies the minimum alignment that each the manager will round up * each allocation to. */ void amm_init(struct arraymm *amm, void *mem, size_t mlen, int algn, int hi2lo); /* * Reset an array memory manager as if it were freshly initialized. The * caller should not have any pointers to memory that 'amm' allocated * as this memory is all considered freed now and available for fresh * allocations. */ void amm_reset(struct arraymm *amm); /* Return the number of bytes that 'amm' has allocated so far. */ size_t amm_get_fill(struct arraymm *amm); /* Return the number of bytes that 'amm' has available for allocation. */ size_t amm_get_avail(struct arraymm *amm); /* Declaration of default memmgr. */ extern struct memmgr stdmm; #endif /* __cat_mem_h */
github188/catlib
utils/pegcc.c
<reponame>github188/catlib #include <string.h> #include <stdlib.h> #include <ctype.h> #include <cat/cat.h> #include <cat/emalloc.h> #include <cat/err.h> #include <cat/optparse.h> #include <cat/peg.h> #include <cat/cpg.h> #include <cat/str.h> #define NODE(_peg, _i) (&(_peg)->nodes[_i]) #define NODE_TYPE(_peg, _i) ((_peg)->nodes[_i].pn_type) #define NODE_ID(_peg, _pn) ((_pn) - ((_peg)->nodes)) #define HASCALLBACK(_pn) \ ((_pn)->pn_type == PEG_PRIMARY && \ ((_pn)->pp_action == PEG_ACT_CODE || \ (_pn)->pp_action == PEG_ACT_LABEL)) struct clopt options[] = { CLOPT_I_NOARG('h', NULL, "print help"), CLOPT_I_NOARG('H', NULL, "generate header file"), CLOPT_I_STRING('o', NULL, "outfn", "Output file name base (defaults \"cpeg\")"), CLOPT_I_STRING('d', NULL, "outdir", "Output directory (defaults to input base path)"), CLOPT_I_STRING('p', NULL, "prefix", "Output prefix filename (defaults to 'cpeg')"), CLOPT_I_NOARG('t', NULL, "Automatically generate tokens for uresolved IDs"), CLOPT_I_STRING('T', NULL, "tokpfx", "Token prefix (defaults to 'CPEGTOK_')"), }; struct clopt_parser oparse = CLOPTPARSER_INIT(options, array_length(options)); const char *progname; const char *in_fname; int has_dname_param = 0; int create_header = 0; char out_dname[256] = ""; char out_froot[256] = "cpeg"; char out_fname_c[256]; char out_fname_h[256]; char out_fbase_h[256]; const char *prefix = "cpeg"; const char *tokpfx = "CPEGTOK_"; FILE *infile; FILE *outfile_c; FILE *outfile_h; uint hlines; int parse_flags = 0; void usage(const char *estr) { char str[4096]; if ( estr != NULL ) fprintf(stderr, "%s\n", estr); optparse_print(&oparse, str, sizeof(str)); fprintf(stderr, "usage: %s [options] INFILE\n", progname); fprintf(stderr, "Options:\n%s\n", str); fprintf(stderr, "\nFile format is:\n" "\t<HEADER>\n" "\t%%%%\n" "\t<GRAMMAR>\n" "\t[%%%%\n" "\t<TRAILER>]\n" "\tThe header may not contain the string '%%%%\\n'\n" "\tThe trailer (including delimiter) is optional\n"); exit(1); } void build_filenames(void) { size_t size; char *s; if ( !has_dname_param ) { s = strrchr(in_fname, '/'); if ( s != NULL ) { size = s - in_fname + 1; if ( size >= sizeof(out_dname) - 1 ) err("Output path too long\n"); memcpy(out_dname, in_fname, size); out_dname[size] = '/'; out_dname[size + 1] = '\0'; } } size = sizeof(out_fname_c); if ( str_copy(out_fname_c, out_dname, size) >= size || str_cat(out_fname_c, out_froot, size) >= size || str_cat(out_fname_c, ".c", size) >= size ) err("Output filename too long\n"); size = sizeof(out_fbase_h); if ( str_copy(out_fbase_h, out_froot, size) >= size || str_cat(out_fbase_h, ".h", size) >= size ) err("Output filename too long\n"); size = sizeof(out_fname_h); if ( str_copy(out_fname_h, out_dname, size) >= size || str_cat(out_fname_h, out_fbase_h, size) >= size ) err("Output filename too long\n"); } void parse_args(int argc, char *argv[]) { int rv; struct clopt *opt; size_t n; infile = stdin; progname = argv[0]; optparse_reset(&oparse, argc, argv); while ( !(rv = optparse_next(&oparse, &opt)) ) { switch (opt->ch) { case 'd': has_dname_param = 1; n = str_copy(out_dname, opt->val.str_val, sizeof(out_dname)); if ( n >= sizeof(out_dname) - 1 ) err("output directory name too long\n"); out_dname[n] = '/'; out_dname[n + 1] = '\0'; break; case 'h': usage(NULL); break; case 'H': create_header = 1; break; case 'o': n = str_copy(out_froot, opt->val.str_val, sizeof(out_froot)); if ( n >= sizeof(out_froot) ) err("output file name too long\n"); break; case 'p': prefix = opt->val.str_val; if ( strlen(prefix) == 0 ) err("Empty parser prefix!"); break; case 't': parse_flags |= PEG_GEN_TOKENS; break; case 'T': tokpfx = opt->val.str_val; break; } } if ( rv != argc - 1 ) usage(oparse.errbuf); in_fname = argv[rv]; build_filenames(); infile = fopen(in_fname, "r"); if (infile == NULL) errsys("Error opening file %s: ", in_fname); outfile_c = fopen(out_fname_c, "w"); if (outfile_c == NULL) errsys("Error opening file %s: ", out_fname_c); if ( create_header ) { outfile_h = fopen(out_fname_h, "w"); if (outfile_h == NULL) errsys("Error opening file %s: ", out_fname_h); } } #define BUFINCR 4096 void read_file(FILE *fp, struct raw *r) { size_t n; size_t ss = 1; r->data = NULL; r->len = 0; do { ss += BUFINCR; r->data = erealloc(r->data, ss); n = fread(r->data + r->len, 1, BUFINCR, fp); if ( ferror(fp) ) errsys("error reading input file: "); r->len += n; } while ( n == BUFINCR ); r->data[r->len] = '\0'; r->len; } void parse_header(struct raw *fstr, struct raw *head, char **gstrp) { char *s, *lp; s = strstr(fstr->data, "%%\n"); if ( s == NULL ) err("Grammar file missing header delimiter '%%%%\\n'\n"); head->data = fstr->data; head->len = (byte_t *)s - fstr->data; s += 3; *gstrp = s; hlines = 0; for ( lp = strchr(fstr->data, '\n'); lp < s; lp = strchr(lp + 1, '\n') ) ++hlines; } void parse_grammar_and_tail(struct raw *fstr, char *start, struct peg_grammar_parser *pgp, struct peg_grammar *peg, struct raw *tail) { int rv; uint hdr_num_chars = (byte_t *)start - fstr->data; char ebuf[256]; rv = peg_parse(pgp, peg, start, fstr->len - hdr_num_chars, parse_flags); if ( rv < 0 ) { pgp->eloc.pos += hdr_num_chars; pgp->eloc.line += hlines; err("%s\n", peg_err_string(pgp, ebuf, sizeof(ebuf))); } tail->data = start + pgp->len; if ( tail->data[0] == '\0' ) { tail->len = 0; return; } else { if ( strncmp(tail->data, "%%\n", 3) != 0 ) err("Grammar did not end in %%%% on its own line.\n" "Successful parse only to line %u\n", hlines + pgp->nlines); tail->data += 3; tail->len = fstr->len - (tail->data - fstr->data); } } void emit_action(struct peg_grammar *peg, int nn) { struct peg_node *pn = NODE(peg, nn); if ( pn->pp_action == PEG_ACT_CODE ) { fprintf(outfile_c, "static int __%s_peg_action%d(int __%s_node, " "struct raw *%s_text, void *%s_ctx)\n" "{ int %s_error = 0;\n", prefix, nn, prefix, prefix, prefix, prefix); fprintf(outfile_c, "#line %u \"%s\"\n", pn->pn_line + hlines, in_fname); fwrite(pn->pp_code.data, 1, pn->pp_code.len, outfile_c); fprintf(outfile_c, "\nreturn %s_error; }\n", prefix); } else { /* forward declaration for callback */ abort_unless(pn->pp_action == PEG_ACT_LABEL); fprintf(outfile_c, "static int %s(int __%s_node, " "struct raw *%s_text, void *%s_ctx);\n", pn->pp_label.data, prefix, prefix, prefix); } } #define MUST_ESCAPE(_c) \ ((_c) == '"' || (_c) == '\\') void emit_initializer(struct peg_grammar *peg, int nn) { int i; int c; char buf[256] = ""; struct peg_node *pn = NODE(peg, nn); fprintf(outfile_c, "{ %d, {", pn->pn_type); if ( pn->pn_type == PEG_LITERAL || pn->pn_type == PEG_CLASS ) { fprintf(outfile_c, "%u, (byte_t *)\"", (uint)pn->pn_str.len); for ( i = 0; i < pn->pn_str.len; ++i ) { c = pn->pn_str.data[i]; if ( isprint(c) && !isspace(c) && !MUST_ESCAPE(c) ) fputc(c, outfile_c); else fprintf(outfile_c, "\\x%02x", c); } fprintf(outfile_c, "\"}, "); } else if ( HASCALLBACK(pn) ) { if ( pn->pp_action == PEG_ACT_CODE ) snprintf(buf, sizeof(buf), "__%s_peg_action%d", prefix, nn); else str_copy(buf, pn->pp_label.data, sizeof(buf)); fprintf(outfile_c, "%u, (byte_t *)\"%s\"}, ", (uint)strlen(buf), buf); } else { fprintf(outfile_c, "0, NULL}, "); } fprintf(outfile_c, "%d, %d, %d, ", pn->pn_next, pn->pn_subnode, pn->pn_line + hlines); if ( HASCALLBACK(pn) ) fprintf(outfile_c, "%d, %d, %d, &%s},\n", PEG_ACT_CALLBACK, pn->pn_flag1, pn->pn_flag2, buf); else fprintf(outfile_c, "%d, %d, %d, NULL},\n", pn->pn_status, pn->pn_flag1, pn->pn_flag2); } void emit_prolog(struct peg_grammar *peg) { int i; /* generate action routines */ for ( i = 0; i < peg->num_nodes; ++i ) if ( HASCALLBACK(NODE(peg, i)) ) emit_action(peg, i); /* generate static parsing array */ fprintf(outfile_c, "struct peg_node __%s_peg_nodes[%d] = {\n", prefix, peg->num_nodes); for ( i = 0; i < peg->num_nodes; ++i ) emit_initializer(peg, i); fprintf(outfile_c, "};\n" "static struct peg_grammar __%s_peg_grammar = {\n" "\t__%s_peg_nodes,\n" "\t%d,\n" "\t%d,\n" "\t%d,\n" "\t%d,\n" "\t0,\n" "};\n\n", prefix, prefix, peg->num_nodes, peg->num_nodes, peg->num_tokens, peg->start_node); } void emit_forward_defs(FILE *fp, struct peg_grammar *peg) { fprintf(fp, "struct %s_parser {\n" "\tstruct cpg_state pstate;\n" "};\n\n", prefix); fprintf(fp, "int %s_init(struct %s_parser *p, int (*getc)(void *));\n\n", prefix, prefix); fprintf(fp, "int %s_parse(struct %s_parser *p, void *in, void *aux);\n\n", prefix, prefix); fprintf(fp, "void %s_reset(struct %s_parser *p);\n\n", prefix, prefix); fprintf(fp, "void %s_fini(struct %s_parser *p);\n\n", prefix, prefix); if ( peg->num_tokens > 0 ) fprintf(fp, "const char *%s_tok_to_str(int id);\n\n", prefix); } int find_token(struct peg_grammar *peg, int idx) { int i; for ( i = 0; i < peg->num_nodes; ++i ) if ( peg->nodes[i].pn_type == PEG_IDENTIFIER && peg->nodes[i].pi_def == PEG_TOKEN_IDX(idx) ) return i; return -1; } void emit_parse_functions(struct peg_grammar *peg) { int i; int id; if ( !create_header ) emit_forward_defs(outfile_c, peg); fprintf(outfile_c, "static int __%s_getc(void *fp) { return fgetc(fp); }\n\n" "int %s_init(struct %s_parser *p, int (*getc)(void *)) {\n" " if (getc == NULL) getc = &__%s_getc;\n" " return cpg_init(&p->pstate, &__%s_peg_grammar, getc);\n" "}\n\n", prefix, prefix, prefix, prefix, prefix); fprintf(outfile_c, "int %s_parse(struct %s_parser *p, void *in, void *aux) {\n" " return cpg_parse(&p->pstate, in, aux);\n" "}\n\n", prefix, prefix); fprintf(outfile_c, "void %s_reset(struct %s_parser *p) {\n" " cpg_reset(&p->pstate);\n" "}\n\n", prefix, prefix); fprintf(outfile_c, "void %s_fini(struct %s_parser *p) {\n" " cpg_fini(&p->pstate);\n" "}\n\n", prefix, prefix); if ( peg->num_tokens > 0 ) { fprintf(outfile_c, "\nstatic char *tokstrs[] = {\n"); for ( i = 0; i < peg->num_tokens; ++i ) { id = find_token(peg, i); abort_unless(id >= 0); fprintf(outfile_c, "\"%s\",\n", NODE(peg, id)->pi_name.data); } fprintf(outfile_c, "NULL};\n\n"); fprintf(outfile_c, "const char *%s_tok_to_str(int id) {\n" " if ( id >= PEG_TOK_FIRST && id < PEG_TOK_FIRST + %d )\n" " return tokstrs[id - PEG_TOK_FIRST];\n" " else\n" " return \"unknown token\";\n" "}\n\n", prefix, peg->num_tokens); } } void generate_parser(struct raw *head, struct peg_grammar *peg, struct raw *tail) { uint tl = 1; uchar *lp; fprintf(outfile_c, "#include <cat/peg.h>\n" "#include <cat/cpg.h>\n" "#include <stdio.h>\n" "#include <string.h>\n"); if ( create_header ) fprintf(outfile_c, "#include \"%s\"\n", out_fbase_h); fprintf(outfile_c, "#line 0 \"%s\"\n", in_fname); fwrite(head->data, 1, head->len, outfile_c); emit_prolog(peg); emit_parse_functions(peg); if ( tail->len > 0 ) { for ( lp = strchr(head->data, '\n'); lp < tail->data; lp = strchr(lp + 1, '\n') ) tl++; fprintf(outfile_c, "#line %u \"%s\"\n", tl, in_fname); fwrite(tail->data, 1, tail->len, outfile_c); } fclose(outfile_c); } void emit_token_defs(FILE *fp, struct peg_grammar *peg) { int i; struct peg_node *pn; for ( i = 0; i < peg->num_nodes; ++i ) { pn = NODE(peg, i); if ( pn->pn_type != PEG_IDENTIFIER || !PEG_IDX_IS_TOKEN(peg, pn->pi_def) ) continue; fprintf(outfile_h, "#define %s%s %d\n", tokpfx, pn->pi_name.data, PEG_TOKEN_ID(pn->pi_def)); } } void generate_header(struct peg_grammar *peg) { fprintf(outfile_h, "#ifndef __%s_h\n", prefix); fprintf(outfile_h, "#define __%s_h\n\n", prefix); fprintf(outfile_h, "#include <cat/peg.h>\n" "#include <cat/cpg.h>\n\n"); emit_forward_defs(outfile_h, peg); emit_token_defs(outfile_h, peg); fprintf(outfile_h, "#endif /* __%s_h */\n", prefix); fclose(outfile_h); } int main(int argc, char *argv[]) { char *gstr; char *tstr; struct raw fstr; struct raw head; struct raw tail; struct peg_grammar_parser pgp; struct peg_grammar peg; parse_args(argc, argv); read_file(infile, &fstr); parse_header(&fstr, &head, &gstr); parse_grammar_and_tail(&fstr, gstr, &pgp, &peg, &tail); generate_parser(&head, &peg, &tail); if ( create_header ) generate_header(&peg); peg_free_nodes(&peg); return 0; }
github188/catlib
src/ring.c
<gh_stars>1-10 /* * ring.c -- Ring Buffer Implementation * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/ring.h> #include <string.h> #define CKRING(r) \ do { abort_unless(r); \ abort_unless(((r)->alloc > 0) && ((r)->start < (r)->alloc)); \ abort_unless((r)->len <= (r)->alloc); \ } while (0) void ring_init(struct ring *r, void *d, size_t l) { abort_unless(r); abort_unless(l); abort_unless(d); r->start = 0; r->len = 0; r->alloc = l; r->data = d; } void ring_reset(struct ring *r) { abort_unless(r); r->start = 0; r->len = 0; } size_t ring_put(struct ring *r, char *in, size_t len, int overwrite) { size_t last, toend, avail; CKRING(r); avail = ring_avail(r); if ( !overwrite && (len > avail) ) len = avail; if ( !in ) { abort_unless(len <= avail); r->len += len; return len; } if ( len > r->alloc ) { /* if the input is bigger than the buffer itself, just put in */ /* the last r->alloc-sized chunk of the input. Might as well */ /* align it while we're at it. */ abort_unless(overwrite); r->start = 0; r->len = r->alloc; memcpy(r->data, in + (len - r->alloc), r->alloc); return len; } last = ring_last(r); /* need to get last before possibly moving start */ if ( len > avail ) { /* We've got more than we have space for, but less than */ /* a buffer's worth. Some old data stays in the buffer. */ /* So adjust the start position accordingly */ size_t ovfl = len - avail; abort_unless(ovfl < r->len); if ( r->start < r->alloc - ovfl ) r->start += ovfl; else r->start = ovfl - (r->alloc - r->start); } toend = r->alloc - last; if ( (last >= r->start) && (toend < len) ) { memcpy(r->data + last, in, toend); memcpy(r->data, in + toend, len - toend); } else { memcpy(r->data + last, in, len); } if ( r->alloc - r->len < len ) r->len = r->alloc; else r->len += len; return len; } size_t ring_get(struct ring *r, char *out, size_t len) { size_t toend; CKRING(r); if ( len > r->len ) len = r->len; toend = r->alloc - r->start; if ( toend < len ) { if ( out ) { memcpy(out, r->data + r->start, toend); memcpy(out + toend, r->data, len - toend); } r->start = len - toend; r->len -= len; } else { if ( out ) memcpy(out, r->data + r->start, len); r->start += len; if ( r->start == r->alloc ) r->start = 0; r->len -= len; } /* Optimization: if ring is empty, then we can reset the start */ if ( r->len == 0 ) r->start = 0; return len; } size_t ring_last(struct ring *r) { size_t toend; CKRING(r); toend = r->alloc - r->start; if ( r->len < toend ) return r->start + r->len; else return r->len - toend; } #undef CKRING
github188/catlib
test/testuemux.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <sys/time.h> #include <cat/io.h> #include <cat/uevent.h> #include <cat/stduse.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <signal.h> struct ioctx { int infd; int outfd; int len; struct ue_ioevent *in; struct ue_ioevent *out; char buf[256]; }; int incb(void *arg, struct callback *cb) { struct ioctx *x; struct uemux *m; int n; x = cb->ctx; m = x->in->mux; n = io_read_upto(x->infd, x->buf, sizeof(x->buf)); if ( n == 0 ) { ue_io_del(x->in); ue_io_del(x->out); return 0; } else if ( n > 0 ) { x->len = n; ue_io_cancel(x->in); ue_io_reg(m, x->out); } else { errsys("reading data!\n"); } return 0; } int outcb(void *arg, struct callback *cb) { struct ioctx *x; struct uemux *m; int n; x = cb->ctx; m = x->out->mux; n = io_write_upto(x->outfd, x->buf, x->len); if ( n == 0 ) { ue_io_del(x->in); ue_io_del(x->out); return 0; } else if ( n > 0 ) { x->len -= n; if ( x->len ) memmove(x->buf, x->buf + n, x->len); else { ue_io_cancel(x->out); ue_io_reg(m, x->in); } } else { errsys("Error writing data"); } return 0; } int percb(void *arg, struct callback *cb) { printf("Periodic ping\n"); return 0; } int attimecb(void *arg, struct callback *cb) { printf("Attime ping\n"); return 0; } int alarmcb(void *arg, struct callback *cb) { printf("Alarm signal fired!\n"); return 0; } int main(int argc, char *argv[]) { struct uemux m; struct timeval tv; unsigned long n; struct ioctx x; ue_init(&m, &estdmm); ue_tm_new(&m, UE_PERIODIC, 2000, percb, NULL); ue_tm_new(&m, UE_TIMEOUT, 7000, attimecb, NULL); ue_sig_new(&m, SIGALRM, alarmcb, NULL); alarm(5); x.infd = 0; x.outfd = 1; x.in = ue_io_new(&m, UE_RD, 0, incb, &x); x.out = ue_io_new(&m, UE_WR, 1, outcb, &x); ue_io_cancel(x.out); ue_runfor(&m, 10000); return 0; }
github188/catlib
src/pool.c
/* * pool.c -- static data pool * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_POOL_DO_DECL #define CAT_USE_INLINE 0 #define CAT_POOL_DO_DECL 1 #include <cat/pool.h>
github188/catlib
include/cat/list.h
<filename>include/cat/list.h<gh_stars>1-10 /* * cat/list.h -- circular doubly linked list * * by <NAME> * * Copyright 2003-2017 -- See accompanying license * */ #ifndef __cat_list #define __cat_list #include <cat/cat.h> #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_LIST_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #endif /* CAT_USE_INLINE */ /* * This structure is both a list head/tail structure and nodes to * embed in other structures to put on a list. */ struct list { struct list *next; struct list *prev; }; /* Declare a list an initialize it as empty */ #define LIST_INITALIZER(name) { &(name), &(name) } #define LIST_DECLARE(name) struct list name = LIST_INITIALIZER(name); /* ----- Accessor macros ----- */ #define l_head(listp) (listp)->next #define l_tail(listp) (listp)->prev #define l_end(listp) (listp) #define l_next(entp) (entp)->next #define l_prev(entp) (entp)->prev /* ----- basic operations ----- */ /* Initialize a fresh list. */ DECL void l_init(struct list *list); /* * Insert an elem into a list after prev. Prev can be an element in the list * or the list head itself to insert at the beginning of the list. */ DECL void l_ins(struct list *prev, struct list *elem); /* Remove an element from its list */ DECL void l_rem(struct list *elem); /* Return a non-zero value if list is empty, otherwise return 0. */ DECL int l_isempty(struct list *list); /* Return a non-zero value if an element is on a list otherwise return 0. */ DECL int l_onlist(struct list *elem); /* Return the number of entries on a list. (by linear count) */ DECL ulong l_length(struct list *list); /* ----- Stack and queue functions ----- */ /* enqueue an element to the end of a list */ DECL void l_enq(struct list *list, struct list *elem); /* * Dequeue an element from the front of a list and return a pointer to it. * Return NULL if the list is empty. */ DECL struct list * l_deq(struct list *list); /* push an element to the front of a list */ DECL void l_push(struct list *list, struct list *elem); /* * Pop an element from the front of a list and return a pointer to it. * Return NULL if the list is empty. */ DECL struct list * l_pop(struct list *list); /* Apply 'f' to each element of a list passing 'arg' to 'f' as state */ DECL void l_apply(struct list *list, apply_f f, void *arg); /* ----- Functions to move whole chunks from one list to another ----- */ /* * Move the elements of 'src' to 'dst'. dst must start empty and src will * be empty after the operation. */ DECL void l_move(struct list *dst, struct list *src); /* * Move the nodes in a list from first to last into a new list dst. dst * must be initially empty. There is no way to specify to cut an empty * list other than to not call the function. */ DECL void l_cut(struct list *dst, struct list *first, struct list *last); /* * Append the elements of list2 to list1. list2 will be empty after * the operation. */ DECL void l_append(struct list *list1, struct list *list2); /* * Insert the elements of list2 into a given list after prev which * like l_ins() may be an element in the list or the list head to * splice the contents to the beginning of the list. list2 will be * empty after the operation. */ DECL void l_splice(struct list *prev, struct list *list2); /* ----- merge sort ----- */ /* * Merge the sorted list1 and list2 elements into list1 in sorted order. * Use cmp to compare two elements for sorting. As always, cmp(x,y) must * return (< 0) if x < y, (== 0) if x == y or (> 0) if x > y. */ DECL void l_merge(struct list *list1, struct list *list2, cmp_f cmp); /* * Run merge sort to sort a list of elements. cmp must behave as specified * in l_merge() above. */ DECL void l_sort(struct list *list, cmp_f cmp); /* * Return the next object in a list of objects with a list node where: * - ptr is the pointer to the current object * - type is the type of the object * - member is the name of the member of type that is a list node */ #define l_next_obj(ptr, type, member) \ container((ptr)->member.next, type, member) /* * Return the previous object in a list of objects with a list node where: * - ptr is the pointer to the current object * - type is the type of the object * - member is the name of the member of type that is a list node */ #define l_prev_obj(ptr, type, member) \ container((ptr)->member.prev, type, member) /* * Iterate forwards over a list setting node to each one in turn. */ #define l_for_each(node, list) \ for ( (node) = l_head(list) ; (node) != l_end(list) ; \ (node) = (node)->next ) /* * Iterate forwards over each node in a list, but use an xtra to hold * list position in case the list gets altered during a list iteration. */ #define l_for_each_safe(node, xtra, list) \ for ( (node) = l_head(list) ; \ (xtra) = (node)->next, (node) != l_end(list) ; \ (node) = (xtra) ) /* * Iterate backwards over a list setting node to each one in turn. */ #define l_for_each_rev(node, list) \ for ( (node) = l_tail(list) ; (node) != l_end(list) ; \ (node) = (node)->prev ) /* * Iterate backwards over each node in a list, but use an xtra to hold * list position in case the list gets altered during a list iteration. */ #define l_for_each_rev_safe(node, xtra, list) \ for ( (node) = l_tail(list) ; \ (xtra) = (node)->prev, (node) != l_end(list) ; \ (node) = (xtra) ) /* ----- Implementation ----- */ #if defined(CAT_LIST_DO_DECL) && CAT_LIST_DO_DECL DECL void l_init(struct list *head) { abort_unless(head); head->next = head->prev = head; } DECL void l_ins(struct list *prev, struct list *elem) { register struct list *next; abort_unless(prev); abort_unless(elem); abort_unless(prev->next && prev->next->prev == prev); next = prev->next; elem->next = next; elem->prev = prev; prev->next = elem; next->prev = elem; } DECL void l_rem(struct list *elem) { register struct list *next, *prev; abort_unless(elem); next = elem->next; prev = elem->prev; abort_unless(next && next->prev == elem); abort_unless(prev && prev->next == elem); prev->next = next; next->prev = prev; elem->next = elem; elem->prev = elem; } DECL void l_enq(struct list *list, struct list *elem) { l_ins(list->prev, elem); } DECL struct list * l_deq(struct list *list) { register struct list *last; abort_unless(list); last = list->next; if ( last != list ) { l_rem(last); return last; } else { return NULL; } } DECL void l_push(struct list *list, struct list *elem) { l_ins(list, elem); } DECL struct list *l_pop(struct list *list) { struct list * first; abort_unless(list); first = list->next; if ( first == list ) return NULL; l_rem(first); return first; } DECL int l_isempty(struct list *list) { abort_unless(list); return (list->next == list); } DECL int l_onlist(struct list *list) { abort_unless(list); return (list->next != list); } DECL ulong l_length(struct list *list) { struct list *t; unsigned long n = 0; abort_unless(list && list->next); for ( t = list->next ; t != list ; t = t->next ) ++n; return n; } DECL void l_apply(struct list *list, apply_f f, void *arg) { struct list *t, *next; abort_unless(list); abort_unless(f); for ( t = list->next ; t != list ; t = next ) { next = t->next; f(t, arg); } } DECL void l_move(struct list *dst, struct list *src) { abort_unless(dst); abort_unless(src); dst->next = src->next; dst->prev = src->prev; src->next->prev = dst; src->prev->next = dst; src->next = src->prev = src; } DECL void l_cut(struct list *dst, struct list *first, struct list *last) { struct list *prev, *after; abort_unless(first); abort_unless(last); abort_unless(dst && l_isempty(dst)); prev = first->prev; after = last->next; dst->next = first; dst->prev = last; first->prev = dst; last->next = dst; prev->next = after; after->prev = prev; } DECL void l_append(struct list *list1, struct list *list2) { abort_unless(list1); l_splice(l_tail(list1), list2); } DECL void l_splice(struct list *prev, struct list *list2) { struct list *after, *l2s, *l2e; abort_unless(list2); abort_unless(prev); if ( l_isempty(list2) ) return; after = prev->next; l2s = list2->next; l2e = list2->prev; l2s->prev = prev; prev->next = l2s; l2e->next = after; after->prev = l2e; list2->next = list2->prev = list2; } DECL void l_merge(struct list *l1, struct list *l2, cmp_f cmp) { struct list mlist, *t, *rest; l_init(&mlist); while ( !l_isempty(l1) && !l_isempty(l2) ) { if ( (*cmp)(l_head(l1), l_head(l2)) < 0 ) t = l_head(l1); else t = l_head(l2); l_rem(t); l_ins(l_tail(&mlist), t); } rest = l_isempty(l1) ? l2 : l1; while ( !l_isempty(rest) ) { t = l_head(rest); l_rem(t); l_ins(l_tail(&mlist), t); } l_move(l1, &mlist); } /* non-recursive merge sort implementation */ DECL void l_sort(struct list *l, cmp_f cmp) { /* Make this the log base-2 of the largest list we expect to sort */ struct list arr[48]; struct list *node; int i, wasempty = 0, last_non_empty = 0; abort_unless(l); abort_unless(cmp); for ( i = 0; i < array_length(arr); ++i ) l_init(&arr[i]); while ( !l_isempty(l) ) { l_rem(node = l_head(l)); wasempty = l_isempty(&arr[0]); if ( wasempty ) { l_ins(&arr[0], node); } else { if ( (*cmp)(node, l_head(&arr[0])) < 0 ) l_ins(&arr[0], node); else l_ins(l_head(&arr[0]), node); } for ( i = 1 ; i < array_length(arr) && !wasempty ; ++i ) { wasempty = l_isempty(&arr[i]); if ( wasempty ) { l_move(&arr[i], &arr[i-1]); } else { l_merge(&arr[i], &arr[i-1], cmp); } } } for ( i = 1 ; i < array_length(arr); ++i ) { if ( !l_isempty(&arr[i]) ) { l_merge(&arr[i], &arr[last_non_empty], cmp); last_non_empty = i; } } l_move(l, &arr[last_non_empty]); } #endif /* CAT_LIST_DO_DECL */ #undef DECL #undef CAT_LIST_DO_DECL #endif /* __cat_list */
github188/catlib
include/cat/stduse.h
<gh_stars>1-10 /* * stduse.h -- application level nicities built on the rest of the catlib * * by <NAME> * * Copyright 2007-2015 -- See accompanying license * */ #ifndef __cat_stduse_h #define __cat_stduse_h #include <cat/cat.h> #include <cat/emalloc.h> #include <cat/err.h> /* Memory manager extras */ #include <cat/mem.h> extern struct memmgr estdmm; struct raw *erawdup(struct raw const * const r); char *erawsdup(struct raw const * const r); #define DECLARE_BINARY_CMPF(_fn, _t) \ static int _fn(const void *a, const void *b) {return memcmp(a, b, sizeof(_t));} /* Application level list data structure */ #include <cat/list.h> struct clist_node { struct list entry; struct clist * list; void * data; }; struct clist_attr { struct clist_node * (*node_alloc)(struct clist *list); void (*node_free)(struct clist *list, struct clist_node *node); attrib_t ctx; }; struct clist { struct clist_node base; size_t fill; int abort_on_fail; struct clist_node * (*node_alloc)(struct clist *list); void (*node_free)(struct clist *list, struct clist_node *node); attrib_t ctx; }; #define l_to_cln(ln) container(ln, struct clist_node, entry) #define cl_next(clnp) l_to_cln((clnp)->entry.next) #define cl_prev(clnp) l_to_cln((clnp)->entry.prev) #define cl_head(clp) (&(clp)->base) #define cl_end(clp) (&(clp)->base) #define cl_first(clp) l_to_cln((clp)->base.entry.next) #define cl_last(clp) l_to_cln((clp)->base.entry.prev) #define cl_for_each(node, list) \ for ( (node) = cl_head(list) ; \ (node) != cl_end(list) ; \ (node) = cl_next(node) ) struct clist *cl_new(const struct clist_attr *attr, int abort_on_fail); void cl_free(struct clist *list); int cl_isempty(struct clist *list); size_t cl_fill(struct clist *list); int cl_ins(struct clist *list, struct clist_node *prev, void *val); void * cl_del(struct clist *list, struct clist_node *node); int cl_enq(struct clist *list, void *val); void * cl_deq(struct clist *list); int cl_push(struct clist *list, void *val); void * cl_pop(struct clist *list); void * cl_top(struct clist *list); void cl_apply(struct clist *list, apply_f f, void *arg); #include <cat/str.h> char * str_copy_a(const char *src); char * str_cat_a(const char *first, const char *second); char * str_fmt_a(const char *fmt, ...); char * str_vfmt_a(const char *fmt, va_list ap); char * str_tok_a(char **start, const char *wschars); #include <cat/dlist.h> struct cdlist { struct dlist entry; void * data; }; void * cdl_data(struct dlist *node); void cdl_set(struct dlist *node, void *data); struct dlist * cdl_new(cat_time_t t, void *data); void * cdl_free(struct dlist *node); /* Application layer hash table functions */ #include <cat/hash.h> struct chnode { struct hnode node; void * data; }; #define cht_data(_n) (container((_n), struct chnode, node)->data) struct chtab; struct chtab_attr { cmp_f kcmp; hash_f hash; size_t hctx_size; struct chnode * (*node_alloc)(struct chtab *, void *k); void (*node_free)(struct chtab *, struct chnode *); void * ctx; }; struct chtab { struct htab table; int abort_on_fail; struct chnode * (*node_alloc)(struct chtab *t, void *k); void (*node_free)(struct chtab *t, struct chnode *n); void * ctx; }; extern struct chtab_attr cht_std_attr_skey; /* string key table */ extern struct chtab_attr cht_std_attr_rkey; /* raw key table */ extern struct chtab_attr cht_std_attr_pkey; /* ptr key table */ extern struct chtab_attr cht_std_attr_bkey; /* binary key table */ struct chtab * cht_new(size_t nbkts, struct chtab_attr *attr, void *hctx, int abort_on_fail); void cht_free(struct chtab *t); void * cht_get(struct chtab *t, void *key); int cht_put(struct chtab *t, void *key, void *data); void * cht_del(struct chtab *t, void *key); void cht_apply(struct chtab *t, apply_f f, void *ctx); #include <cat/avl.h> struct canode { struct anode node; void * data; }; #define cavl_data(_n) (container((_n), struct canode, node)->data) struct cavltree; struct cavltree_attr { cmp_f kcmp; struct canode * (*node_alloc)(struct cavltree *t, void *k); void (*node_free)(struct cavltree *t, struct canode *n); void * ctx; }; struct cavltree { struct avltree tree; int abort_on_fail; struct canode * (*node_alloc)(struct cavltree *t, void *k); void (*node_free)(struct cavltree *t, struct canode *n); void * ctx; }; extern struct cavltree_attr cavl_std_attr_skey; /* string key table */ extern struct cavltree_attr cavl_std_attr_rkey; /* raw key table */ extern struct cavltree_attr cavl_std_attr_pkey; /* ptr key table */ extern struct cavltree_attr cavl_std_attr_bkey; /* binary key table */ struct cavltree * cavl_new(struct cavltree_attr *attr, int abort_on_fail); void cavl_free(struct cavltree *t); void * cavl_get(struct cavltree *t, void *key); int cavl_put(struct cavltree *t, void *key, void *data); void * cavl_del(struct cavltree *t, void *key); void cavl_apply(struct cavltree *t, apply_f f, void *ctx); #include <cat/rbtree.h> struct crbnode { struct rbnode node; void * data; }; #define crb_data(_n) (container((_n), struct crbnode, node)->data) struct crbtree; struct crbtree_attr { cmp_f kcmp; struct crbnode *(*node_alloc)(struct crbtree *t, void *k); void (*node_free)(struct crbtree *t, struct crbnode *n); void * ctx; }; struct crbtree { struct rbtree tree; int abort_on_fail; struct crbnode *(*node_alloc)(struct crbtree *t, void *k); void (*node_free)(struct crbtree *t, struct crbnode *n); void * ctx; }; extern struct crbtree_attr crb_std_attr_skey; /* string key table */ extern struct crbtree_attr crb_std_attr_rkey; /* raw key table */ extern struct crbtree_attr crb_std_attr_pkey; /* ptr key table */ extern struct crbtree_attr crb_std_attr_bkey; /* binary key table */ struct crbtree *crb_new(struct crbtree_attr *attr, int abort_on_fail); void crb_free(struct crbtree *t); void * crb_get(struct crbtree *t, void *key); int crb_put(struct crbtree *t, void *key, void *data); void * crb_del(struct crbtree *t, void *key); void crb_apply(struct crbtree *t, apply_f f, void *ctx); #include <cat/splay.h> struct cstnode { struct stnode node; void * data; }; #define cst_data(_n) (container((_n), struct cstnode, node)->data) struct cstree; struct cstree_attr { cmp_f kcmp; struct cstnode *(*node_alloc)(struct cstree *t, void *k); void (*node_free)(struct cstree *t, struct cstnode *n); void * ctx; }; struct cstree { struct sptree tree; int abort_on_fail; struct cstnode *(*node_alloc)(struct cstree *t, void *k); void (*node_free)(struct cstree *t, struct cstnode *n); void * ctx; }; extern struct cstree_attr cst_std_attr_skey; /* string key table */ extern struct cstree_attr cst_std_attr_rkey; /* raw key table */ extern struct cstree_attr cst_std_attr_pkey; /* ptr key table */ extern struct cstree_attr cst_std_attr_bkey; /* binary key table */ struct cstree * cst_new(struct cstree_attr *attr, int abort_on_fail); void cst_free(struct cstree *t); void * cst_get(struct cstree *t, void *key); int cst_put(struct cstree *t, void *key, void *data); void * cst_del(struct cstree *t, void *key); void cst_apply(struct cstree *t, apply_f f, void *ctx); #include <cat/heap.h> struct heap * hp_new(size_t size, cmp_f cmp); void hp_free(struct heap *hp); #include <cat/ring.h> char * ring_alloc(struct ring *r, size_t len); int ring_fmt(struct ring *r, const char *fmt, ...); #include <cat/match.h> struct std_kmppat { struct kmppat pattern; struct memmgr * mm; }; struct kmppat * kmp_pnew(struct memmgr *mm, struct raw *pat); void kmp_free(struct kmppat *kmp); struct std_bmpat { struct bmpat pattern; struct memmgr * mm; }; struct bmpat * bm_pnew(struct memmgr *mm, struct raw *pat); void bm_free(struct bmpat *bmp); struct sfxtree * sfx_new(struct memmgr *mm, struct raw *pat); void sfx_free(struct sfxtree *sfx); #include <cat/bitset.h> struct safebitset { uint nbits; uint len; bitset_t * set; struct memmgr * mm; }; struct safebitset *sbs_new(struct memmgr *mm, uint nbits); void sbs_free(struct safebitset *set); void sbs_zero(struct safebitset *set); void sbs_fill(struct safebitset *set); uint sbs_copy(struct safebitset *dst, struct safebitset *src); int sbs_test(struct safebitset *set, uint index); void sbs_set(struct safebitset *set, uint index); void sbs_clr(struct safebitset *set, uint index); void sbs_flip(struct safebitset *set, uint index); void sbs_set_to(struct safebitset *set, uint index, int val); #endif /* __cat_stduse_h */
github188/catlib
src/match.c
/* * match.c -- Routines to do fast string matching. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/match.h> #include <stdlib.h> #include <string.h> #include <ctype.h> void kmp_pinit(struct kmppat *kmp, struct raw *pat, ulong *skips) { ulong q, k, len; uchar *pp; abort_unless(kmp); abort_unless(pat && pat->data); abort_unless(skips); kmp->pat = *pat; kmp->skips = skips; len = pat->len; pp = (uchar *)pat->data; skips[0] = 0; k = 0; for ( q = 1 ; q < len ; ++q ) { while ( k > 0 && pp[k] != pp[q] ) k = skips[k-1]; if ( pp[k] == pp[q] ) ++k; skips[q] = k; } } int kmp_match(const struct raw *str, struct kmppat *pat, ulong *loc) { const char *sp, *pp; ulong slen, plen, q, i; abort_unless(str && str->data); abort_unless(pat && pat->skips && pat->pat.data); sp = str->data; slen = str->len; pp = pat->pat.data; plen = pat->pat.len; for ( i = 0, q = 0 ; i < slen ; ++i ) { while ( q > 0 && pp[q] != sp[i] ) q = pat->skips[q-1]; if ( pp[q] == sp[i] ) ++q; if ( q == plen ) { if ( loc ) *loc = i - plen + 1; return 1; } } return 0; } void bm_pinit(struct bmpat *bmp, struct raw *pat, ulong *skips, ulong *scratch) { ulong i, j, len; byte_t *pp; abort_unless(bmp); abort_unless(pat); abort_unless(skips); abort_unless(pat->len <= ((ulong)~0 - 1)); bmp->pat = *pat; bmp->skips = skips; len = pat->len; pp = pat->data; if ( len == 0 ) return; for ( i = 0 ; i < 256 ; ++i ) bmp->last[i] = 0; for ( i = 0 ; i < len ; ++i ) bmp->last[pp[i]] = i + 1; for ( i = 0 ; i < len ; ++i ) skips[i] = 0; i = len; j = len - 1; do { scratch[j] = i + 1; while ( (i < len) && (pp[i] != pp[j]) ) { if ( skips[i] == 0 ) skips[i] = i - j; i = scratch[i] - 1; } --i; } while ( j-- > 0 ); for ( j = 0 ; j < len ; ++j ) { if ( skips[j] == 0 ) skips[j] = i+1; if ( i == j ) i = scratch[j] - 1; } } void bm_pinit_lite(struct bmpat *bmp, struct raw *pat) { ulong i, len; byte_t *pp; abort_unless(bmp); abort_unless(pat); abort_unless(pat->len <= ((ulong)~0 - 1)); bmp->pat = *pat; bmp->skips = NULL; len = pat->len; pp = pat->data; if ( len == 0 ) return; for ( i = 0 ; i < 256 ; ++i ) bmp->last[i] = 0; for ( i = 0 ; i < len ; ++i ) bmp->last[pp[i]] = i + 1; } int bm_match(struct raw *str, struct bmpat *pat, ulong *loc) { ulong i, j, slen, plen, skip; uchar *pp, *sp; abort_unless(str && str->data); abort_unless(pat && pat->skips && pat->pat.data); pp = (uchar *)pat->pat.data; plen = pat->pat.len; sp = (uchar *)str->data; slen = str->len; i = 0; while ( i <= slen - plen ) { j = plen; while ( j > 0 && pp[j-1] == sp[i+j-1] ) --j; if ( j == 0 ) { if ( loc ) *loc = i; return 1; } else { skip = pat->last[sp[i+j-1]]; if ( skip < j ) skip = j - skip; else skip = 1; if ( (pat->skips != NULL) && (skip < pat->skips[j-1]) ) skip = pat->skips[j-1]; i += skip; } } return 0; } #define isexplicit(suffix) ( (suffix)->end < (suffix)->start ) static int edgecmp(const void *c1, const void *c2) { int rv; const struct sfxedgekey *ek1 = c1; const struct sfxedgekey *ek2 = c2; if ( !(rv = (int)(ek1->node - ek2->node)) ) rv = ek1->character - ek2->character; return rv; } static unsigned edgehash(const void *key, void *notused) { struct sfxedgekey const *ek = key; return ((ulong)ek->node * 257) + ek->character; } static struct hnode *newedge(struct sfxedgekey *ek, struct memmgr *mm) { struct sfxedge *edge; struct sfxedgekey *nk; edge = mem_get(mm, sizeof(struct sfxedge) + sizeof(struct sfxedgekey)); nk = (struct sfxedgekey *)(edge + 1); memset(nk, 0, sizeof(*nk)); nk->node = ek->node; nk->character = ek->character; ht_ninit(&edge->hentry, nk); edge->node = NULL; return &edge->hentry; } /* if *create == 0, do not create the node. If *create != 0 then *create */ /* returns 0 if the node was already there or 1 if the node was created */ static struct sfxedge *getedge(struct sfxtree *t, struct sfxnode *par, int ch, int *create) { struct sfxedgekey ek; struct hnode *node; struct htab *ht = &t->edges; unsigned hash; ek.node = par; ek.character = ch; if ( !(node = ht_lkup(ht, &ek, &hash)) ) { if ( !*create ) return NULL; if ( !(node = newedge(&ek, t->mm)) ) { *create = 0; return NULL; } *create = 1; ht_ins(ht, node, hash); } else { *create = 0; } return (struct sfxedge *)node; } static struct sfxnode *newnode(struct sfxtree *sfx) { struct sfxnode *node; if ( !(node = mem_get(sfx->mm, sizeof(*node))) ) return NULL; node->sptr = NULL; return node; } static struct sfxnode *split(struct sfxtree *sfx, struct sfxedge *edge, long off, long index) { int create; struct sfxedge *e1, *e2; struct sfxnode *newint, *newleaf; uchar *text = (uchar *)sfx->str.data; if ( !(newint = newnode(sfx)) ) return NULL; create = 1; if ( !(e1 = getedge(sfx, newint, text[edge->start + off], &create)) ) { mem_free(sfx->mm, newint); return NULL; } newint->sptr = ((struct sfxedgekey *)edge->hentry.key)->node; abort_unless(create); e1->node = edge->node; edge->node = newint; e1->start = edge->start + off; e1->end = edge->end; edge->end = edge->start + off - 1; create = 1; if ( !(e2 = getedge(sfx, newint, text[index], &create)) ) return NULL; abort_unless(create); if ( !(newleaf = newnode(sfx)) ) return NULL; e2->start = index; e2->end = sfx->str.len - 1; e2->node = newleaf; return newint; } static void canonical(struct sfxtree *t, struct suffix *s) { long span; uchar *text; struct sfxedge *edge; int no = 0; text = (uchar *)t->str.data; if ( !isexplicit(s) ) { edge = getedge(t, s->node, text[s->start], &no); abort_unless(edge); span = edge->end - edge->start + 1; while ( span <= s->end - s->start + 1 ) { s->start += span; s->node = edge->node; if ( s->start <= s->end ) { edge = getedge(t, s->node, text[s->start], &no); span = edge->end - edge->start + 1; } } } } static int sfx_build(struct sfxtree *sfx) { long i, span; struct suffix active; struct sfxnode *lastpar, *cur; uchar *text; struct sfxedge *edge; int create; active.node = &sfx->root; active.start = 0; active.end = -1; text = (uchar *)sfx->str.data; for ( i = 0 ; i < sfx->str.len ; ++i ) { lastpar = NULL; while (1) { cur = active.node; if ( isexplicit(&active) ) { create = 1; edge = getedge(sfx, cur, text[i], &create); if ( !edge ) return -1; if ( !create ) break; if ( !(edge->node = newnode(sfx)) ) return -1; edge->start = i; edge->end = sfx->str.len - 1; } else { create = 0; edge = getedge(sfx, cur, text[active.start], &create); abort_unless(edge); span = active.end - active.start + 1; abort_unless(edge->end - edge->start+1 > span); if ( text[edge->start + span] == text[i] ) break; if ( !(cur = split(sfx, edge, span, i)) ) return -1; } if ( lastpar && (lastpar != &sfx->root) ) lastpar->sptr = cur; lastpar = cur; if ( active.node == &sfx->root ) ++active.start; else active.node = active.node->sptr; canonical(sfx, &active); } if ( lastpar && (lastpar != &sfx->root) ) lastpar->sptr = cur; ++active.end; canonical(sfx, &active); } return 0; } int sfx_init(struct sfxtree *sfx, struct raw *str, struct memmgr *mm) { struct hnode **buckets; struct sfxnode *root; abort_unless(sfx); abort_unless(str && str->data); abort_unless(str->len <= CAT_SFX_MAXLEN); sfx->mm = mm; sfx->str = *str; /* XXX fix size? */ if ( ((size_t)~0) / sizeof(struct hnode *) < str->len ) return -1; if ( !(buckets = mem_get(mm, sizeof(struct hnode *) * str->len)) ) return -1; ht_init(&sfx->edges, buckets, str->len, edgecmp, edgehash, NULL); root = &sfx->root; root->sptr = NULL; if ( sfx_build(sfx) < 0 ) { sfx_clear(sfx); return -1; } return 0; } int sfx_match(struct sfxtree *sfx, struct raw *pat, ulong *loc) { struct sfxnode *cur; struct sfxedge *edge = NULL, *lastedge = NULL; uchar *cp, *end; long len; int nocre = 0; abort_unless(sfx); abort_unless(pat && pat->data); abort_unless(pat->len <= CAT_SFX_MAXLEN); len = 0; cur = &sfx->root; end = (uchar *)pat->data + pat->len; cp = (uchar *)pat->data; while ( (cp < end) && ((edge = getedge(sfx, cur, *cp, &nocre)) != NULL) ) { lastedge = edge; len = edge->end - edge->start + 1; if ( end - cp < len ) len = end - cp; abort_unless(len >= 1); if ( memcmp(sfx->str.data + edge->start, cp, len) ) return 0; cp += len; cur = edge->node; } if ( cp != end ) return 0; if ( loc ) { if ( !lastedge ) *loc = 0; else { *loc = edge->start + len - pat->len; abort_unless((long)*loc >= 0); } } return 1; } static void ap_edgefree(void *data, void *ctx) { struct sfxedge *edge = container(data, struct sfxedge, hentry); struct sfxtree *t = ctx; ht_rem(&edge->hentry); if ( edge->node != NULL ) mem_free(t->mm, edge->node); mem_free(t->mm, edge); } void sfx_clear(struct sfxtree *sfx) { ht_apply(&sfx->edges, ap_edgefree, sfx); mem_free(sfx->mm, sfx->edges.bkts); } struct rex_parse_aux { struct memmgr *mm; struct rex_group *initial; struct rex_group *final; uchar *start; uchar *end; struct rex_group *gstack; struct rex_choice *lastch; int *eptr; int gnum; }; static int rex_parse(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux); static int rex_parse_error(struct rex_node **rxnn, struct rex_parse_aux *aux, uchar *p) { *rxnn = NULL; if ( aux->eptr ) { if ( p ) *aux->eptr = p - aux->start; else *aux->eptr = -1; } return -1; } #define INTERNAL_WILDCARD 256 static int parse_bound(uchar **p) { int v = 0; uchar *dp = *p; while ( isdigit(*dp) ) { v = v * 10 + (*dp - '0'); ++dp; } if ( dp == *p ) return INTERNAL_WILDCARD; if ( v < 0 || v > 255 ) return -1; *p = dp; return v; } static int rex_check_repitions(struct rex_node *rxn, uchar **pp, struct rex_parse_aux *aux) { uchar *p = *pp; if ( p == aux->end ) return 0; if ( *p == '?' ) { rxn->repmin = 0; rxn->repmax = 1; *pp = p + 1; } else if ( *p == '*' ) { rxn->repmin = 0; rxn->repmax = REX_WILDCARD; *pp = p + 1; } else if ( *p == '+' ) { rxn->repmin = 1; rxn->repmax = REX_WILDCARD; *pp = p + 1; } else if ( *p == '{' ) { int v; ++p; v = parse_bound(&p); if ( v < 0 ) return rex_parse_error(&rxn->next, aux, p); rxn->repmin = (v == INTERNAL_WILDCARD) ? 0 : v; if ( *p != ',' ) { if ( *p != '}' || v < 1 ) return rex_parse_error(&rxn->next, aux, p); rxn->repmax = v; *pp = p + 1; return 0; } ++p; v = parse_bound(&p); if ( v < 1 ) return rex_parse_error(&rxn->next, aux, p); rxn->repmax = (v == INTERNAL_WILDCARD) ? REX_WILDCARD : v; if ( rxn->repmin > rxn->repmax && rxn->repmax != REX_WILDCARD ) return rex_parse_error(&rxn->next, aux, *pp); if ( *p != '}' ) return rex_parse_error(&rxn->next, aux, p); *pp = p + 1; } return 0; } /* TODO: let's optimize this */ static int span_regular(uchar *p, unsigned max) { static const char *special = "*[](){}+?|.\\$^"; uchar *t = p; retry_null: while ( max > 0 && !strchr(special, *t) ) { --max; ++t; } if ( (max > 0) && (*t == '\0') ) { --max; ++t; goto retry_null; } return t - p; } static int rex_parse_str(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { int rv, len = 0, maxlen = aux->end - p, span; struct rex_node_str *rs; uchar *s, *op; if ( !(rs = mem_get(aux->mm, sizeof(*rs))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = (struct rex_node *)rs; rs->base.type = REX_T_STRING; rs->base.repmin = rs->base.repmax = 1; rs->base.next = NULL; rxnn = &rs->base.next; s = rs->str; if ( maxlen > sizeof(rs->str) ) maxlen = sizeof(rs->str); do { span = span_regular(p, maxlen); memcpy(s, p, span); s += span; p += span; maxlen -= span; len += span; if ( span == 0 ) { if ( *p != '\\' ) break; if ( maxlen < 2 ) return rex_parse_error(rxnn, aux, p); *s++ = *(p + 1); p += 2; --maxlen; ++len; } } while ( maxlen > 0 ); rs->len = len; op = p; if ( (rv = rex_check_repitions(&rs->base, &p, aux)) < 0 ) return rv; if ( p != op ) { if ( rs->len > 1 ) { struct rex_node_str *rs2; if ( !(rs2 = mem_get(aux->mm, sizeof(*rs2))) ) return rex_parse_error(rxnn, aux, NULL); rs->len -= 1; *rxnn = (struct rex_node *)rs2; rs2->base.type = REX_T_STRING; rs2->base.repmin = rs->base.repmin; rs2->base.repmax = rs->base.repmax; rs2->base.next = NULL; rs2->len = 1; rxnn = &rs2->base.next; rs->base.repmin = rs->base.repmax = 1; } } return rex_parse(rxnn, p, aux); } static int rex_parse_class(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { uchar *start = p + 1, *end = start; int invert = 0, i, rv; struct rex_ascii_class *rxc; /* handle the special cases for the first character */ if ( end == aux->end ) { return rex_parse_error(rxnn, aux, p - 1); } if ( *end == '^' ) { ++invert; ++end; ++start; } if ( end == aux->end ) { return rex_parse_error(rxnn, aux, p - 1); } if ( *end == ']' ) { ++end; } /* find the end delimeter and make sure we */ for ( ; end < aux->end && *end != ']'; ++end ) ; if ( end == start || end == aux->end ) rex_parse_error(rxnn, aux, p - 1); if ( !(rxc = mem_get(aux->mm, sizeof(*rxc))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = &rxc->base; rxc->base.type = REX_T_CLASS; rxc->base.repmin = rxc->base.repmax = 1; rxc->base.next = NULL; rxnn = &rxc->base.next; memset(&rxc->set, 0, sizeof(rxc->set)); for ( p = start; p < end; ++p ) { if ( *p == '-' && p != start && p != end - 1 ) { uchar ch = *(p - 1); uchar last = *(p + 1); if ( ch > last ) return rex_parse_error(rxnn, aux, p - 1); do { rxc->set[(ch >> 3) & 0x1F] |= (1 << (ch & 0x7)); } while ( ch++ < last ); ++p; } else { rxc->set[(*p >> 3) & 0x1F] |= (1 << (*p & 0x7)); } } if ( invert ) { for ( i = 0; i < 32 ; ++i ) rxc->set[i] = ~rxc->set[i]; } p = end + 1; if ( (rv = rex_check_repitions(&rxc->base, &p, aux)) < 0 ) return rv; return rex_parse(rxnn, p, aux); } static int rex_parse_any(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { struct rex_ascii_class *rc; int rv; if ( !(rc = mem_get(aux->mm, sizeof(*rc))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = &rc->base; rc->base.type = REX_T_CLASS; rc->base.repmin = rc->base.repmax = 1; rc->base.next = NULL; rxnn = &rc->base.next; memset(rc->set, ~0, sizeof(rc->set)); ++p; if ( (rv = rex_check_repitions(&rc->base, &p, aux)) < 0 ) return rv; return rex_parse(rxnn, p, aux); } static int rex_parse_choice(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { struct rex_choice *rc; if ( !(rc = mem_get(aux->mm, sizeof(*rc))) ) return rex_parse_error(rxnn, aux, NULL); rc->base.type = REX_T_CHOICE; rc->base.repmin = rc->base.repmax = 1; rc->base.next = NULL; if ( aux->lastch == NULL ) { struct rex_group *rg = aux->gstack; if ( rg == NULL ) rg = aux->initial; rc->opt1 = rg->base.next; rg->base.next = &rc->base; } else { rc->opt1 = aux->lastch->opt2; aux->lastch->opt2 = &rc->base; } rc->opt2 = NULL; *rxnn = NULL; rxnn = &rc->opt2; aux->lastch = rc; return rex_parse(rxnn, p+1, aux); } static int rex_parse_group_s(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { struct rex_group *rg; if ( !(rg = mem_get(aux->mm, sizeof(*rg))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = &rg->base; rg->base.type = REX_T_GROUP_S; rg->base.repmin = rg->base.repmax = 1; rg->base.next = NULL; rxnn = &rg->base.next; rg->num = ++aux->gnum; rg->other = aux->gstack; aux->gstack = rg; aux->lastch = NULL; return rex_parse(rxnn, p+1, aux); } static int finalize_choices(struct rex_group *rgs, struct rex_group *rge, struct rex_parse_aux *aux) { struct rex_node *rn, **trav; struct rex_choice *rc; if ( aux->lastch == NULL ) return 0; abort_unless(rgs->base.next->type == REX_T_CHOICE); /* we should now have a linked list of choices linked through the */ /* ->opt2 pointers with the last opt2 pointer pointing to a */ /* non-choice node. Each of the opt1 lists should end with a node */ /* pointing to NULL. The list _can_ be empty meaning an opt1 */ /* can point to NULL. Any sub-groups with choices should have the */ /* form of a group start node followed by a list of choices _all_ */ /* of which point to the group end node through their next pointer. */ /* So, hitting such a group should go from start to choice to end to */ /* whatever follows in the rest of the choice expression. This code */ /* changes all the final NULL pointers to point to the group end node.*/ /* Note that the last list will already point to the end node. */ rn = rgs->base.next; while ( rn->type == REX_T_CHOICE ) { rc = (struct rex_choice *)rn; rc->base.next = &rge->base; trav = &rc->opt1; while ( *trav != NULL ) trav = &(*trav)->next; *trav = &rge->base; rn = rc->opt2; } return 0; } static int rex_parse_group_e(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { struct rex_group *rge, *rgs, *rgn; int rv; /* Check the group start stack and pop the top one */ if ( aux->gstack == NULL ) return rex_parse_error(rxnn, aux, p); rgs = aux->gstack; aux->gstack = rgs->other; /* allocate node */ if ( !(rge = mem_get(aux->mm, sizeof(*rge))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = &rge->base; rge->base.type = REX_T_GROUP_E; rge->base.repmin = rge->base.repmax = 1; rge->base.next = NULL; rxnn = &rge->base.next; rgs->other = rge; rge->other = rgs; rge->num = rgs->num; ++p; /* close out any current choice nodes */ finalize_choices(rgs, rge, aux); /* reinstate enclosing group's choice (if any) */ if ( ((rgn = aux->gstack) != NULL) && (rgn->base.next->type == REX_T_CHOICE) ) { struct rex_choice *rc = (struct rex_choice *)rgn->base.next; while ( rc->opt2->type == REX_T_CHOICE ) rc = (struct rex_choice *)rc->opt2; aux->lastch = rc; } else { aux->lastch = NULL; } if ( (rv = rex_check_repitions(&rge->base, &p, aux)) < 0 ) return rv; rgs->base.repmin = rge->base.repmin; rgs->base.repmax = rge->base.repmax; return rex_parse(rxnn, p, aux); } static int rex_parse_anchor(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { struct rex_node *rn; if ( !(rn = mem_get(aux->mm, sizeof(*rn))) ) return rex_parse_error(rxnn, aux, NULL); *rxnn = rn; rn->type = (*p == '^') ? REX_T_BANCHOR : REX_T_EANCHOR; rn->repmin = rn->repmax = 1; rn->next = NULL; rxnn = &rn->next; return rex_parse(rxnn, p + 1, aux); } static int rex_parse(struct rex_node **rxnn, uchar *p, struct rex_parse_aux *aux) { abort_unless(aux && aux->end && aux->initial && aux->final && aux->mm); if ( p == aux->end ) { if ( aux->gstack != NULL ) return rex_parse_error(rxnn, aux, p); *rxnn = &aux->final->base; finalize_choices(aux->initial, aux->final, aux); return 0; } switch (*p) { case '*': case ']': case '+': case '?': case '{': case '}': return rex_parse_error(rxnn, aux, p); case '^': case '$': return rex_parse_anchor(rxnn, p, aux); case '(': return rex_parse_group_s(rxnn, p, aux); case '[': return rex_parse_class(rxnn, p, aux); case ')': return rex_parse_group_e(rxnn, p, aux); case '.': return rex_parse_any(rxnn, p, aux); case '|': return rex_parse_choice(rxnn, p, aux); default: return rex_parse_str(rxnn, p, aux); } } static int all_paths_start(struct rex_node *rxn) { switch (rxn->type) { case REX_T_BANCHOR: return 1; case REX_T_GROUP_S: return all_paths_start(rxn->next); case REX_T_CHOICE: { struct rex_choice *rc = (struct rex_choice *)rxn; return all_paths_start(rc->opt1) && all_paths_start(rc->opt2); } break; default: return 0; } } int rex_init(struct rex_pat *rxp, struct raw *pat, struct memmgr *mm, int *error) { struct rex_parse_aux aux; int rv; if ( !rxp || !pat || !pat->data || mm == NULL ) return -1; rxp->start_anchor = 0; rxp->start.base.type = REX_T_GROUP_S; rxp->start.base.repmin = 1; rxp->start.base.repmax = 1; rxp->start.base.next = NULL; rxp->start.num = 0; rxp->start.other = &rxp->end; rxp->end.base.type = REX_T_GROUP_E; rxp->end.base.repmin = 1; rxp->end.base.repmax = 1; rxp->end.base.next = NULL; rxp->end.num = 0; rxp->end.other = &rxp->start; rxp->mm = mm; aux.mm = rxp->mm; aux.initial = &rxp->start; aux.final = &rxp->end; aux.start = (uchar *)pat->data; aux.end = (uchar *)pat->data + pat->len; aux.gstack = NULL; aux.lastch = NULL; aux.eptr = error; aux.gnum = 0; rv = rex_parse(&rxp->start.base.next, (uchar *)pat->data, &aux); if ( rv == 0 ) rxp->start_anchor = all_paths_start(&rxp->start.base); else rex_free(rxp); return rv; } static void rex_free_help(struct rex_node *node, struct rex_node *end, struct memmgr *mm) { if ( node == NULL || node == end ) { return; } else if ( node->type == REX_T_GROUP_S ) { struct rex_group *rg = (struct rex_group *)node; rex_free_help(node->next, (struct rex_node *)rg->other, mm); rex_free_help((struct rex_node *)rg->other, end, mm); if ( rg->num > 0 ) mem_free(mm, node); } else if ( node->type == REX_T_CHOICE ) { struct rex_choice *rc = (struct rex_choice *)node; rex_free_help(rc->opt1, end, mm); rex_free_help(rc->opt2, end, mm); mem_free(mm, node); } else { rex_free_help(node->next, end, mm); mem_free(mm, node); } } void rex_free(struct rex_pat *rxp) { abort_unless(rxp); rex_free_help(&rxp->start.base, &rxp->end.base, rxp->mm); } struct rex_match_aux { char *start; char *end; char *gstart; unsigned grep; struct rex_match_loc *match; unsigned nmatch; struct rex_match_aux *prev; }; static int rex_match_rxn(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux); static int rex_next(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { int rv = REX_NOMATCH; if ( (rxn->repmax == REX_WILDCARD) || (rep < rxn->repmax) ) { rv = rex_match_rxn(rxn, cur, rep, aux); if ( rv != REX_NOMATCH ) return rv; } if ( rep >= rxn->repmin ) rv = rex_match_rxn(rxn->next, cur, 0, aux); return rv; } static int rex_match_string(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { struct rex_node_str *rs = (struct rex_node_str *)rxn; if ( ((aux->end - cur) >= rs->len) && (memcmp(rs->str, cur, rs->len) == 0) ) { return rex_next(rxn, cur + rs->len, rep + 1, aux); } else if ( rxn->repmin == 0 && rep == 0 ) { return rex_match_rxn(rxn->next, cur, 0, aux); } else { return REX_NOMATCH; } } static int rex_match_class(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { struct rex_ascii_class *rac = (struct rex_ascii_class *)rxn; int i, j; if ( aux->end - cur > 0 ) { i = *(uchar *)cur; j = i >> 3; i &= 0x7; if ( (rac->set[j] & (1 << i)) ) return rex_next(rxn, cur + 1, rep + 1, aux); } if ( rxn->repmin == 0 && rep == 0 ) return rex_match_rxn(rxn->next, cur, 0, aux); return REX_NOMATCH; } static int rex_match_choice(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { struct rex_choice *rc = (struct rex_choice *)rxn; int rv; abort_unless(!rep); rv = rex_match_rxn(rc->opt1, cur, 0, aux); if ( rv != REX_NOMATCH ) return rv; else return rex_match_rxn(rc->opt2, cur, 0, aux); } static int rex_match_group_s(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { struct rex_group *rg = (struct rex_group *)rxn; struct rex_match_aux aux2, *new_aux = aux; int rv; abort_unless(aux); if ( rep == 0 ) { aux2 = *aux; aux2.gstart = cur; aux2.prev = aux; new_aux = &aux2; } new_aux->grep = rep + 1; rv = rex_match_rxn(rxn->next, cur, 0, new_aux); if ( rv != REX_ERROR ) { if ( rv == REX_NOMATCH && rxn->repmin == 0 && rep == 0 ) { /* we are doing the job of the end group here */ if ( rg->num < aux->nmatch && !aux->match[rg->num].valid ) { aux->match[rg->num].valid = 1; aux->match[rg->num].start = cur - aux->start; aux->match[rg->num].len = 0; } rv = rex_match_rxn(rg->other->base.next, cur, 0, aux); } } return rv; } static int rex_match_group_e(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { struct rex_group *rg = (struct rex_group *)rxn; int rv = REX_NOMATCH; rep = aux->grep; abort_unless(aux); if ( (rxn->repmax == REX_WILDCARD) || (rep < rxn->repmax) ) { rv = rex_match_group_s(&rg->other->base, cur, aux->grep, aux); aux->grep = rep; if ( rv != REX_NOMATCH ) return rv; } if ( rep >= rxn->repmin ) rv = rex_match_rxn(rxn->next, cur, 0, aux->prev); if ( rv == REX_MATCH && rg->num < aux->nmatch && !aux->match[rg->num].valid ) { aux->match[rg->num].valid = 1; aux->match[rg->num].start = aux->gstart - aux->start; aux->match[rg->num].len = cur - aux->gstart; } return rv; } static int rex_match_rxn(struct rex_node *rxn, char *cur, unsigned rep, struct rex_match_aux *aux) { int rv; if ( rxn == NULL ) return REX_MATCH; switch( rxn->type ) { case REX_T_STRING: rv = rex_match_string(rxn, cur, rep, aux); break; case REX_T_CLASS: rv = rex_match_class(rxn, cur, rep, aux); break; case REX_T_CHOICE: rv = rex_match_choice(rxn, cur, rep, aux); break; case REX_T_GROUP_S: rv = rex_match_group_s(rxn, cur, rep, aux); break; case REX_T_GROUP_E: rv = rex_match_group_e(rxn, cur, rep, aux); break; case REX_T_BANCHOR: if ( cur == aux->start ) return rex_match_rxn(rxn->next, cur, 0, aux); else return REX_NOMATCH; break; case REX_T_EANCHOR: if ( cur == aux->end ) return rex_match_rxn(rxn->next, cur, 0, aux); else return REX_NOMATCH; break; default: return REX_ERROR; } return rv; } int rex_match(struct rex_pat *rxp, struct raw *str, struct rex_match_loc *m, uint nm) { struct rex_match_aux aux; char *cur; int rv; if ( rxp == NULL || str == NULL || str->data == NULL ) return REX_ERROR; if ( rxp->start.base.repmin != 1 || rxp->start.base.repmax != 1 || rxp->end.base.repmin != 1 || rxp->end.base.repmax != 1 ) return REX_ERROR; if ( nm > 0 && m == 0 ) return REX_ERROR; aux.start = str->data; aux.end = str->data + str->len; aux.match = m; aux.nmatch = nm; memset(m, 0, sizeof(*m) * nm); /* if all paths start with a start anchor don't search */ /* the entire string: stop and return here */ aux.gstart = aux.start; rv = rex_match_rxn(&rxp->start.base, aux.gstart, 0, &aux); if ( rv != REX_NOMATCH || rxp->start_anchor || aux.gstart == aux.end ) return rv; for ( cur = aux.start + 1; cur < aux.end; ++cur ) { aux.gstart = cur; rv = rex_match_rxn(&rxp->start.base, cur, 0, &aux); if ( rv != REX_NOMATCH ) return rv; } return REX_NOMATCH; }
github188/catlib
include/std/stdio.h
<filename>include/std/stdio.h<gh_stars>1-10 /* * stdio.h -- C stdio.h header file. * * by <NAME> * * Copyright 2003-2014 -- See accompanying license * */ #ifndef __cat_stdio_h #define __cat_stdio_h #include <cat/cat.h> #include <stdarg.h> #if !CAT_USE_STDLIB typedef struct { char * f_buffer; size_t f_buflen; size_t f_fill; int f_flags; int f_fd; int f_lastop; } FILE; #define BUFSIZ 4096 #define _IOUNUSED 0x0 #define _IONBF 0x1 #define _IOLBF 0x2 #define _IOFBF 0x3 #define _IOBFMASK 0x3 #define EOF -1 #define CAT_SIO_READ 0x10 #define CAT_SIO_WRITE 0x20 #define CAT_SIO_RDWR (CAT_SIO_READ|CAT_SIO_WRITE) #define CAT_SIO_BINARY 0x40 #define CAT_SIO_EOF 0x100 #define CAT_SIO_ERR 0x200 #define CAT_SIO_BUFGIVEN 0x400 FILE *fopen(const char *path, const char *mode); FILE *freopen(const char *path, const char *mode, FILE *file); int fflush(FILE *stream); int fclose(FILE *stream); void clearerr(FILE *stream); int feof(FILE *stream); int ferror(FILE *stream); int fileno(FILE *stream); size_t fwrite(const void *ptr, size_t msiz, size_t nmem, FILE *file); int fputc(int c, FILE *stream); int fputs(const char *s, FILE *stream); int putc(int c, FILE *stream); int putchar(int c); int puts(const char *s); size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file); void setbuf(FILE *stream, char *buf); void setbuffer(FILE *stream, char *buf, size_t size); void setlinebuf(FILE *file); int setvbuf(FILE *file, char *buf, int mode, size_t bsiz); int printf(const char *format, ...); int fprintf(FILE *stream, const char *format, ...); int vprintf(const char *format, va_list ap); int vfprintf(FILE *stream, const char *format, va_list ap); int snprintf(char *buf, size_t len, const char *fmt, ...); int sprintf(char *buf, const char *fmt, ...); int vsnprintf(char *buf, size_t len, const char *fmt, va_list ap); int vsprintf(char *buf, const char *fmt, va_list ap); /* not implemented */ int fgetc(FILE *stream); extern FILE *stdin, *stdout, *stderr; #endif /* !CAT_USE_STDLIB */ #endif /* __cat_stdio_h */
github188/catlib
src/pack.c
<filename>src/pack.c /* * pack.c -- Functions to pack values into byte arrays * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/pack.h> #include <stdarg.h> #include <ctype.h> #include <string.h> #include <stdlib.h> typedef unsigned char byte; typedef unsigned short half; typedef unsigned long word; typedef signed char sbyte; typedef signed short shalf; typedef signed long sword; #if PSIZ_MAX % PSIZ_BYTE == 0 && PSIZ_BYTE > 1 #define PSIZ_BYTE_OVERFLOW ((PSIZ_MAX / PSIZ_BYTE) + 1) #else #define PSIZ_BYTE_OVERFLOW (PSIZ_MAX / PSIZ_BYTE) #endif #if PSIZ_MAX % PSIZ_HALF == 0 #define PSIZ_HALF_OVERFLOW ((PSIZ_MAX / PSIZ_HALF) + 1) #else #define PSIZ_HALF_OVERFLOW (PSIZ_MAX / PSIZ_HALF) #endif #if PSIZ_MAX % PSIZ_WORD == 0 #define PSIZ_WORD_OVERFLOW ((PSIZ_MAX / PSIZ_WORD) + 1) #else #define PSIZ_WORD_OVERFLOW (PSIZ_MAX / PSIZ_WORD) #endif #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG typedef unsigned long long jumbo; typedef signed long long sjumbo; #if PSIZ_MAX % PSIZ_JUMBO == 0 #define PSIZ_JUMBO_OVERFLOW ((PSIZ_MAX / PSIZ_JUMBO) + 1) #else #define PSIZ_JUMBO_OVERFLOW (PSIZ_MAX / PSIZ_JUMBO) #endif #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ static byte *pack_half(byte *p, word val, int bigendian) { if ( bigendian ) { *p++ = (val >> 8) & 0xFF; *p++ = val & 0xFF; } else { *p++ = val & 0xFF; *p++ = (val >> 8) & 0xFF; } return p; } static byte *pack_word(byte *p, word val, int bigendian) { if ( bigendian ) { *p++ = (val >> 24) & 0xFF; *p++ = (val >> 16) & 0xFF; *p++ = (val >> 8) & 0xFF; *p++ = val & 0xFF; } else { *p++ = val & 0xFF; *p++ = (val >> 8) & 0xFF; *p++ = (val >> 16) & 0xFF; *p++ = (val >> 24) & 0xFF; } return p; } static byte *unpack_half(byte *p, void *hp, int bigendian, int issigned) { half u = 0; shalf s = 0; if ( bigendian ) { if ( issigned ) { s = (*p++ & 0xFF) << 8; s |= *p++ & 0xFF; s |= -(s & 0x8000); *(shalf *)hp = s; } else { u = (*p++ & 0xFF) << 8; u |= *p++; *(half *)hp = u; } } else { if ( issigned ) { s = (*p++ & 0xFF); s |= (*p++ & 0xFF) << 8; s |= -(s & 0x8000); *(shalf *)hp = s; } else { u |= (*p++ & 0xFF); u = (*p++ & 0xFF) << 8; *(half *)hp = u; } } return p; } static byte *unpack_word(byte *p, void *wp, int bigendian, int issigned) { word u = 0; sword s = 0; if ( bigendian ) { if ( issigned ) { s = ((sword)*p++ & 0xFF) << 24; s |= ((sword)*p++ & 0xFF) << 16; s |= ((sword)*p++ & 0xFF) << 8; s |= ((sword)*p++ & 0xFF); s |= -(s & 0x80000000); *(sword *)wp = s; } else { u = ((word)*p++ & 0xFF) << 24; u |= ((word)*p++ & 0xFF) << 16; u |= ((word)*p++ & 0xFF) << 8; u |= ((word)*p++ & 0xFF); *(word *)wp = u; } } else { if ( issigned ) { s = ((sword)*p++ & 0xFF); s |= ((sword)*p++ & 0xFF) << 8; s |= ((sword)*p++ & 0xFF)<< 16; s |= ((sword)*p++ & 0xFF)<< 24; s |= -(s & 0x80000000); *(sword *)wp = s; } else { u = ((word)*p++ & 0xFF); u |= ((word)*p++ & 0xFF) << 8; u |= ((word)*p++ & 0xFF) << 16; u |= ((word)*p++ & 0xFF) << 24; *(word *)wp = u; } } return p; } #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG static byte *pack_jumbo(byte *p, jumbo jval, int bigendian) { if ( bigendian ) { *p++ = (jval >> 56) & 0xFF; *p++ = (jval >> 48) & 0xFF; *p++ = (jval >> 40) & 0xFF; *p++ = (jval >> 32) & 0xFF; *p++ = (jval >> 24) & 0xFF; *p++ = (jval >> 16) & 0xFF; *p++ = (jval >> 8) & 0xFF; *p++ = jval & 0xFF; } else { *p++ = jval & 0xFF; *p++ = (jval >> 8) & 0xFF; *p++ = (jval >> 16) & 0xFF; *p++ = (jval >> 24) & 0xFF; *p++ = (jval >> 32) & 0xFF; *p++ = (jval >> 40) & 0xFF; *p++ = (jval >> 48) & 0xFF; *p++ = (jval >> 56) & 0xFF; } return p; } static byte *unpack_jumbo(byte *p, void *jp, int bigendian, int issigned) { jumbo u = 0; sjumbo s = 0; if ( bigendian ) { if ( issigned ) { s = ((sjumbo)*p++ & 0xFF) << 56; s |= ((sjumbo)*p++ & 0xFF) << 48; s |= ((sjumbo)*p++ & 0xFF) << 40; s |= ((sjumbo)*p++ & 0xFF) << 32; s |= ((sjumbo)*p++ & 0xFF) << 24; s |= ((sjumbo)*p++ & 0xFF) << 16; s |= ((sjumbo)*p++ & 0xFF) << 8; s |= ((sjumbo)*p++ & 0xFF); s |= -(s & 0x8000000000000000ll); *(sjumbo *)jp = s; } else { u = ((jumbo)*p++ & 0xFF) << 56; u |= ((jumbo)*p++ & 0xFF) << 48; u |= ((jumbo)*p++ & 0xFF) << 40; u |= ((jumbo)*p++ & 0xFF) << 32; u |= ((jumbo)*p++ & 0xFF) << 24; u |= ((jumbo)*p++ & 0xFF) << 16; u |= ((jumbo)*p++ & 0xFF) << 8; u |= ((jumbo)*p++ & 0xFF); *(jumbo *)jp = u; } } else { if ( issigned ) { s = ((sjumbo)*p++ & 0xFF); s |= ((sjumbo)*p++ & 0xFF) << 8; s |= ((sjumbo)*p++ & 0xFF) << 16; s |= ((sjumbo)*p++ & 0xFF) << 24; s |= ((sjumbo)*p++ & 0xFF) << 32; s |= ((sjumbo)*p++ & 0xFF) << 40; s |= ((sjumbo)*p++ & 0xFF) << 48; s |= ((sjumbo)*p++ & 0xFF) << 56; s |= -(s & 0x8000000000000000ll); *(sjumbo *)jp = s; } else { u = ((jumbo)*p++ & 0xFF); u |= ((jumbo)*p++ & 0xFF) << 8; u |= ((jumbo)*p++ & 0xFF) << 16; u |= ((jumbo)*p++ & 0xFF) << 24; u |= ((jumbo)*p++ & 0xFF) << 32; u |= ((jumbo)*p++ & 0xFF) << 40; u |= ((jumbo)*p++ & 0xFF) << 48; u |= ((jumbo)*p++ & 0xFF) << 56; *(jumbo *)jp = u; } } return p; } #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ size_t pack(void *buf, size_t blen, const char *fmt, ...) { va_list ap; int bigendian = 1; size_t nreps, i, left; size_t len; byte *p, *bytep; half *halfp; word *wordp; struct raw *raw; char *cp; #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG jumbo *jumbop; #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ abort_unless(buf); abort_unless(fmt); if ( blen == 0 ) return 0; if ( blen > PSIZ_MAX ) blen = PSIZ_MAX; left = blen; va_start(ap, fmt); p = buf; while ( *fmt ) { if ( toupper(*fmt) == 'E' ) { bigendian = *fmt == 'E'; continue; } nreps = 0; if ( isdigit(*fmt) ) { nreps = strtoul(fmt, &cp, 10); if ( nreps <= 0 ) goto error; fmt = cp; } switch ( *fmt ) { case 'b': case 'B': if ( nreps == 0 ) { if ( PSIZ_BYTE > left ) goto error; *p++ = va_arg(ap, int) & 0xFF; left -= PSIZ_BYTE; } else { if ( (nreps > PSIZ_BYTE_OVERFLOW) || (PSIZ_BYTE * nreps > left) ) goto error; bytep = va_arg(ap, byte *); abort_unless(bytep); for ( i = 0 ; i < nreps ; ++i ) *p++ = (bytep[i] & 0xFF); left -= PSIZ_BYTE * nreps; } break; case 'h': case 'H': if ( ! nreps ) { if ( PSIZ_HALF > left ) goto error; p = pack_half(p, (half)va_arg(ap, int), bigendian); left -= PSIZ_HALF; } else { if ( (nreps > PSIZ_HALF_OVERFLOW) || (PSIZ_HALF * nreps > left) ) goto error; halfp = va_arg(ap, half *); abort_unless(halfp); for ( i = 0 ; i < nreps ; ++i ) p = pack_half(p, halfp[i], bigendian); left -= PSIZ_HALF * nreps; } break; case 'w': case 'W': if ( ! nreps ) { if ( PSIZ_WORD > left ) goto error; p = pack_word(p, va_arg(ap, word), bigendian); left -= PSIZ_WORD; } else { if ( (nreps > PSIZ_WORD_OVERFLOW) || (PSIZ_WORD * nreps > left) ) goto error; wordp = va_arg(ap, word *); abort_unless(wordp); for ( i = 0 ; i < nreps ; ++i ) p = pack_word(p, wordp[i], bigendian); left -= PSIZ_WORD * nreps; } break; #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG case 'j': case 'J': if ( ! nreps ) { if ( PSIZ_JUMBO > left ) goto error; p = pack_jumbo(p, va_arg(ap,jumbo), bigendian); left -= PSIZ_JUMBO; } else { if ( (nreps > PSIZ_JUMBO_OVERFLOW) || (PSIZ_JUMBO * nreps > left) ) goto error; jumbop = va_arg(ap, jumbo *); abort_unless(jumbop); for ( i = 0 ; i < nreps ; ++i ) p = pack_jumbo(p, jumbop[i], bigendian); left -= PSIZ_JUMBO * nreps; } break; #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ case 'r': if ( ! nreps ) nreps = 1; raw = va_arg(ap, struct raw *); abort_unless(raw); for ( i = 0 ; i < nreps ; ++i ) { len = raw[i].len; if ( (len > PSIZ_MAX) || (len > left) ) goto error; memmove(p, raw[i].data, len); p += len; left -= len; } break; default: goto error; } ++fmt; } va_end(ap); return blen - left; error: va_end(ap); return 0; } size_t unpack(void *buf, size_t blen, const char *fmt, ...) { va_list ap; byte *p, *bytep; sbyte *sbytep; int bigendian = 1, issigned; size_t pulled, nreps, i; size_t osiz, isiz; char *cp, *inp; byte *(*unpackf)(byte *, void *, int, int); abort_unless(buf); abort_unless(fmt); abort_unless(blen <= PSIZ_MAX); if ( blen == 0 ) return 0; p = (byte *)buf; pulled = 0; va_start(ap, fmt); while ( *fmt ) { if ( toupper(*fmt) == 'E' ) { bigendian = *fmt == 'E'; continue; } nreps = 1; if ( isdigit(*fmt) ) { nreps = strtoul(fmt, &cp, 10); if ( nreps <= 0 ) goto error; fmt = cp; } switch ( *fmt ) { case 'b': if ( (nreps > PSIZ_BYTE_OVERFLOW) || (blen < PSIZ_BYTE * nreps) || (PSIZ_BYTE * nreps > blen - pulled) ) goto error; bytep = va_arg(ap, byte *); abort_unless(bytep); for ( i = 0 ; i < nreps ; ++i ) *bytep++ = *p++; pulled += PSIZ_BYTE * nreps; nreps = 0; break; case 'B': if ( (nreps > PSIZ_BYTE_OVERFLOW) || (blen < PSIZ_BYTE * nreps) || (PSIZ_BYTE * nreps > blen - pulled) ) goto error; sbytep = va_arg(ap, sbyte *); abort_unless(sbytep); for ( i = 0 ; i < nreps ; ++i ) { sbyte sb = *p++ & 0xFF; sb |= -(sb & 0x80); *sbytep++ = sb; } pulled += PSIZ_BYTE * nreps; nreps = 0; break; case 'h': case 'H': isiz = PSIZ_HALF; osiz = PSIZ_HALF_OVERFLOW; unpackf = &unpack_half; issigned = *fmt == 'H'; inp = (char *)va_arg(ap, half *); break; case 'w': case 'W': isiz = PSIZ_WORD; osiz = PSIZ_WORD_OVERFLOW; unpackf = &unpack_word; issigned = *fmt == 'W'; inp = (char *)va_arg(ap, word *); break; #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG case 'j': case 'J': isiz = PSIZ_JUMBO; osiz = PSIZ_JUMBO_OVERFLOW; unpackf = &unpack_jumbo; issigned = *fmt == 'W'; inp = (char *)va_arg(ap, jumbo *); break; #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ default: goto error; } if ( nreps > 0 ) { if ( (nreps > osiz) || (blen < isiz * nreps) || (isiz * nreps > blen - pulled) ) goto error; abort_unless(inp); for ( i = 0 ; i < nreps ; ++i ) { p = (*unpackf)(p, inp, bigendian, issigned); inp += isiz; } pulled += isiz * nreps; } ++fmt; } va_end(ap); return pulled; error: va_end(ap); return 0; } size_t packlen(const char *fmt, ...) { va_list ap; size_t max, i, nreps; struct raw *raw; char *cp; abort_unless(fmt); va_start(ap, fmt); max = PSIZ_MAX; while ( *fmt ) { nreps = 1; if ( isdigit(*fmt) ) { nreps = strtoul(fmt, &cp, 10); if (nreps <= 0) goto error; fmt = cp; } switch ( *fmt ) { case 'e': case 'E': break; case 'b': case 'B': if ( (nreps > PSIZ_BYTE_OVERFLOW) || (nreps * PSIZ_BYTE > max) ) goto error; max -= PSIZ_BYTE * nreps; break; case 'h': case 'H': if ( (nreps > PSIZ_HALF_OVERFLOW) || (nreps * PSIZ_HALF > max) ) goto error; max -= PSIZ_HALF * nreps; break; case 'w': case 'W': if ( (nreps > PSIZ_WORD_OVERFLOW) || (nreps * PSIZ_WORD > max) ) goto error; max -= PSIZ_WORD * nreps; break; #if defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG case 'j': case 'J': if ( (nreps > PSIZ_JUMBO_OVERFLOW) || (nreps * PSIZ_JUMBO > max) ) goto error; max -= PSIZ_JUMBO * nreps; break; #endif /* defined(CAT_HAS_LONGLONG) && CAT_HAS_LONGLONG */ case 'r': raw = va_arg(ap, struct raw *); abort_unless(raw); for ( i = 0 ; i < nreps ; ++i ) { if ( raw[i].len > max ) goto error; max -= raw[i].len; } break; default: goto error; } ++fmt; } va_end(ap); return PSIZ_MAX - max; error: va_end(ap); return 0; }
github188/catlib
src/grow.c
/* * grow.c -- funtions to grow dynamically allocated memory * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cat.h> #include <cat/aux.h> #include <cat/mem.h> #include <cat/grow.h> #include <stdlib.h> /* * Rules: * - min must be less that CAT_MAXGROW * - len and ptr must be nonnull * - *ptr may be null if and only if len == 0 * - if min == 0 then it the buffer double in size or be set to CAT_MINGROW * if len == 0 * - the new length will be a power of 2 multiple of the old length or * CAT_MAXGROW if doubling the length would put it above CAT_MAXGROW */ int grow(byte_t **ptr, size_t *lenp, size_t min) { void *p2 = *ptr; int rv; rv = agrow(&p2, 1, lenp, min); *ptr = p2; return rv; } int agrow(void **ptr, size_t ilen, size_t *lenp, size_t min) { size_t len, n, newlen; byte_t *p; size_t maxmem = (size_t)~0; abort_unless(ptr); abort_unless(ilen > 0); abort_unless(lenp); #if CAT_HAS_DIV maxmem /= ilen; #else maxmem = uldivmod(maxmem, ilen, 1); #endif len = *lenp; abort_unless((len > 0) || (*ptr == NULL)); abort_unless(len <= maxmem); if ( min > maxmem ) return -1; /* When min == 0 && len == maxmem fall through to return 0 */ if ( (min == 0) && (len < maxmem) ) min = len + 1; if ( min <= len ) return 0; if ( len > 0 ) { newlen = len; } else { newlen = CAT_MINGROW / ilen; if ( newlen == 0 ) newlen = 1; } while ( newlen < min ) { n = newlen << 1; if ( (n < newlen) || (n > maxmem) ) newlen = maxmem; else newlen = n; } p = realloc(*ptr, newlen * ilen); if ( !p ) return -1; *ptr = p; *lenp = newlen; return 0; } int mm_grow(struct memmgr *mm, byte_t **ptr, size_t *lenp, size_t min) { void *p2 = ptr; int rv; rv = mm_agrow(mm, &p2, 1, lenp, min); *ptr = p2; return rv; } int mm_agrow(struct memmgr *mm, void **ptr, size_t ilen, size_t *lenp, size_t min) { size_t len, n, newlen; byte_t *p; size_t maxmem = (size_t)~0; abort_unless(ptr); abort_unless(ilen > 0); abort_unless(lenp); #if CAT_HAS_DIV maxmem /= ilen; #else maxmem = uldivmod(maxmem, ilen, 1); #endif len = *lenp; abort_unless((len > 0) || (*ptr == NULL)); abort_unless(len <= maxmem); if ( min > maxmem ) return -1; /* When min == 0 && len == maxmem fall through to return 0 */ if ( (min == 0) && (len < maxmem) ) min = len + 1; if ( min <= len ) return 0; if ( len > 0 ) { newlen = len; } else { newlen = CAT_MINGROW / ilen; if ( newlen == 0 ) newlen = 1; } while ( newlen < min ) { n = newlen << 1; if ( (n < newlen) || (n > maxmem) ) newlen = maxmem; else newlen = n; } p = mem_resize(mm, *ptr, newlen); if ( !p ) return -1; *ptr = p; *lenp = newlen; return 0; }
github188/catlib
test/testmatch.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <cat/cat.h> #include <cat/match.h> #include <cat/err.h> #include <cat/raw.h> #include <cat/stduse.h> void usage(void) { err("usage: testmatch (-k|-b|-s) <string> <pattern>\n"); } void dokmp(struct raw *str, struct raw *pat) { struct kmppat *kmp; unsigned long loc; kmp = kmp_pnew(&estdmm, pat); if (kmp_match(str, kmp, &loc)) printf("Found %s at position %u in %s\n", pat->data, (uint)loc, str->data); else printf("%s not found in %s\n", pat->data, str->data); free(kmp); } void dobm(struct raw *str, struct raw *pat) { struct bmpat *bmp; unsigned long loc; bmp = bm_pnew(&estdmm, pat); if (bm_match(str, bmp, &loc)) printf("Found %s at position %u in %s\n", pat->data, (uint)loc, str->data); else printf("%s not found in %s\n", pat->data, str->data); free(bmp); } struct gatherctx { struct sfxtree *sfx; struct chtab *edges; struct chtab *nodes; }; static int nedges = 0, nnodes = 0; void gather(void *edgep, void *gatherp) { struct sfxedge *edge = edgep; struct gatherctx *gctx = gatherp; ++nedges; if ( !cht_get(gctx->edges, edge) ) cht_put(gctx->edges, edge, int2ptr(nedges)); if ( !cht_get(gctx->nodes, edge->node) ) { ++nnodes; cht_put(gctx->nodes, edge->node, int2ptr(nnodes)); } } void printedges(void *edgep, void *gatherp) { struct sfxedge *edge = edgep; struct gatherctx *gctx = gatherp; struct sfxedgekey *ek = edge->hentry.key; int src, dst, edgenum; char ch; char str[50]; src = ptr2int(cht_get(gctx->nodes, ek->node)); dst = ptr2int(cht_get(gctx->nodes, edge->node)); edgenum = ptr2int(cht_get(gctx->edges, edge)); ch = ek->character; if ( ch == '\0' ) ch = '@'; if ( edge->end - edge->start + 1 > sizeof(str) ) str[0] = '\0'; else { memcpy(str, gctx->sfx->str.data + edge->start, edge->end - edge->start + 1); str[edge->end - edge->start + 1] = '\0'; } printf("Edge %3d: %3d (%c:%3ld,%3ld) -> %3d: %s\n", edgenum, src, ch, edge->start, edge->end, dst, str); } void printsfx(struct sfxtree *sfx) { struct gatherctx gctx; int i; char ch; gctx.sfx = sfx; gctx.edges = cht_new(100, &cht_std_attr_pkey, NULL, 1); gctx.nodes = cht_new(100, &cht_std_attr_pkey, NULL, 1); cht_put(gctx.nodes, &sfx->root, int2ptr(1)); nnodes = 1; ht_apply(&sfx->edges, gather, &gctx); for ( i = 0 ; i < sfx->str.len ; ++i ) printf("%2d ", i); printf("\n"); for ( i = 0 ; i < sfx->str.len ; ++i ) { ch = sfx->str.data[i]; if ( !isprint(ch) ) ch = '@'; printf(" %c ", ch); } printf("\n"); ht_apply(&sfx->edges, printedges, &gctx); cht_free(gctx.edges); cht_free(gctx.nodes); } void dosuffix(struct raw *str, struct raw *pat) { struct sfxtree *sfx; unsigned long loc; sfx = sfx_new(&estdmm, str); if (sfx_match(sfx, pat, &loc)) printf("Found %s at position %u in %s\n", pat->data, (uint)loc, str->data); else printf("%s not found in %s\n", pat->data, str->data); /* printsfx(sfx); */ sfx_clear(sfx); free(sfx); } int main(int argc, char *argv[]) { struct raw str, pat; if (argc < 4 || argv[1][0] != '-' ) usage(); str_to_raw(&str, argv[2], 0); str_to_raw(&pat, argv[3], 0); switch (argv[1][1]) { case 'k': dokmp(&str, &pat); break; case 'b': dobm(&str, &pat); break; case 's': dosuffix(&str, &pat); break; default: usage(); } return 0; }
github188/catlib
include/cat/crc.h
<filename>include/cat/crc.h /* * cat/crc.h -- Cyclic Redundancy Check headers * * by <NAME> * * Copyright 2015 -- See accompanying license * */ #ifndef __cat_crc32_h #define __cat_crc32_h #include <cat/cat.h> struct crc32tab { ulong resid[256]; }; #define CAT_CRC32_POLY 0x04C11DB7 #define CAT_CRC32_POLY_REV 0xEDB88320 #define CAT_CRC32C_POLY 0x1EDC6F41 /* Table accelerated CRC32 operations */ /* * Initialize a CRC-32 table for big-endian bits given a polynomial. * * - poly should represent a 33-bit irreducible polynomial in GF(2) with * the high order coefficient (x^32) == 1. The high order '1' is assumed * and the parameter should contain the coefficients of the remaining 32 * terms in the polynomial. The least-significant bit represents the * coefficient of term x^0. */ void crc32t_be_init(struct crc32tab *t, ulong poly); /* * Calculate the CRC-32 of a stream of bytes given an initial residue and * an initialized a table initialized by crc32t_be_init(). Returns the * new residue which one can pass to subsequent crc32t_be() calls. The * bits in the individual bytes are processed in big-endian order. The * residue is in big-endian bit order. */ ulong crc32t_be(const struct crc32tab *t, const void *p, size_t size, ulong crc); /* * Initialize a CRC-32 table for little-endian bits given a polynomial. * * - poly should represent a 33-bit irreducible polynomial in GF(2) with * the high order coefficient (x^32) == 1. The high order '1' is assumed * and the parameter should contain the coefficients of the remaining 32 * terms in the polynomial. The least-significant bit represents the * coefficient of term x^0. */ void crc32t_le_init(struct crc32tab *t, ulong poly); /* * Calculate the CRC-32 of a stream of bytes given an initial residue and * an initialized a table initialized by crc32t_le_init(). Returns the * new residue which one can pass to subsequent crc32t_le() calls. The * bits in the individual bytes are processed in little-endian order. The * residue is in little-endian bit order. */ ulong crc32t_le(const struct crc32tab *t, const void *p, size_t size, ulong crc); /* * Initialize global state for standard CRC-32 checksum calculations. * Used for for embedded environments where C global data structure * initialization isn't automatic or in multi-threaded environments. */ void crc32_init(void); /* * Begin a standard CRC-32 checksum and return the initial residue. * This function is threadsafe if crc32_init() has been called at * some point in the past. * * The standard CRC-32 checksum: * - Starts with an initial residue of 0xFFFFFFFF * - Processes bytes in little-endian bit-order * - Returns a checksum of the final residue in little-endian bit order * XORed with 0xFFFFFFFF */ ulong crc32_start(void); /* * Continue a standard CRC-32 checksum by adding more bytes. * - 'crc' must be the last current CRC residue returned either from * crc32_start() or the latest crc32_step() call. */ ulong crc32_step(const void *p, size_t size, ulong crc); /* * Output the the final CRC-32 given the last residue of a computation * begun with crc32_start() and crc32_step() calls. */ ulong crc32_finish(ulong crc); /* Convenience wrapper for a one-shot standard CRC-32 checksum calculation */ #define crc32(p, size) \ crc32_finish(crc32_step((p), (size), crc32_start())) #endif /* __cat_crc32_h */
github188/catlib
test/testlex.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/lex.h> #include <cat/err.h> #include <cat/stduse.h> #include <stdio.h> #include <string.h> enum token_e { WHITESPACE, NEWLINE, NUMBER, PLUS, MINUS, TIMES, DIVIDE, LPAREN, RPAREN }; const char *tok2name[] = { "whitespace", "newline", "number", "plus", "minus", "times", "divide", "left parentheses", "right parentheses" }; void Lex_add(struct lexer *lex, const char *pat, int tok) { if (lex_add_entry(lex, pat, tok) < 0) err("Error adding token '%d' with pattern '%s'", tok, pat); } int main(int argc, char *argv[]) { struct lexer *lex; char buffer[65563], *bp = buffer; int tok; const char *tokp; int toklen; lex = lex_new(&estdmm); Lex_add(lex, "[ \t]+", WHITESPACE); Lex_add(lex, "[\n\r]+", NEWLINE); Lex_add(lex, "-?[0-9]+", NUMBER); Lex_add(lex, "\\+", PLUS); Lex_add(lex, "-", MINUS); Lex_add(lex, "\\*", TIMES); Lex_add(lex, "/", DIVIDE); Lex_add(lex, "\\(", LPAREN); Lex_add(lex, "\\)", RPAREN); while ( bp < buffer + sizeof(buffer) - 1 && fgets(bp, sizeof(buffer) - (bp - buffer), stdin) ) { bp += strlen(bp); } lex_reset(lex, buffer); while ( (tok = lex_next_token(lex, &tokp, &toklen)) >= 0 ) { printf("Token %s", tok2name[tok]); if ( tok == NUMBER ) { char argbuf[256] = { 0 }; if ( toklen > sizeof(argbuf) - 1 ) toklen = sizeof(argbuf) - 1; memcpy(argbuf, tokp, toklen); printf(": '%s'", argbuf); } putchar('\n'); } if ( tok == LEX_END ) { printf("Normal token stream end\n"); } else if ( tok == LEX_NOMATCH ) { printf("No match for more tokens\n"); } else if ( tok == LEX_ERROR ) { printf("Error in token match\n"); } else { printf("Unknown return code: %d\n", tok); } return 0; }
github188/catlib
src/cpg.c
<gh_stars>1-10 #include <cat/cpg.h> #include <cat/str.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #define STR(_state, _cursor) ((_state)->buf + (_cursor)->i) #define CHAR(_state, _cursor) ((_state)->buf[(_cursor)->i]) #define CHARI(_state, _cursor, _off) ((_state)->buf[(_cursor)->i + _off]) #define NODE(_peg, _idx) (&(_peg)->nodes[_idx]) #define NODE_VALID_IDX(_peg, _idx) \ ((_idx) >= 0 && (_idx) < (_peg)->max_nodes) #define NODE_VALID(_peg, _idx, _type) \ (NODE_VALID_IDX(_peg, _idx) && ((_peg)->nodes[_idx].pn_type == _type)) int cpg_init(struct cpg_state *state, struct peg_grammar *peg, int (*getc)(void *in)) { abort_unless(state != NULL); state->debug = 0; state->depth = 0; state->in = NULL; state->buf = malloc(4096); if ( state->buf == NULL ) return -1; state->buflen = 4096; state->getc = getc; state->peg = peg; cpg_reset(state); return 0; } static int cpg_getc(struct cpg_state *state) { void *newbuf; int c; if ( state->cur.i >= state->eof ) { abort_unless(state->cur.i == state->eof); return EOF; } if ( state->cur.i >= state->buflen ) { abort_unless(state->cur.i == state->buflen); newbuf = realloc(state->buf, state->buflen + 4096); if ( newbuf == NULL ) return -2; state->buf = newbuf; memset((uchar *)newbuf + state->buflen, '\0', 4096); state->buflen += 4096; } if ( state->cur.i >= state->readidx ) { abort_unless(state->cur.i == state->readidx); c = (*state->getc)(state->in); if ( c == EOF ) { state->eof = state->cur.i; return EOF; } state->buf[state->readidx++] = c; } if ( state->buf[state->cur.i - 1] == '\n' ) state->cur.line++; return state->buf[state->cur.i++]; } /* * Forward definitions */ static int cpg_match_expression(struct cpg_state *state, int expr, void *aux); static int cpg_match_sequence(struct cpg_state *state, int seq, void *aux); static int cpg_match_primary(struct cpg_state *state, int pri, void *aux); static int cpg_match_identifier(struct cpg_state *state, int id, void *aux); static int cpg_match_token(struct cpg_state *state, int id, void *aux); static int cpg_match_literal(struct cpg_state *state, int lit, void *aux); static int cpg_match_class(struct cpg_state *state, int cls, void *aux); static int cpg_match_expression(struct cpg_state *state, int seq, void *aux) { struct peg_grammar *peg = state->peg; int rv; for ( ; seq >= 0 ; seq = NODE(peg, seq)->pn_next ) { rv = cpg_match_sequence(state, seq, aux); if ( rv != 0 ) return rv; } return 0; } static int cpg_match_sequence(struct cpg_state *state, int seq, void *aux) { struct peg_grammar *peg = state->peg; struct cpg_cursor oc = state->cur; struct peg_node *pn; int pri; int rv; abort_unless(NODE_VALID(peg, seq, PEG_SEQUENCE)); pn = NODE(peg, seq); for ( pri = pn->ps_pri; pri >= 0; pri = NODE(peg, pri)->pn_next ) { rv = cpg_match_primary(state, pri, aux); if ( rv <= 0 ) { state->cur = oc; return rv; } } return 1; } static int cpg_match_primary(struct cpg_state *state, int pri, void *aux) { struct peg_grammar *peg = state->peg; struct cpg_cursor oc = state->cur; struct peg_node *pn; uint nmatch = 0; int repeat; int mtype; int rv = -1; struct raw r; int act_rv; abort_unless(NODE_VALID(peg, pri, PEG_PRIMARY)); pn = NODE(peg, pri); repeat = (pn->pp_suffix == PEG_ATTR_STAR || pn->pp_suffix == PEG_ATTR_PLUS); abort_unless(NODE_VALID_IDX(peg, pn->pp_match)); mtype = NODE(peg, pn->pp_match)->pn_type; do { switch ( mtype ) { case PEG_SEQUENCE: rv = cpg_match_expression(state, pn->pp_match, aux); break; case PEG_IDENTIFIER: rv = cpg_match_identifier(state, pn->pp_match, aux); break; case PEG_LITERAL: rv = cpg_match_literal(state, pn->pp_match, aux); break; case PEG_CLASS: rv = cpg_match_class(state, pn->pp_match, aux); break; default: abort_unless(0); } if ( rv > 0 ) ++nmatch; } while ( rv > 0 && repeat ); if ( rv < 0 ) return rv; switch ( pn->pp_suffix ) { case PEG_ATTR_NONE: rv = (nmatch == 1); break; case PEG_ATTR_QUESTION: rv = 1; break; case PEG_ATTR_STAR: rv = 1; break; case PEG_ATTR_PLUS: rv = (nmatch >= 1); break; default: abort_unless(0); } if ( pn->pp_prefix != PEG_ATTR_NONE ) { state->cur = oc; if ( pn->pp_prefix == PEG_ATTR_NOT ) rv = !rv; else abort_unless(pn->pp_prefix == PEG_ATTR_AND); } else if ( rv <= 0 ) { state->cur = oc; } if ( rv > 0 && pn->pp_action == PEG_ACT_CALLBACK ) { r.data = state->buf + oc.i; r.len = state->cur.i - oc.i; act_rv = (*pn->pn_action_cb)(pri, &r, aux); if ( act_rv < 0 ) return act_rv; } return rv; } static void pad(struct cpg_state *state) { int i; for ( i = 0; i < state->depth; ++i ) fputc(' ', stderr); } static int cpg_match_identifier(struct cpg_state *state, int id, void *aux) { int rv; struct peg_grammar *peg = state->peg; struct peg_node *pn = NODE(state->peg, id); if ( state->debug ) { pad(state); fprintf(stderr, ">:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } ++state->depth; if ( PEG_IDX_IS_TOKEN(peg, pn->pi_def) ) { rv = cpg_match_token(state, id, aux); } else { abort_unless(NODE_VALID(peg, pn->pi_def, PEG_DEFINITION)); rv = cpg_match_expression(state, NODE(peg, pn->pi_def)->pd_expr, aux); } --state->depth; if ( state->debug ) { if ( rv < 0 ) { pad(state); fprintf(stderr, "E:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } else if ( rv == 0 ) { pad(state); fprintf(stderr, "F:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } else { pad(state); fprintf(stderr, "S:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } } return rv; } static int cpg_match_token(struct cpg_state *state, int id, void *aux) { struct peg_grammar *peg = state->peg; struct cpg_cursor oc = state->cur; int c; abort_unless(NODE_VALID(peg, id, PEG_IDENTIFIER)); if ( state->debug ) { pad(state); fprintf(stderr, "T>:'%d' at <L:%d/P:%d>\n", id, state->cur.line, state->cur.i); } c = cpg_getc(state); if ( c != EOF && c == PEG_TOKEN_ID(NODE(peg, id)->pi_def) ) { if ( state->debug ) { pad(state); fprintf(stderr, "TS:'%d' at <L:%d/P:%d>\n", id, state->cur.line, state->cur.i); } return 1; } else { state->cur = oc; if ( state->debug ) { pad(state); fprintf(stderr, "TF:'%d' at <L:%d/P:%d>\n", id, state->cur.line, state->cur.i); } return 0; } } static int cpg_match_literal(struct cpg_state *state, int lit, void *aux) { struct peg_grammar *peg = state->peg; struct cpg_cursor oc = state->cur; struct peg_node *pn = NODE(peg, lit); int c; int i; if ( state->debug ) { pad(state); fprintf(stderr, "L>:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } for ( i = 0 ; i < pn->pl_value.len ; ++i ) { c = cpg_getc(state); if ( c == EOF || c != pn->pl_value.data[i] ) goto fail; } if ( state->debug ) { pad(state); fprintf(stderr, "LS:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } return 1; fail: if ( state->debug ) { pad(state); fprintf(stderr, "LF:'%s' at <L:%d/P:%d>\n", pn->pn_str.data, state->cur.line, state->cur.i); } state->cur = oc; return 0; } static int cpg_match_class(struct cpg_state *state, int cls, void *aux) { struct peg_grammar *peg = state->peg; struct cpg_cursor oc = state->cur; int c; abort_unless(NODE_VALID(peg, cls, PEG_CLASS)); if ( state->debug ) { pad(state); fprintf(stderr, "C>:'%d' at <L:%d/P:%d>\n", cls, state->cur.line, state->cur.i); } c = cpg_getc(state); if ( c != EOF && cset_contains(NODE(peg, cls)->pc_cset, c) ) { if ( state->debug ) { pad(state); fprintf(stderr, "CS:'%d' at <L:%d/P:%d>\n", cls, state->cur.line, state->cur.i); } return 1; } else { state->cur = oc; if ( state->debug ) { pad(state); fprintf(stderr, "CF:'%d' at <L:%d/P:%d>\n", cls, state->cur.line, state->cur.i); } return 0; } } void cpg_set_debug_level(struct cpg_state *state, int level) { state->debug = level; } int cpg_parse(struct cpg_state *state, void *in, void *aux) { int rv; state->in = in; rv = cpg_match_identifier(state, state->peg->start_node, aux); if ( rv >= 0 && (state->cur.i < state->eof) ) rv = -1; return rv; } void cpg_reset(struct cpg_state *state) { if ( state->buf != NULL ) memset(state->buf, '\0', state->buflen); state->cur.i = 1; state->cur.line = 1; state->readidx = 1; state->eof = (uint)-1; } void cpg_fini(struct cpg_state *state) { free(state->buf); state->buf = NULL; state->buflen = 0; state->in = NULL; state->readidx = 0; state->peg = NULL; state->getc = NULL; state->eof = 0; state->debug = 0; }
github188/catlib
include/cat/lex.h
/* * lex.h -- Simple lexical analyzer using simple regexes * * by <NAME> * * Copyright 2012 -- See accompanying license */ #include <cat/cat.h> #include <cat/list.h> #include <cat/match.h> #include <cat/mem.h> struct lexer_entry { struct list entry; int token; struct rex_pat pattern; }; struct lexer { struct list entries; struct raw input; const char * next_char; struct memmgr * mm; }; enum { LEX_OK = 0, LEX_END = -1, LEX_NOMATCH = -2, LEX_ERROR = -3 }; /* instantiate a new lexer */ struct lexer *lex_new(struct memmgr *mm); /* add a pattern and assign it to a token in the lexer */ int lex_add_entry(struct lexer *lex, const char *pattern, int token); /* reset the lexer with input to tokenize: must be null terminated */ void lex_reset(struct lexer *lex, const char *string); /* get the next token along with the string that matched and its length */ /* returns LEX_END if at the end of the input, LEX_NOMATCH if hitting a */ /* input that the lexer is unable to match and LEX_ERROR if an error occurs */ int lex_next_token(struct lexer *lex, const char **string, int *len); /* free the lexer and release all associated resources */ void lex_destroy(struct lexer *lex);
github188/catlib
include/cat/avl.h
/* * cat/avl.h -- AVL tree implementation * * by <NAME> * * Copyright 2003-2017 -- See accompanying license * */ #ifndef __cat_avl_h #define __cat_avl_h #include <cat/cat.h> #include <cat/aux.h> /* Structure for an AVL-tree node: to be embedded in other structures */ struct anode { struct anode * p[3]; signed char b; /* - == left and + == right */ uchar pdir; /* on the parent's left or right ? */ struct avltree *tree; /* tree that owns this node */ void * key; /* the node's key */ }; #define CA_L 0 /* left node */ #define CA_R 2 /* right node */ #define CA_P 1 /* parent node */ #define CA_N 3 /* Used to denote an exact node when given a (p,dir) pair */ /* Structure for an AVL tree and root node */ struct avltree { cmp_f cmp; struct anode root; }; #define avl_left p[CA_L] #define avl_right p[CA_R] #define avl_parent p[CA_P] #define avl_root root.p[CA_P] #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define PTRDECL static #define CAT_AVL_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #define PTRDECL #endif /* CAT_USE_INLINE */ /* ----- Main Functions ----- */ /* Initialize an AVL tree. 'cmp' is the function to compare nodes with. */ DECL void avl_init(struct avltree *t, cmp_f cmp); /* Initialize a node of an AVL tree. 'k' is the node's key. */ DECL void avl_ninit(struct anode *n, void *k); /* * Find a node in an AVL tree 't' with key matching 'key'. This function * can be used in two modes depending on whether 'dir' is NULL. * * Mode 1: dir != NULL (lookup before insert) * - always returns a pointer to an AVL tree node * - if on return *dir == CA_N, then the return value of the function * points to the node in the tree whose key matches 'key'. * - otherwise, returns a node in the tree that would be the parent * of a new node inserted with a key of 'key' into the tree and * *dir is set to the pointer in said node that will point to said node. * - if *dir != CA_N, and loc = avl_lkup(); then one can call * avl_ins(t, n, loc, dir) where 'n' is a new node with a key equal * to the original search key to insert 'n' into the tree. * * Mode 2: dir == NULL (pure lookup) * - returns a pointer to the node in the tree that matches 'key' on * success, or a NULL if 'key' was not found in the tree. */ DECL struct anode * avl_lkup(struct avltree *t, const void *key, int *dir); /* * Insert a new node 'n' into an AVL tree 't' with 'loc' as the parent, and * dir indicating which pointer in 'loc' will point to 'n'. See avl_lkup() * for how to find the correct 'loc' and 'dir' values. */ DECL struct anode * avl_ins(struct avltree *t, struct anode *n, struct anode *loc, int dir); /* Remove a node from an AVL tree */ DECL void avl_rem(struct anode *node); /* Apply 'func' to every node in 't' passing 'ctx' as state to func */ DECL void avl_apply(struct avltree *t, apply_f func, void * ctx); /* Returns non-zero if 't' is empty or 0 if 't' is non-empty */ DECL int avl_isempty(struct avltree *t); /* Return the root node of the 't' or NULL if the tree is empty. */ DECL struct anode * avl_getroot(struct avltree *t); /* Return a pointer to the minimum node in 't' or NULL if the tree is empty */ DECL struct anode * avl_getmin(struct avltree *t); /* Return a pointer to the maximum node in 't' or NULL if the tree is empty */ DECL struct anode * avl_getmax(struct avltree *t); /* ----- Auxiliary (helper) functions (don't use) ----- */ DECL void avl_fix(struct anode *p, struct anode *c, int dir); DECL void avl_findloc(struct avltree *t, const void *key, struct anode **p, int *d); DECL void avl_ins_at(struct avltree *t, struct anode *node, struct anode *par, int dir); DECL void avl_rleft(struct anode *n1, struct anode *n2, int ins); DECL void avl_rright(struct anode *n1, struct anode *n2, int ins); DECL void avl_zleft(struct anode *n1, struct anode *n2, struct anode *n3); DECL void avl_zright(struct anode *n1, struct anode *n2, struct anode *n3); DECL struct anode *avl_findrep(struct anode *node); /* ----- Implementation ----- */ #if defined(CAT_AVL_DO_DECL) && CAT_AVL_DO_DECL DECL void avl_init(struct avltree *t, cmp_f cmp) { abort_unless(t); abort_unless(cmp); t->cmp = cmp; avl_ninit(&t->root, NULL); t->root.pdir = CA_P; } DECL void avl_ninit(struct anode *n, void *k) { abort_unless(n); n->p[0] = n->p[1] = n->p[2] = NULL; n->pdir = CA_P; n->b = 0; n->key = k; } DECL struct anode *avl_lkup(struct avltree *t, const void *key, int *rdir) { struct anode *p; int dir; abort_unless(t); avl_findloc(t, key, &p, &dir); if ( rdir ) { *rdir = dir; return p; } else { if ( dir == CA_N ) return p; else return NULL; } } DECL struct anode *avl_ins(struct avltree *t, struct anode *node, struct anode *loc, int atdir) { struct anode *p; int dir; const void *key; abort_unless(t); if ( !node ) return NULL; key = node->key; if ( loc ) { p = loc; dir = atdir; abort_unless((dir == CA_L) || (dir == CA_R) || ((dir == CA_P) && (p == &t->root))); } else { avl_findloc(t, key, &p, &dir); } if ( dir == CA_N ) { avl_fix(node, p->p[CA_L], CA_L); avl_fix(node, p->p[CA_R], CA_R); avl_fix(p->p[CA_P], node, p->pdir); node->tree = t; p->tree = NULL; avl_ninit(p, p->key); return p; } else { avl_ins_at(t, node, p, dir); node->tree = t; return NULL; } } DECL int avl_isempty(struct avltree *t) { abort_unless(t); return t->avl_root == NULL; } DECL struct anode *avl_getroot(struct avltree *t) { abort_unless(t); return t->avl_root; } DECL struct anode * avl_getmin(struct avltree *t) { struct anode *trav; abort_unless(t); trav = t->avl_root; if ( trav != NULL ) { while ( trav->p[CA_L] != NULL ) trav = trav->p[CA_L]; } return trav; } DECL struct anode * avl_getmax(struct avltree *t) { struct anode *trav; abort_unless(t); trav = t->avl_root; if ( trav != NULL ) { while ( trav->p[CA_R] != NULL ) trav = trav->p[CA_R]; } return trav; } /* currently an inorder traversal: we could add an arg to change this */ DECL void avl_apply(struct avltree *t, apply_f func, void * ctx) { struct anode *trav; int dir = CA_P; abort_unless(t); abort_unless(func); trav = t->avl_root; if ( ! trav ) return; do { switch(dir) { case CA_P: if ( trav->p[CA_L] ) trav = trav->p[CA_L]; /* dir stays the same */ else if ( trav->p[CA_R] ) trav = trav->p[CA_R]; /* dir stays the same */ else { func(trav, ctx); dir = trav->pdir; trav = trav->p[CA_P]; } break; case CA_L: if ( trav->p[CA_R] ) { dir = CA_P; trav = trav->p[CA_R]; /* dir stays the same */ } else { func(trav, ctx); dir = trav->pdir; trav = trav->p[CA_P]; } break; case CA_R: func(trav, ctx); dir = trav->pdir; trav = trav->p[CA_P]; break; } } while ( trav != &t->root ); } DECL void avl_findloc(struct avltree *t, const void *key, struct anode **pn, int *pd) { struct anode *tmp, *par; int dir = CA_P; abort_unless(t); abort_unless(pn); abort_unless(pd); par = &t->root; while ( (tmp = par->p[dir]) ) { par = tmp; dir = (*t->cmp)(key, tmp->key); if ( dir < 0 ) dir = CA_L; else if ( dir > 0 ) dir = CA_R; else { *pn = par; *pd = CA_N; return; } } *pn = par; *pd = dir; } DECL void avl_ins_at(struct avltree *t, struct anode *node, struct anode *par, int dir) { struct anode *tmp; abort_unless(t); abort_unless(node); abort_unless(par); abort_unless(dir >= CA_L && dir <= CA_R); avl_fix(par, node, dir); while ( (dir = node->pdir) != CA_P ) { node = node->p[CA_P]; /* dir - 1 == -1 if dir == CA_L and 1 if dir == CA_R */ if ( node->b += (dir - 1) ) { if ( node->b < -1 ) { if ( (tmp = node->p[CA_L])->b < 0 ) avl_rright(node, tmp, 1); else avl_zright(node, tmp, tmp->p[CA_R]); return; } else if ( node->b > 1 ) { if ( (tmp = node->p[CA_R])->b > 0 ) avl_rleft(node, tmp, 1); else avl_zleft(node, tmp, tmp->p[CA_L]); return; } } else /* balance is now 0 */ break; } } DECL struct anode *avl_findrep(struct anode *node) { struct anode *tmp; abort_unless(node); tmp = node->p[CA_L]; if ( ! tmp ) return node->p[CA_R]; else { while ( tmp->p[CA_R] ) tmp = tmp->p[CA_R]; } return tmp; } DECL void avl_rem(struct anode *node) { struct anode *rep, *par, *trav, *tmp, *tmp2; int dir; abort_unless(node); if ( ! node || ! node->tree ) return; par = node->p[CA_P]; rep = avl_findrep(node); /* if replacement is not a direct child and is not NULL */ if ( rep && (node->p[CA_L] != rep) && (node->p[CA_R] != rep) ) { trav = rep->p[CA_P]; dir = rep->pdir; avl_fix(rep->p[CA_P], rep->p[CA_L], rep->pdir); avl_fix(rep, node->p[CA_L], CA_L); avl_fix(rep, node->p[CA_R], CA_R); avl_fix(node->p[CA_P], rep, node->pdir); rep->b = node->b; } else { trav = par; dir = node->pdir; avl_fix(par, rep, dir); /* due to findrep alg, either node->p[CA_L] must be NULL or */ /* rep->p[CA_R] must be NULL */ /* rep is the right node iff the left is NULL */ if ( rep && (node->p[CA_L] == rep) ) { trav = rep; dir = CA_L; rep->b = node->b; avl_fix(rep, node->p[CA_R], CA_R); } } node->p[0] = node->p[1] = node->p[2] = NULL; node->tree = NULL; node->pdir = CA_P; node->b = 0; /* now traverse up the tree */ while ( dir != CA_P ) { if ( trav->b -= (dir - 1) ) { if ( trav->b < -1 ) { if ( (tmp = trav->p[CA_L])->b <= 0 ) { avl_rright(trav, tmp, 0); if ( tmp->b ) break; trav = tmp; } else { tmp2 = tmp->p[CA_R]; avl_zright(trav, tmp, tmp2); trav = tmp2; } } else if ( trav->b > 1 ) { if ( (tmp = trav->p[CA_R])->b >= 0 ) { avl_rleft(trav, tmp, 0); if ( tmp->b ) break; trav = tmp; } else { tmp2 = tmp->p[CA_L]; avl_zleft(trav, tmp, tmp2); trav = tmp2; } } else /* unbalanced but no height change */ break; } dir = trav->pdir; trav = trav->p[CA_P]; } } DECL void avl_fix(struct anode *p, struct anode *c, int dir) { abort_unless(p); abort_unless(dir >= CA_L && dir <= CA_R); p->p[dir] = c; if ( c ) { c->pdir = dir; c->p[CA_P] = p; } } DECL void avl_rleft(struct anode *n1, struct anode *n2, int ins) { abort_unless(n1); abort_unless(n2); avl_fix(n1, n2->p[CA_L], CA_R); avl_fix(n1->p[CA_P], n2, n1->pdir); avl_fix(n2, n1, CA_L); if ( ins || (n2->b > 0) ) { n1->b = 0; n2->b = 0; } else { n1->b = 1; n2->b = -1; } } DECL void avl_rright(struct anode *n1, struct anode *n2, int ins) { abort_unless(n1); abort_unless(n2); avl_fix(n1, n2->p[CA_R], CA_L); avl_fix(n1->p[CA_P], n2, n1->pdir); avl_fix(n2, n1, CA_R); if ( ins || (n2->b < 0) ) { n1->b = 0; n2->b = 0; } else { n1->b = -1; n2->b = 1; } } DECL void avl_zleft(struct anode *n1, struct anode *n2, struct anode *n3) { abort_unless(n1); abort_unless(n2); abort_unless(n3); avl_fix(n2, n3->p[CA_R], CA_L); avl_fix(n1, n3->p[CA_L], CA_R); avl_fix(n1->p[CA_P], n3, n1->pdir); avl_fix(n3, n1, CA_L); avl_fix(n3, n2, CA_R); switch ( n3->b ) { case -1: n1->b = 0; n2->b = 1; break; case 0: n1->b = 0; n2->b = 0; break; case 1: n1->b = -1; n2->b = 0; break; } n3->b = 0; } DECL void avl_zright(struct anode *n1, struct anode *n2, struct anode *n3) { abort_unless(n1); abort_unless(n2); abort_unless(n3); avl_fix(n2, n3->p[CA_L], CA_R); avl_fix(n1, n3->p[CA_R], CA_L); avl_fix(n1->p[CA_P], n3, n1->pdir); avl_fix(n3, n1, CA_R); avl_fix(n3, n2, CA_L); switch ( n3->b ) { case -1: n1->b = 1; n2->b = 0; break; case 0: n1->b = 0; n2->b = 0; break; case 1: n1->b = 0; n2->b = -1; break; } n3->b = 0; } #endif /* CAT_AVL_DO_DECL */ #undef PTRDECL #undef DECL #undef CAT_AVL_DO_DECL #endif /* __cat_avl_h */
github188/catlib
src/hash.c
/* * hash.c -- Hash table implementation * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_HASH_DO_DECL #define CAT_USE_INLINE 0 #define CAT_HASH_DO_DECL 1 #include <cat/hash.h>
github188/catlib
test/pegs/peg-print.c
<reponame>github188/catlib #include <cat/peg.h> #include <cat/buffer.h> #include <cat/emalloc.h> #include <cat/err.h> #include <stdio.h> #include <stdlib.h> char *readfile(const char *filename, uint *fs) { FILE *fp; long fsize; char *buf; long nread; fp = fopen(filename, "r"); if ( fp == NULL ) errsys("opening file %s: ", filename); fseek(fp, 0, SEEK_END); fsize = ftell(fp); rewind(fp); buf = emalloc(fsize + 1); nread = fread(buf, 1, fsize, fp); if ( fsize != nread ) errsys("error reading file: "); *fs = fsize; return buf; } int main(int argc, char *argv[]) { char *buf; char estr[256]; struct peg_grammar_parser pgp; struct peg_grammar peg; uint fsize; if ( argc < 2 ) err("usage: %s filename\n", argv[0]); buf = readfile(argv[1], &fsize); if ( peg_parse(&pgp, &peg, buf, fsize, 0) < 0 ) err("%s\n", peg_err_string(&pgp, estr, sizeof(estr))); printf("Successfully parsed %s\n", argv[1]); printf("Parsed Grammar\n"); peg_print(&peg, stdout); return 0; }
github188/catlib
include/cat/sort.h
/* * cat/sort.h -- Sorting arrays * * by <NAME> * * Copyright 2009-2012 See accompanying license * */ #ifndef __cat_sort_h #define __cat_sort_h #include <cat/cat.h> void isort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp); void ssort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp); void hsort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp); void qsort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp); void array_to_voidp(void **varr, void *arr, size_t nelem, size_t esize); void permute_array(void *arr, void *tswap, void **varr, size_t nelem, size_t esize); #endif /* __cat_sort_h */
github188/catlib
include/cc/stdarg.h
/* * stdarg.h -- variable argument macros * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __catstdarg_h #define __catstdarg_h /* stdarg.h -- a best guess: works for x86 */ typedef char *va_list; #define __CAT_ASIZ sizeof(int) #define __CAT_ROUND(x) ((((x) + __CAT_ASIZ - 1) / __CAT_ASIZ) * __CAT_ASIZ) #define va_start(ap, last) ((ap)=(char*)&(last)+__CAT_ROUND(sizeof(last))) #define va_arg(ap, type) \ ((sizeof(type) < sizeof(int)) ? \ ((ap) += sizeof(int), *((type *)((ap) - sizeof(int)))) : \ ((ap) += sizeof(type), *((type *)((ap) - sizeof(type))))) #define va_copy(dst, src) ((dst) = (src)) #define __va_copy(d,s) va_copy(d,s) #define va_end(ap) ((void) 0) #endif /* __catstdarg_h */
github188/catlib
test/pegs/peg-test-parse.c
<gh_stars>1-10 #include <cat/peg.h> #include <cat/buffer.h> #include <cat/emalloc.h> #include <cat/err.h> #include <cat/cpg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char *readfile(const char *filename, uint *fs) { FILE *fp; long fsize; char *buf; long nread; fp = fopen(filename, "r"); if ( fp == NULL ) errsys("opening file %s: ", filename); fseek(fp, 0, SEEK_END); fsize = ftell(fp); rewind(fp); buf = emalloc(fsize + 1); nread = fread(buf, 1, fsize, fp); if ( fsize != nread ) errsys("error reading file: "); *fs = fsize; return buf; } int lgetc(void *p) { return fgetc(p); } int action(int n, struct raw *r, void *aux) { struct cpg_state *cs = aux; char buf[256]; size_t len = r->len; int i; for ( i = 0; i < cs->depth; ++i ) fputc(' ', stderr); if ( len >= sizeof(buf) ) len = sizeof(buf) - 1; memcpy(buf, r->data, len); buf[len] = '\0'; fprintf(stderr, "Primary %d matched on \"%s\"\n", n, buf); return 0; } int main(int argc, char *argv[]) { FILE *pfile; char *buf; char estr[256]; struct peg_grammar_parser pgp; struct peg_grammar peg; struct cpg_state cs; uint fsize; int i; int rv; if ( argc < 3 ) err("usage: %s peg-filename parse-filename\n", argv[0]); buf = readfile(argv[1], &fsize); if ( peg_parse(&pgp, &peg, buf, fsize, 0) < 0 ) err("%s\n", peg_err_string(&pgp, estr, sizeof(estr))); if ( pgp.len != pgp.input_len ) err("PEG parser only parsed to position %u of %u / line %u\n", pgp.len, pgp.input_len, pgp.nlines); printf("Successfully parsed %s\n", argv[1]); for ( i = 0; i < peg.max_nodes; ++i ) { if ( peg.nodes[i].pn_type == PEG_PRIMARY ) { peg.nodes[i].pn_action_cb = &action; peg.nodes[i].pp_action = PEG_ACT_CALLBACK; } } cpg_init(&cs, &peg, lgetc); cs.debug = 1; pfile = fopen(argv[2], "r"); if ( pfile == NULL ) errsys("Error opening %s\n", argv[2]); rv = cpg_parse(&cs, pfile, &cs); if ( rv >= 0 ) printf("%s parsed successfully\n", argv[2]); else printf("%s failed to parse successfully\n", argv[2]); return 0; }
github188/catlib
include/cat/pack.h
<reponame>github188/catlib<gh_stars>1-10 /* * cat/pack.h -- functions to pack and unpack values into byte arrays * * by <NAME> * * Copyright 2003-2017 See accompanying license * */ #ifndef __cat_pack_h #define __cat_pack_h #include <cat/cat.h> /* "eEbhwjBHWJr" e - little endian E - big endian b - byte (8 bits) -- pass in byte_t / uchar / uchar h - half-word (16 bits) -- pass in short / ushort w - word (32 bits) -- pass in long / ulong j - jumbo word (64 bits) -- pass in long long / ullong B - signed 8 bit value -- pass in signed char / schar H - signed 16 bit value -- pass in short W - signed 32 bit value -- pass in long J - signed 64 bit value -- pass in long long r - (struct raw *) follows (pack only) Prefix with a number to indicate a count. In this case source or destination operand is an array of the type indicated. */ /* * Pack values into 'buf' which must be a buffer of length 'len' using 'fmt' * and any remaining arguments. */ size_t pack(void * buf, size_t len, const char *fmt, ... ); /* * Unpack values from 'buf' which must be a buffer of length 'len' using 'fmt' * and any remaining arguments as pointers to extraction locations. */ size_t unpack(void * buf, size_t len, const char *fmt, ... ); /* Return the length of buffer required to pack according to 'fmt' and args */ size_t packlen(const char *fmt, ... ); #define PSIZ_BYTE 1 #define PSIZ_HALF 2 #define PSIZ_WORD 4 #define PSIZ_JUMBO 8 #ifdef CAT_PSIZ_MAX #define PSIZ_MAX CAT_PSIZ_MAX #else /* CAT_PSIZ_MAX */ #define PSIZ_MAX 0x7fffffff #endif /* CAT_PSIZ_MAX */ #if CAT_USE_INLINE #define DECL static inline #else /* CAT_USE_INLINE */ #define DECL static #endif /* CAT_USE_INLINE */ /* These functions all assume that CHAR_BIT == 8 */ /* Convert a 16-bit value from network to host byte order */ DECL uint16_t ntoh16(uint16_t v) { byte_t *p = (byte_t*)&v; return (p[0] << 8) | p[1]; } /* Convert a 16-bit value pointed to by pp from network to host byte order */ DECL uint16_t ntoh16x(void *pp) { byte_t *p = pp; return ((uint16_t)p[0] << 8) | (uint16_t)p[1]; } /* Convert a 16-bit value from host to network byte order */ DECL uint16_t hton16(uint16_t v) { uint16_t ov = 0; byte_t *p = (byte_t*)&ov; *p++ = v >> 8; *p = v; return ov; } /* * Convert a 16-bit value host to network byte order into the location * that pp points to. */ DECL void hton16i(uint16_t v, void *pp) { byte_t *p = (byte_t*)pp; *p++ = v >> 8; *p = v; } /* Convert a 32-bit value from network to host byte order */ DECL uint32_t ntoh32(uint32_t v) { byte_t *p = (byte_t*)&v; return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3]; } /* Convert a 32-bit value pointed to by pp from network to host byte order */ DECL uint32_t ntoh32x(void *pp) { byte_t *p = pp; return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3]; } /* Convert a 32-bit value from host to network byte order */ DECL uint32_t hton32(uint32_t v) { uint32_t ov = 0; byte_t *p = (byte_t*)&ov; *p++ = v >> 24; *p++ = v >> 16; *p++ = v >> 8; *p = v; return ov; } /* * Convert a 32-bit value host to network byte order into the location * that pp points to. */ DECL void hton32i(uint32_t v, void *pp) { byte_t *p = (byte_t*)pp; *p++ = v >> 24; *p++ = v >> 16; *p++ = v >> 8; *p = v; } #if CAT_64BIT /* Convert a 64-bit value from network to host byte order */ DECL uint64_t ntoh64(uint64_t v) { byte_t *p = (byte_t*)&v; return ((uint64_t)p[0] << 56) | ((uint64_t)p[1] << 48) | ((uint64_t)p[2] << 40) | ((uint64_t)p[3] << 32) | ((uint64_t)p[4] << 24) | ((uint64_t)p[5] << 16) | ((uint64_t)p[6] << 8) | (uint64_t)p[7]; } /* Convert a 64-bit value pointed to by pp from network to host byte order */ DECL uint64_t ntoh64x(void *pp) { byte_t *p = pp; return ((uint64_t)p[0] << 56) | ((uint64_t)p[1] << 48) | ((uint64_t)p[2] << 40) | ((uint64_t)p[3] << 32) | ((uint64_t)p[4] << 24) | ((uint64_t)p[5] << 16) | ((uint64_t)p[6] << 8) | (uint64_t)p[7]; } /* Convert a 64-bit value from host to network byte order */ DECL uint64_t hton64(uint64_t v) { uint64_t ov = 0; byte_t *p = (byte_t*)&ov; *p++ = v >> 56; *p++ = v >> 48; *p++ = v >> 40; *p++ = v >> 32; *p++ = v >> 24; *p++ = v >> 16; *p++ = v >> 8; *p = v; return ov; } /* * Convert a 64-bit value host to network byte order into the location * that pp points to. */ DECL void hton64i(uint64_t v, void *pp) { byte_t *p = (byte_t*)pp; *p++ = v >> 56; *p++ = v >> 48; *p++ = v >> 40; *p++ = v >> 32; *p++ = v >> 24; *p++ = v >> 16; *p++ = v >> 8; *p = v; } #endif /* CAT_64BIT */ #endif /* __cat_pack_h */
github188/catlib
src/emalloc.c
<filename>src/emalloc.c<gh_stars>1-10 /* * emalloc.c -- malloc code that aborts the program when out of memory. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cat.h> #include <cat/emalloc.h> #include <cat/err.h> #include <stdlib.h> #include <string.h> static void def_emalloc_abort(char *s, void *omem, size_t size, size_t nmem, int syserr); static emalloc_abort_f abort_func = def_emalloc_abort; static void def_emalloc_abort(char *s, void *omem, size_t size, size_t nmem, int syserr) { errsys(s); } #if CAT_DEBUG_LEVEL <= 0 void * emalloc(size_t size) { void *m; abort_unless(size > 0); if ( !(m = malloc(size)) ) (*abort_func)("emalloc: ", NULL, size, 1, 1); return m; } void * ecalloc(size_t nmemb, size_t size) { void *m; abort_unless(nmemb > 0 && size > 0); if ( !(m = calloc(nmemb, size)) ) (*abort_func)("ecalloc: ", NULL, size, nmemb, 1); return m; } void * erealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) && (size > 0) ) (*abort_func)("erealloc: ", old, size, 1, 1); return m; } char * estrdup(const char *s) { char *ns; abort_unless(s); if ( !(ns = strdup(s)) ) (*abort_func)("estrdup: ", NULL, strlen(s)+1, 1, 1); return ns; } #else /* CAT_DEBUG_LEVEL <= 0 */ void * emalloc(size_t size) { void *m; if ( size == 0 ) (*abort_func)("emalloc: zero size!", NULL, size, 1, 0); if ( !(m = malloc(size)) ) (*abort_func)("emalloc: ", NULL, size, 1, 1); return m; } void * ecalloc(size_t nmemb, size_t size) { void *m; size_t tlen; if ( size == 0 ) (*abort_func)("ecalloc: zero size!", NULL, size, 1, 0); if ( nmemb == 0 ) (*abort_func)("ecalloc: zero nmemb!", NULL, size, 1, 0); if ( (size_t)~0 / nmemb < size ) (*abort_func)("ecalloc: size overflow!", NULL, size, 1, 0); tlen = nmemb * size; if ( !(m = malloc(tlen)) ) (*abort_func)("ecalloc: ", NULL, size, nmemb, 1); memset(m, 0, tlen); return m; } void * erealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) && (size > 0) ) (*abort_func)("erealloc: ", old, size, 1, 1); return m; } char * estrdup(const char *s) { char *ns; if ( s == NULL ) (*abort_func)("estrdup: null source str!", NULL, 0, 1, 0); if ( !(ns = strdup(s)) ) (*abort_func)("estrdup: ", NULL, strlen(s)+1, 1, 1); return ns; } #endif /* CAT_DEBUG_LEVEL <= 0 */
github188/catlib
src/shell.c
/* * shell.c -- Dumb shell interpreter. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/shell.h> #include <cat/str.h> #include <cat/stduse.h> #include <string.h> #include <stdlib.h> #include <ctype.h> /* * Possible TODOs * Allow quoted strings */ static void shell_free_value(struct shell_value *val) { free_f freep; if ( (freep = val->sval_free) ) (*freep)(val->sval_mm, val->sval_ptr); } void shell_env_init(struct shell_env *env, struct shell_cmd_entry *ents, unsigned nents, void *ctx) { uint i; abort_unless(env); abort_unless(ents); env->se_cmds = ents; env->se_ncmds = nents; memset(env->se_vars, 0, CAT_MAX_VARS * sizeof(env->se_vars[0])); /* XXX redundant in most systems */ for ( i = 0 ; i < CAT_MAX_VARS ; ++i ) shell_free_var(&env->se_vars[i]); env->se_ctx = NULL; } int shell_parse(char *str, char **retvar, char *args[CAT_MAX_VARS]) { int nargs = 0; char *tok, *state = str, *first, *eq; *retvar = NULL; /* get the first argument*/ first = str_tok_a(&state, NULL); /* if there was none, return 0: a noop */ if ( !first ) return 0; /* check if the first token was a variable assignment */ /* proper form is "VARNAME= " */ if ( (eq = strchr(first, '=')) != NULL ) { /* check that the variable name does not start with $ */ if ( first[0] == '$' ) return -1; /* get rid of the = */ *eq = '\0'; *retvar = first; if ( *(eq + 1) != '\0' ) { args[0] = eq + 1; ++nargs; } } else { /* if no variable assignment, first token was first argument */ args[0] = first; ++nargs; } /* read out the rest of the arguments */ while ( nargs < CAT_MAX_CMD_ARGS ) { tok = str_tok_a(&state, NULL); if ( !tok ) { if ( *state == '\0' ) break; else goto err; } args[nargs++] = tok; } /* check if there are more than CAT_MAX_CMD_ARGS and return an error */ /* if there are */ if ( (nargs == CAT_MAX_CMD_ARGS) && (tok = str_tok_a(&state, NULL)) ) { goto err; } return nargs; err: if ( *retvar ) *retvar = NULL; return -1; } static struct shell_var *new_var(struct shell_env *env, const char *vname) { struct shell_var *var, *end; size_t slen; abort_unless(env && vname); abort_unless(vname[0] != '\0'); slen = strlen(vname); if ( slen > CAT_MAX_VARNLEN - 1 ) return NULL; for ( var = env->se_vars, end = var + CAT_MAX_VARS ; var < end ; ++var ) if ( var->sv_name[0] == '\0' ) { memcpy(var->sv_name, vname, slen + 1); return var; } return NULL; } struct shell_var *shell_find_var(struct shell_env *env, const char *name) { struct shell_var *var, *end; abort_unless(env && name); /* simple linear search for the variable entry */ for ( var = env->se_vars, end = var + CAT_MAX_VARS ; var < end ; ++var ) if ( strcmp(var->sv_name, name) == 0 ) return var; return NULL; } int shell_run(struct shell_env *env, char *cmdstr) { char *args[CAT_MAX_CMD_ARGS] = { 0 }; char *retvar; int nargs, rv = -1; struct shell_value result; struct shell_cmd_entry *cmd, *end; struct shell_var *var = NULL; /* parse the line into arguments and possibly a return variable name */ if ( (nargs = shell_parse(cmdstr, &retvar, args)) < 0 ) return nargs; /* if there is a return variable name look it up */ if ( retvar ) { var = shell_find_var(env, retvar); if ( !var ) { var = new_var(env, retvar); if ( !var ) return -1; } } /* if there were no arguments it is either a noop or a variable */ /* clear operation: handle each accordingly */ /* XXX note that this can cause a memory leak if not careful :( */ /* We need to see how to address this: maybe allow variables to be */ /* reference counted pointers which are automatically destructed */ /* this is a TODO */ if ( nargs == 0 ) { if ( var ) shell_free_var(var); return 0; } /* find the actual command and run it */ for ( cmd = env->se_cmds, end = cmd+env->se_ncmds; cmd < end ; ++cmd ) { if ( strcmp(cmd->cmd_name, args[0]) == 0 ) { /* found it */ /* run the command, set the var, return success */ rv = (*cmd->cmd_func)(env, nargs, args, &result); if ( var && rv >= 0 ) { shell_free_value(&var->sv_value); var->sv_value = result; } break; } } return rv; } int shell_is_var(const char *name) { abort_unless(name); return name[0] == '$'; } void shell_free_var(struct shell_var *sv) { struct shell_value *val; abort_unless(sv); val = &sv->sv_value; shell_free_value(val); sv->sv_name[0] = '\0'; val->sval_type = SVT_NIL; val->sval_free = NULL; val->sval_mm = NULL; val->sval_int = 0; } int shell_arg2int(struct shell_env *env, const char *str, int *rv) { struct shell_var *v; char *endp; int ival; abort_unless(env && str && rv); if ( shell_is_var(str) ) { v = shell_find_var(env, str+1); if ( !v || v->sv_value.sval_type != SVT_INT ) return -1; *rv = v->sv_value.sval_int; } else { ival = strtol(str, &endp, 0); if ( str == endp ) return -1; *rv = ival; } return 0; } int shell_arg2uint(struct shell_env *env, const char *str, uint *rv) { struct shell_var *v; char *endp; uint uval; abort_unless(env && str && rv); if ( shell_is_var(str) ) { v = shell_find_var(env, str+1); if ( !v || v->sv_value.sval_type != SVT_UINT ) return -1; *rv = v->sv_value.sval_uint; } else { uval = strtoul(str, &endp, 0); if ( str == endp ) return -1; *rv = uval; } return 0; } int shell_arg2dbl(struct shell_env *env, const char *str, double *rv) { struct shell_var *v; char *endp; double dval; abort_unless(env && str && rv); if ( shell_is_var(str) ) { v = shell_find_var(env, str+1); if ( !v || v->sv_value.sval_type != SVT_DOUBLE ) return -1; *rv = v->sv_value.sval_dbl; } else { dval = strtod(str, &endp); if ( str == endp ) return -1; *rv = dval; } return 0; } int shell_arg2str(struct shell_env *env, char *str, char **rv) { struct shell_var *v; abort_unless(env && str && rv); if ( shell_is_var(str) ) { v = shell_find_var(env, str+1); if ( !v || v->sv_value.sval_type != SVT_STRING ) return -1; *rv = v->sv_value.sval_ptr; } else { *rv = str; } return 0; } int shell_arg2ptr(struct shell_env *env, char *str, void **rv) { struct shell_var *v; abort_unless(env && str && rv); if ( shell_is_var(str) ) { v = shell_find_var(env, str+1); if ( !v || v->sv_value.sval_type != SVT_PTR ) return -1; *rv = v->sv_value.sval_ptr; } else { char *endp; ulong ul = strtoul(str, &endp, 0); if ( str == endp ) return -1; *rv = (void *)ul; } return 0; }
github188/catlib
include/cat/cpg.h
#ifndef __cpg_h #define __cpg_h #include <cat/peg.h> struct cpg_cursor { uint i; uint line; }; struct cpg_state { int debug; int depth; void *in; struct cpg_cursor cur; uchar *buf; uint buflen; uint readidx; uint eof; int (*getc)(void *in); struct peg_grammar *peg; }; int cpg_init(struct cpg_state *state, struct peg_grammar *peg, int (*getc)(void *in)); void cpg_set_debug_level(struct cpg_state *state, int level); int cpg_parse(struct cpg_state *state, void *in, void *aux); void cpg_reset(struct cpg_state *state); void cpg_fini(struct cpg_state *state); #endif /* __cpg_h */
github188/catlib
src/aux.c
<reponame>github188/catlib /* * aux.c -- funtions needed by most or all modules * * by <NAME> * * Copyright 2003-2014 See accompanying license * */ #include <cat/cat.h> #include <cat/aux.h> #include <stdlib.h> #include <string.h> int cmp_ptr(const void *k1, const void *k2) { return ((char *)k1 - (char *)k2); } int cmp_str(const void *k1, const void *k2) { return strcmp(k1, k2); } int cmp_raw(const void *k1p, const void *k2p) { const struct raw *k1 = k1p; const struct raw *k2 = k2p; if ( k1->len > k2->len ) return -1; else if ( k1->len < k2->len ) return 1; else return memcmp(k1->data, k2->data, k1->len); } int cmp_intptr(const void *k1, const void *k2) { return ptr2int(k1) - ptr2int(k2); } int cmp_uintptr(const void *k1, const void *k2) { uintptr_t v1 = ptr2uint(k1); uintptr_t v2 = ptr2uint(k2); if ( v1 < v2 ) return -1; else if ( v1 == v2 ) return 0; else return 1; } ulong uldivmod(ulong dend, ulong dsor, int div) { ulong r = 0; int i; if ( dsor == 0 ) return 0xFFFFFFFFul; for ( i = 0; i < 32; ++i ) { r = (r << 1) | (dend >> 31); dend = dend << 1; if ( r >= dsor ) { r -= dsor; dend += 1; } } return div ? dend : r; } #if CAT_HAS_LONGLONG ullong ulldivmod(ullong dend, ullong dsor, int div) { ullong r = 0; int i; if ( dsor == 0 ) return 0xFFFFFFFFFFFFFFFFull; for ( i = 0; i < 64; ++i ) { r = (r << 1) | (dend >> 63); dend = dend << 1; if ( r >= dsor ) { r -= dsor; dend += 1; } } return div ? dend : r; } #endif /* CAT_HAS_LONGLONG */
github188/catlib
src/catstr.c
/* * catstr.c -- application level strings * * by <NAME> * * Copyright 2007-2012 See accompanying license * */ #include <cat/catstr.h> #include <cat/str.h> #include <cat/grow.h> #include <cat/match.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #if CAT_HAS_POSIX #include <errno.h> #include <unistd.h> #endif /* CAT_HAS_POSIX */ static struct memmgr *cs_mmp = &stdmm; #define CKCS(cs) \ if (!cs || !cs->cs_data || \ (cs->cs_size > CS_MAXLEN) || (cs->cs_dlen > cs->cs_size)) \ return CS_ERROR; #define CKCSP(cs) \ if (!cs || !cs->cs_data || \ (cs->cs_size > CS_MAXLEN) || (cs->cs_dlen > cs->cs_size)) \ return NULL; #define CKCSI(cs) \ if (!cs || !cs->cs_data || \ (cs->cs_size > CS_MAXLEN) || (cs->cs_dlen > cs->cs_size)) \ return -1; #define CKCSN(cs) \ if (!cs || !cs->cs_data || \ (cs->cs_size > CS_MAXLEN) || (cs->cs_dlen > cs->cs_size)) \ return; void cs_init(struct catstr *cs, char *data, size_t size, int data_is_str) { size_t dlen = 0; if ( data_is_str && data ) dlen = strlen(data); if ( size > CS_MAXLEN || size < 1 || dlen > size - 1) { cs->cs_size = 0; cs->cs_dynamic = 0; cs->cs_data = NULL; return; } cs->cs_size = size - 1; cs->cs_data = data; cs->cs_dlen = dlen; cs->cs_data[dlen] = '\0'; } void cs_clear(struct catstr *cs) { CKCSN(cs); cs->cs_dlen = 0; cs->cs_data[0] = '\0'; } size_t cs_set_cstr(struct catstr *cs, const char *cstr) { size_t cstrlen; abort_unless(cstr); CKCS(cs); cstrlen = strlen(cstr); if ( cstrlen > CS_MAXLEN || cstrlen > cs->cs_size ) return CS_ERROR; cs->cs_dlen = cstrlen; memmove(cs->cs_data, cstr, cstrlen); cs->cs_data[cstrlen] = '\0'; return cstrlen; } size_t cs_trunc_d(struct catstr *cs, size_t len) { CKCS(cs); if ( len < cs->cs_dlen ) { cs->cs_dlen = len; cs->cs_data[len] = '\0'; return len; } else { return cs->cs_dlen; } } size_t cs_concat_d(struct catstr *dst, const struct catstr *src) { size_t tomove, tlen; CKCS(dst); CKCS(src); if ( CS_MAXLEN - dst->cs_dlen > src->cs_dlen ) return CS_ERROR; tomove = dst->cs_size - dst->cs_dlen; if ( tomove > src->cs_dlen ) tomove = src->cs_dlen; tlen = tomove + dst->cs_dlen; memmove(dst->cs_data + dst->cs_dlen, src->cs_data, tomove); dst->cs_dlen += tomove; dst->cs_data[dst->cs_dlen] = '\0'; return tlen; } size_t cs_copy_d(struct catstr *dst, struct catstr *src) { size_t tocopy; CKCS(dst); CKCS(src); tocopy = src->cs_dlen; if ( tocopy >= dst->cs_size ) tocopy = dst->cs_size - 1; memmove(dst->cs_data, src->cs_data, tocopy); dst->cs_data[tocopy] = '\0'; dst->cs_dlen = tocopy; return tocopy; } size_t cs_format_d(struct catstr *dst, const char *fmt, ...) { va_list ap; int rv; abort_unless(fmt); va_start(ap, fmt); rv = str_vfmt(dst->cs_data, dst->cs_size, fmt, ap); va_end(ap); if ( rv < 0 ) { dst->cs_dlen = 0; dst->cs_data[0] = '\0'; return CS_ERROR; } dst->cs_dlen = rv; if ( rv > dst->cs_size ) dst->cs_dlen = dst->cs_size; return (size_t)rv; } size_t cs_find_cc(const struct catstr *cs, char ch) { const char *cp; const char *end; size_t off = 0; CKCS(cs); cp = cs->cs_data; end = cp + cs->cs_dlen; while ( cp < end && *cp != ch ) { ++cp; ++off; } if ( cp == end ) return CS_NOTFOUND; else return off; } size_t cs_span_cc(const struct catstr *cs, const char *accept) { const char *cp; const char *ap; const char *end; size_t off = 0; CKCS(cs); cp = cs->cs_data; end = cp + cs->cs_dlen; while ( cp < end ) { for ( ap = (const char *)accept ; *ap != '\0' ; ++ap ) if ( *cp == *ap ) break; if ( *ap == '\0' ) break; ++cp; ++off; } return off; } size_t cs_cspan_cc(const struct catstr *cs, const char *reject) { const char *cp; const char *rp; const char *end; size_t off = 0; CKCS(cs); cp = cs->cs_data; end = cp + cs->cs_dlen; while ( cp < end ) { for ( rp = (const char *)reject ; *rp != '\0' ; ++rp ) if ( *cp == *rp ) goto done; ++cp; ++off; } done: return off; } size_t cs_find_uc(const struct catstr *cs, const char *utf8ch) { size_t off = 0, dlen; int scs, fcs, i; const char *fcp = (const char *)utf8ch; const char *scp; CKCS(cs); abort_unless(utf8ch); scp = (const char *)cs->cs_data; dlen = cs->cs_dlen; if ( (fcs = utf8_nbytes(*fcp)) < 0 ) return CS_ERROR; while ( off < dlen ) { if ( (scs = utf8_nbytes(scp[off])) < 0 ) return CS_ERROR; if ( fcs != scs ) { off += scs; continue; } for ( i = 0 ; i < scs ; ++i ) if ( scp[off + i] != fcp[i] ) break; if ( i == scs ) off += scs; else break; } if ( off == dlen ) return CS_NOTFOUND; else return off; } static int utf8match(const char *c1, const char *c2) { int c1b, c2b; abort_unless(c1 && c2); c1b = utf8_nbytes(*c1); c2b = utf8_nbytes(*c2); if ( c1b == CS_ERROR || c2b == CS_ERROR ) return -1; while ( c1b > 0 ) { if ( *c1 != *c2 ) return c2b; --c1b; ++c1; ++c2; } return 0; } size_t cs_span_uc(const struct catstr *cs, const char *utf8ch, int nc) { size_t off = 0, dlen, u8off; int i, mr, uclen; const char *fcp = (const char *)utf8ch; const char *scp; CKCS(cs); abort_unless(utf8ch && nc > 0); scp = (const char *)cs->cs_data; dlen = cs->cs_dlen; while ( off < dlen ) { for ( u8off = 0, i = 0 ; i < nc ; ++i ) { mr = utf8match(&scp[off], &fcp[u8off]); if ( mr < 0 ) return CS_ERROR; if ( mr == 0 ) break; u8off += mr; } if ( i == nc ) break; uclen = utf8_nbytes(scp[off]); if ( uclen < 0 ) return CS_ERROR; off += (size_t)uclen; } return off; } size_t cs_cspan_uc(const struct catstr *cs, const char *utf8ch, int nc) { size_t off = 0, dlen, u8off; int i, mr; const char *fcp = (const char *)utf8ch; const char *scp; CKCS(cs); abort_unless(utf8ch && nc > 0); scp = (const char *)cs->cs_data; dlen = cs->cs_dlen; while ( off < dlen ) { for ( u8off = 0, i = 0 ; i < nc ; ++i ) { mr = utf8match(&scp[off], &fcp[u8off]); if ( mr < 0 ) return CS_ERROR; if ( mr == 0 ) goto out; u8off += (size_t)mr; } off += utf8_nbytes(scp[off]); } out: return off; } size_t cs_find(const struct catstr *findin, const struct catstr *find) { struct raw praw; CKCS(findin); CKCS(find); praw.len = find->cs_dlen; praw.data = (char *)find->cs_data; return cs_find_raw(findin, &praw); } size_t cs_find_str(const struct catstr *findin, const char *s) { struct raw praw; CKCS(findin); praw.len = strlen(s); praw.data = (char *)s; return cs_find_raw(findin, &praw); } size_t cs_find_raw(const struct catstr *findin, const struct raw *r) { struct bmpat bmp; ulong off; int rv; struct raw rstr; CKCS(findin); /* TODO: fix bm_* so it uses size_t */ abort_unless(r->len <= (ulong)~0); bm_pinit_lite(&bmp, (struct raw *)r); rstr.len = findin->cs_dlen; rstr.data = (char *)findin->cs_data; rv = bm_match(&rstr, &bmp, &off); if ( rv < 0 ) return CS_NOTFOUND; else return off; } struct catstr *cs_copy_from_chars(const char *s) { size_t slen; struct catstr *cs; slen = strlen(s); if ( (cs = cs_alloc(slen)) == NULL ) return NULL; memmove(cs->cs_data, s, slen); cs->cs_dlen = slen; cs->cs_data[slen] = '\0'; return cs; } struct catstr *cs_format(const char *fmt, ...) { va_list ap; int rv, rv2; struct catstr *cs; char dummy[1]; abort_unless(fmt); va_start(ap, fmt); rv = str_vfmt(dummy, sizeof(dummy), fmt, ap); va_end(ap); if ( (rv < 0) || (rv + 1 <= 0) ) return NULL; if ( (cs = cs_alloc(rv)) == NULL ) return NULL; cs->cs_dlen = rv; va_start(ap, fmt); rv2 = str_vfmt((char *)cs->cs_data, rv+1, fmt, ap); va_end(ap); abort_unless(rv == rv2); return cs; } int cs_concat(struct catstr *dst, struct catstr *src) { size_t newlen; CKCSI(dst); CKCSI(src); if ( CS_MAXLEN - dst->cs_dlen > src->cs_dlen ) return -1; newlen = dst->cs_dlen + src->cs_dlen; if ( cs_grow(dst, newlen) < 0 ) return -1; memmove(dst->cs_data + dst->cs_dlen, src->cs_data, dst->cs_dlen); dst->cs_dlen = newlen; dst->cs_data[newlen] = '\0'; return 0; } int cs_grow(struct catstr *cs, size_t minlen) { byte_t *csp; size_t tlen, olen; CKCSI(cs); abort_unless(minlen <= CS_MAXLEN); abort_unless(cs->cs_dynamic); csp = (byte_t *)&cs->cs_data; tlen = olen = cs_alloc_size(cs->cs_size); if ( mm_grow(cs_mmp, &csp, &tlen, cs_alloc_size(minlen)) < 0 ) return -1; abort_unless(tlen >= olen); cs->cs_data = csp; cs->cs_size = tlen - 1; return 0; } int cs_addch(struct catstr *cs, char ch) { CKCSI(cs); if ( cs->cs_dlen >= cs->cs_size ) { if ( cs->cs_dynamic ) { if ( cs_grow(cs, cs->cs_dlen + 1) < 0 ) return -1; } else { return -1; } } cs->cs_data[cs->cs_dlen++] = ch; cs->cs_data[cs->cs_dlen] = '\0'; return 0; } struct catstr *cs_substr(const struct catstr *orig, size_t off, size_t len) { struct catstr *cs; size_t remaining; CKCSP(orig); /* allocate empty string */ if ( off >= orig->cs_dlen ) return cs_alloc(0); remaining = orig->cs_dlen - off; if ( remaining > len ) len = remaining; if ( (cs = cs_alloc(len)) == NULL ) return NULL; cs->cs_dlen = len; memmove(cs->cs_data, orig->cs_data + off, len); cs->cs_data[len] = '\0'; return cs; } size_t cs_rev_off(const struct catstr *cs, size_t roff) { CKCS(cs); if ( roff > cs->cs_dlen ) roff = cs->cs_dlen; return cs->cs_dlen - roff; } #if CAT_HAS_POSIX int cs_fd_readline(int fd, struct catstr **csp) { struct catstr *cs; char *p; int eol = 0, rv; size_t sofar = 0; abort_unless(csp); if ( (cs = cs_alloc(128)) == NULL ) return -1; while ( !eol ) { p = cs->cs_data + sofar; if ( (rv = read(fd, p, 1)) < 1 ) { if ( rv == 0 ) { eol = 1; } else { if ( errno == EINTR ) continue; cs_free(cs); *csp = NULL; return -1; } } else if ( *p == '\n' ) { ++sofar; eol = 1; } else { ++sofar; if ( cs_isfull(cs) ) { if ( cs_grow(cs, cs->cs_size * 2) < 0 ) { cs_free(cs); *csp = NULL; return -1; } } abort_unless(cs); } } cs->cs_dlen = sofar; cs->cs_data[sofar] = '\0'; *csp = cs; return 0; } int cs_file_readline(FILE *file, struct catstr **csp) { struct catstr *cs; char *p, *trav; int eol = 0; size_t sofar = 0, avail; abort_unless(csp); if ( (cs = cs_alloc(128)) == NULL ) return -1; while ( !eol ) { p = cs->cs_data + sofar; avail = cs->cs_size - sofar; abort_unless(avail > 2); if ( fgets((char *)p, avail+1, file) == NULL ) { cs_free(cs); *csp = NULL; return -1; } for ( trav = p ; trav < p + avail; ++trav ) if ( *trav == '\n' ) break; if ( trav != p + avail ) { eol = 1; abort_unless(trav - p + 1 <= avail); cs->cs_dlen = sofar + (trav - p + 1); /* guaranteed by fgets() */ abort_unless(cs->cs_data[cs->cs_dlen] == '\0'); } else { /* guaranteed by fgets() */ abort_unless(p[avail] == '\0'); sofar += avail; if ( cs_grow(cs, cs->cs_size * 2) < 0 ) { cs_free(cs); *csp = NULL; return -1; } } } *csp = cs; return 0; } #endif /* CAT_HAS_POSIX */ struct catstr *cs_alloc(size_t len) { struct catstr *cs; if ( len > CS_MAXLEN ) return NULL; if ( (cs = mem_get(cs_mmp, sizeof(*cs))) == NULL ) return NULL; if ( (cs->cs_data = mem_get(cs_mmp, cs_alloc_size(len))) == NULL ) { mem_free(cs_mmp, cs); return NULL; } cs->cs_size = len; cs->cs_dlen = 0; cs->cs_data[0] = '\0'; cs->cs_dynamic = 1; return cs; } void cs_free(struct catstr *cs) { CKCSN(cs); abort_unless(cs->cs_dynamic); mem_free(cs_mmp, cs->cs_data); mem_free(cs_mmp, cs); } void cs_setmm(struct memmgr *mm) { abort_unless(mm); cs_mmp = mm; }
github188/catlib
test/testcrc.c
<filename>test/testcrc.c<gh_stars>1-10 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cat/crc.h> #include <cat/err.h> const char check_vec[] = "123456789"; #define CRC32_CHECK_VAL 0xCBF43926ul #define CRC32C_CHECK_VAL 0xE3069283ul void crc32_file(const char *s) { FILE *fp; char buf[1024]; size_t n; ulong crc; crc = crc32_start(); fp = fopen(s, "r"); if ( !fp ) errsys("Unable to open file %s", s); do { n = fread(buf, 1, sizeof(buf), fp); if ( n ) crc = crc32_step(buf, n, crc); } while ( n == sizeof(buf) ); if ( ferror(fp) ) errsys("Error reading file %s", fp); printf("CRC32 for file %s is 0x%08lx\n", s, crc32_finish(crc)); } static void check_crc32_1bit(void) { ulong crc; uchar byte = 1; struct crc32tab ctab; crc32t_be_init(&ctab, CAT_CRC32_POLY); crc = crc32t_be(&ctab, &byte, 1, 0); fprintf(stderr, "CRC32 of 0x01 is 0x%08lx. Should be 0x%08lx\n", crc, (ulong)CAT_CRC32_POLY); if ( crc == CAT_CRC32_POLY ) fprintf(stderr, "PASSED\n"); else fprintf(stderr, "FAILED\n"); } static ulong reverse(ulong x) { x = ((x >> 16) & 0xFFFF) | (x << 16); x = ((x >> 8) & 0x00FF00FF) | ((x << 8) & 0xFF00FF00); x = ((x >> 4) & 0x0F0F0F0F) | ((x << 4) & 0xF0F0F0F0); x = ((x >> 2) & 0x33333333) | ((x << 2) & 0xCCCCCCCC); x = ((x >> 1) & 0x55555555) | ((x << 1) & 0xAAAAAAAA); return x; } static ulong dumbcrc32(const void *voidp, size_t len) { const byte_t *p; int i; ulong crc = 0xFFFFFFFF; for ( p = voidp; *p; p++ ) { for ( i = 0; i < 8; i++ ) { if ( ((*p >> i) ^ (crc >> 31)) & 1 ) crc = (crc << 1) ^ CAT_CRC32_POLY; else crc <<= 1; crc &= 0xFFFFFFFF; } } return reverse(crc) ^ 0xFFFFFFFF; } static void check_crc32_dumb(void) { ulong crc; crc = dumbcrc32(check_vec, strlen(check_vec)); fprintf(stderr, "Dumb CRC32 of \"%s\" is 0x%08lx. Should be 0x%08lx\n", check_vec, crc, CRC32_CHECK_VAL); if ( crc == CRC32_CHECK_VAL ) fprintf(stderr, "PASSED\n"); else fprintf(stderr, "FAILED\n"); } static void check_crc32(void) { ulong crc; crc = crc32(check_vec, strlen(check_vec)); fprintf(stderr, "CRC32 of \"%s\" is 0x%08lx. Should be 0x%08lx\n", check_vec, crc, CRC32_CHECK_VAL); if ( crc == CRC32_CHECK_VAL ) fprintf(stderr, "PASSED\n"); else fprintf(stderr, "FAILED\n"); } static void check_crc32c(void) { ulong crc = 0xFFFFFFFF; struct crc32tab ctab; crc32t_le_init(&ctab, CAT_CRC32C_POLY); crc = crc32t_le(&ctab, check_vec, strlen(check_vec), crc); crc ^= 0xFFFFFFFF; fprintf(stderr, "CRC32c of \"%s\" is 0x%08lx. Should be 0x%08lx\n", check_vec, crc, CRC32C_CHECK_VAL); if ( crc == CRC32C_CHECK_VAL ) fprintf(stderr, "PASSED\n"); else fprintf(stderr, "FAILED\n"); } int main(int argc, char *argv[]) { if ( argc == 2 && strcmp(argv[1], "-h") == 0 ) { fprintf(stderr, "usage: %s [file]\n", argv[0]); exit(1); } check_crc32_1bit(); check_crc32_dumb(); check_crc32(); check_crc32c(); if ( argc > 1 ) crc32_file(argv[1]); return 0; }
github188/catlib
src/stduse.c
/* * stduse.c -- application level nicities built on the rest of the catlib * * by <NAME> * * Copyright 2007-2015 See accompanying license * */ #include <cat/cat.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <cat/err.h> #include <cat/stduse.h> #include <cat/grow.h> #include <cat/bitset.h> #include <cat/emalloc.h> #if CAT_HAS_POSIX #include <sys/time.h> #endif /* CAT_HAS_POSIX */ #ifndef va_copy #ifndef __va_copy #error "No va_copy() or __va_copy() macros!" #else /* __va_copy */ #define va_copy(dst, src) __va_copy(dst, src) #endif /* __va_copy */ #endif /* va_copy */ #define SMAX (~(size_t)0) /* Memory operations */ static void * std_ealloc(struct memmgr *mm, size_t size) { void *m; abort_unless(mm && size > 0); if ( !(m = malloc(size)) ) errsys("malloc: "); return m; } static void * std_eresize(struct memmgr *mm, void *old, size_t newsize) { void *m; abort_unless(mm && newsize >= 0); if ( !(m = realloc(old, newsize)) && (newsize > 0) ) errsys("realloc: "); return m; } static void std_efree(struct memmgr *mm, void *p) { free(p); } struct memmgr estdmm = { std_ealloc, std_eresize, std_efree, &estdmm }; union raw_u { struct raw raw; cat_align_t align; }; struct raw *erawdup(struct raw const * const r) { size_t s; struct raw *rnew; if ( !r || !r->data || !r->len ) err("erawdup: invalid raw provided\n"); s = r->len + sizeof(union raw_u); if ( s < sizeof(union raw_u) ) err("erawdup: integer overflow\n"); rnew = emalloc(s); rnew->len = r->len; rnew->data = (byte_t *)((union raw_u *)rnew + 1); memcpy(rnew->data, r->data, r->len); return rnew; } char *erawsdup(struct raw const * const r) { char *s; if ( r == NULL || r->data == NULL || r->len + 1 < r->len ) err("erawdup: invalid raw provided\n"); s = emalloc(r->len + 1); memmove(s, r->data, r->len); s[r->len] = '\0'; return s; } /* List operations */ static struct clist_node *cl_def_node_alloc(struct clist *list) { return malloc(sizeof(struct clist_node)); } static void cl_def_node_free(struct clist *list, struct clist_node *node) { free(node); } static struct clist_attr cl_def_attr = { cl_def_node_alloc, cl_def_node_free, { 0 } }; struct clist *cl_new(const struct clist_attr *attr, int abort_on_fail) { struct clist *list; if ( attr == NULL ) attr = &cl_def_attr; abort_unless(attr->node_alloc != NULL); abort_unless(attr->node_free != NULL); list = malloc(sizeof(*list)); if ( list == NULL ) { if ( abort_on_fail ) err("cl_new: unable to allocate list\n"); return NULL; } l_init(&list->base.entry); list->base.list = NULL; list->fill = 0; list->abort_on_fail = abort_on_fail; list->node_alloc = attr->node_alloc; list->node_free = attr->node_free; list->ctx = attr->ctx; return list; } void cl_free(struct clist *list) { while ( !cl_isempty(list) ) cl_del(list, cl_first(list)); free(list); } int cl_isempty(struct clist *list) { return list->fill == 0; } size_t cl_fill(struct clist *list) { return list->fill; } int cl_ins(struct clist *list, struct clist_node *prev, void *val) { struct clist_node *node; node = (*list->node_alloc)(list); if ( node == NULL ) { if ( list->abort_on_fail ) err("cl_ins: unable to allocate NULL\n"); return -1; } if ( prev == NULL ) prev = cl_head(list); l_ins(&prev->entry, &node->entry); node->list = list; node->data = val; list->fill += 1; return 0; } void *cl_del(struct clist *list, struct clist_node *node) { void *p = node->data; if ( node->list != NULL ) { l_rem(&node->entry); node->list->fill -= 1; node->list = NULL; } (*list->node_free)(list, node); return p; } int cl_enq(struct clist *list, void *val) { return cl_ins(list, cl_last(list), val); } void *cl_deq(struct clist *list) { if ( list->fill == 0 ) return NULL; return cl_del(list, cl_first(list)); } int cl_push(struct clist *list, void *val) { return cl_ins(list, NULL, val); } void *cl_pop(struct clist *list) { if ( list->fill == 0 ) return NULL; return cl_del(list, cl_first(list)); } void *cl_top(struct clist *list) { if ( list->fill == 0 ) return NULL; return cl_first(list)->data; } void cl_apply(struct clist *list, apply_f f, void *arg) { struct clist_node *cur, *next; abort_unless(list != NULL); abort_unless(f != NULL); for ( cur = cl_head(list) ; cur != cl_end(list) ; cur = next ) { next = cl_next(cur); (*f)(cur, arg); } } /* String functions */ char * str_copy_a(const char *src) { size_t len; char *newstr; len = strlen(src) + 1; abort_unless(len > 0); newstr = emalloc(len); return memmove(newstr, src, len); } char * str_cat_a(const char *first, const char *second) { size_t len1, len2, tlen; char *newstr; len1 = strlen(first); len2 = strlen(second); abort_unless((size_t)~0 - 1 >= len1); abort_unless((size_t)~0 - 1 - len1 >= len2); tlen = len1 + len2 + 1; newstr = emalloc(tlen); memmove(newstr, first, len1); memmove(newstr + len1, second, len2 + 1); return newstr; } char * str_fmt_a(const char *fmt, ...) { va_list ap; char *newstr; va_start(ap, fmt); newstr = str_vfmt_a(fmt, ap); va_end(ap); return newstr; } char * str_vfmt_a(const char *fmt, va_list ap) { int len; char *buf; va_list oap; abort_unless(fmt); va_copy(oap, ap); len = str_vfmt(NULL, 0, fmt, ap); if ( len < 0 ) return NULL; abort_unless((size_t)~0 - 1 >= len); buf = emalloc(len + 1); len = str_vfmt(buf, len+1, fmt, oap); abort_unless(len >= 0); return buf; } static int is_space(const char *s, const char *wschars) { abort_unless(s && wschars); /* TODO make UTF8-compliant */ while ( *wschars != '\0' ) if ( *wschars++ == *s ) return 1; return 0; } char * str_tok_a(char **start, const char *wschars) { char *s, *e, *rs; size_t tlen; if ( !wschars ) wschars = " \t\r\n"; if ( !start || !*start ) return NULL; s = *start; while ( *s != '\0' && is_space(s, wschars) ) s++; if ( *s == '\0' ) { *start = s; return NULL; } e = s + 1; while ( *e != '\0' && !is_space(e, wschars) ) e++; tlen = e - s; rs = emalloc(tlen+1); memmove(rs, s, tlen); rs[tlen] = '\0'; *start = e; return rs; } /* Delta list functions */ void * cdl_data(struct dlist *nodep) { abort_unless(nodep); return container(nodep, struct cdlist, entry)->data; } void cdl_set(struct dlist *nodep, void *data) { abort_unless(nodep); container(nodep, struct cdlist, entry)->data = data; } struct dlist * cdl_new(cat_time_t t, void *data) { struct cdlist *node; node = emalloc(sizeof(*node)); dl_init(&node->entry, t); node->data = data; return &node->entry; } void * cdl_free(struct dlist * nodep) { void *old = NULL; struct cdlist *node; if ( nodep ) { node = container(nodep, struct cdlist, entry); old = node->data; free(node); } return old; } /* Used by all xxx_apply() functions to store the real apply function */ /* when wrapping with a new apply function to get the data pointer. */ struct apply_ctx { void *ctx; apply_f f; }; /* Hash table functions */ static struct chnode *cht_node_alloc_skey(struct chtab *t, void *key) { char *kcpy; struct chnode *chn; kcpy = strdup(key); if ( kcpy == NULL ) return NULL; chn = malloc(sizeof(*chn)); if ( chn == NULL ) { free(kcpy); return NULL; } ht_ninit(&chn->node, kcpy); return chn; } static void cht_node_free_skey(struct chtab *t, struct chnode *chn) { abort_unless(chn != NULL); abort_unless(chn->node.key != NULL); free(chn->node.key); free(chn); } struct chtab_attr cht_std_attr_skey = { &cmp_str, &ht_shash, 0, &cht_node_alloc_skey, &cht_node_free_skey, NULL, }; static struct chnode *cht_node_alloc_rkey(struct chtab *t, void *key) { struct chnode *chn; struct raw *rkey = key; struct raw *rnode; abort_unless(rkey != NULL); chn = malloc(CAT_ALIGN_SIZE(sizeof(*chn)) + CAT_ALIGN_SIZE(sizeof(*rnode)) + rkey->len); if ( chn == NULL ) return NULL; rnode = (struct raw *)((byte_t *)chn + CAT_ALIGN_SIZE(sizeof(*chn))); rnode->len = rkey->len; if ( rkey->len > 0 ) { rnode->data = (byte_t *)rnode + CAT_ALIGN_SIZE(sizeof(*rnode)); memmove(rnode->data, rkey->data, rkey->len); } else { rnode->data = NULL; } ht_ninit(&chn->node, rnode); return chn; } static void cht_node_free_rkey(struct chtab *t, struct chnode *chn) { free(chn); } struct chtab_attr cht_std_attr_rkey = { &cmp_raw, &ht_rhash, 0, &cht_node_alloc_rkey, &cht_node_free_rkey, NULL, }; static struct chnode *cht_node_alloc_pkey(struct chtab *t, void *key) { struct chnode *chn; chn = malloc(sizeof(*chn)); if ( chn == NULL ) return NULL; ht_ninit(&chn->node, key); return chn; } static void cht_node_free_pkey(struct chtab *t, struct chnode *chn) { free(chn); } struct chtab_attr cht_std_attr_pkey = { &cmp_ptr, &ht_phash, 0, &cht_node_alloc_pkey, &cht_node_free_pkey, NULL, }; struct chtab_attr cht_std_attr_bkey = { NULL, /* Must be supplied by user */ NULL, /* Must be supplied by user */ 0, /* Must be supplied by user */ &cht_node_alloc_pkey, &cht_node_free_pkey, NULL, }; struct chtab *cht_new(size_t nbkts, struct chtab_attr *attr, void *hctx, int abort_on_fail) { size_t n; size_t tsize; size_t hctx_size; struct chtab *t; void *new_hctx; struct hnode **buckets; if ( attr == NULL ) attr = &cht_std_attr_skey; abort_unless(attr->kcmp != NULL); abort_unless(attr->hash != NULL); abort_unless(attr->node_alloc != NULL); abort_unless(attr->node_free != NULL); tsize = CAT_ALIGN_SIZE(sizeof(struct chtab)); hctx_size = CAT_ALIGN_SIZE(attr->hctx_size); abort_unless(hctx_size >= attr->hctx_size); abort_unless(SMAX - hctx_size >= tsize); n = hctx_size + tsize; abort_unless((SMAX - n) / sizeof(struct hnode *) >= nbkts); n += sizeof(struct hnode *) * nbkts; t = emalloc(n); if ( t == NULL ) { if ( abort_on_fail ) err("cht_new: unable to allocate table\n"); return NULL; } new_hctx = (byte_t *)t + tsize; buckets = (struct hnode **)((byte_t *)new_hctx + hctx_size); if (hctx_size != 0) memmove(new_hctx, hctx, attr->hctx_size); else new_hctx = NULL; ht_init(&t->table, buckets, nbkts, attr->kcmp, attr->hash, new_hctx); t->abort_on_fail = abort_on_fail; t->node_alloc = attr->node_alloc; t->node_free = attr->node_free; t->ctx = attr->ctx; return t; } void cht_free(struct chtab *t) { unsigned i; struct chnode *chn; abort_unless(t != NULL); for ( i = 0; i < t->table.nbkts ; ++i ) { while ( t->table.bkts[i] != NULL ) { chn = container(t->table.bkts[i], struct chnode, node); ht_rem(&chn->node); (*t->node_free)(t, chn); } } free(t); } void *cht_get(struct chtab *t, void *key) { struct hnode *hn; abort_unless(t != NULL); abort_unless(key != NULL); hn = ht_lkup(&t->table, key, NULL); if ( hn != NULL ) return container(hn, struct chnode, node)->data; return NULL; } int cht_put(struct chtab *t, void *key, void *data) { struct hnode *hn; struct chnode *chn; uint h; abort_unless(t != NULL); abort_unless(key != NULL); abort_unless(data != NULL); hn = ht_lkup(&t->table, key, &h); if ( hn != NULL ) { chn = container(hn, struct chnode, node); chn->data = data; return 1; } chn = (*t->node_alloc)(t, key); if ( chn == NULL ) { if ( t->abort_on_fail ) err("cht_put: unable to allocate node\n"); return -1; } chn->data = data; ht_ins(&t->table, &chn->node, h); return 0; } void *cht_del(struct chtab *t, void *key) { struct hnode *hn; struct chnode *chn; void *data = NULL; abort_unless(t != NULL); abort_unless(key != NULL); hn = ht_lkup(&t->table, key, NULL); if ( hn != NULL ) { ht_rem(hn); chn = container(hn, struct chnode, node); data = chn->data; (*t->node_free)(t, chn); } return data; } static void cht_apply_wrap(void *p, void *ctx) { struct chnode *chn = p; struct apply_ctx *ac = ctx; (*ac->f)(chn->data, ac->ctx); } void cht_apply(struct chtab *t, apply_f f, void *ctx) { struct apply_ctx ac; ac.ctx = t->ctx; ac.f = f; ht_apply(&t->table, &cht_apply_wrap, &ac); } /* AVL Trees */ static struct canode *cavl_node_alloc_skey(struct cavltree *t, void *key) { char *kcpy; struct canode *can; kcpy = strdup(key); if ( kcpy == NULL ) return NULL; can = malloc(sizeof(*can)); if ( can == NULL ) { free(kcpy); return NULL; } avl_ninit(&can->node, kcpy); return can; } static void cavl_node_free_skey(struct cavltree *t, struct canode *can) { abort_unless(can != NULL); abort_unless(can->node.key != NULL); free(can->node.key); free(can); } struct cavltree_attr cavl_std_attr_skey = { &cmp_str, &cavl_node_alloc_skey, &cavl_node_free_skey, 0, }; static struct canode *cavl_node_alloc_rkey(struct cavltree *t, void *key) { struct canode *can; struct raw *rkey = key; struct raw *rnode; abort_unless(rkey != NULL); can = malloc(CAT_ALIGN_SIZE(sizeof(*can)) + CAT_ALIGN_SIZE(sizeof(*rnode)) + rkey->len); if ( can == NULL ) return NULL; rnode = (struct raw *)((byte_t *)can + CAT_ALIGN_SIZE(sizeof(*can))); rnode->len = rkey->len; if ( rkey->len > 0 ) { rnode->data = (byte_t *)rnode + CAT_ALIGN_SIZE(sizeof(*rnode)); memmove(rnode->data, rkey->data, rkey->len); } else { rnode->data = NULL; } avl_ninit(&can->node, rnode); return can; } static void cavl_node_free_rkey(struct cavltree *t, struct canode *can) { free(can); } struct cavltree_attr cavl_std_attr_rkey = { &cmp_raw, &cavl_node_alloc_rkey, &cavl_node_free_rkey, 0, }; static struct canode *cavl_node_alloc_pkey(struct cavltree *t, void *key) { struct canode *can; can = malloc(sizeof(*can)); if ( can == NULL ) return NULL; avl_ninit(&can->node, key); return can; } static void cavl_node_free_pkey(struct cavltree *t, struct canode *can) { free(can); } struct cavltree_attr cavl_std_attr_pkey = { &cmp_ptr, &cavl_node_alloc_pkey, &cavl_node_free_pkey, 0, }; struct cavltree_attr cavl_std_attr_bkey = { NULL, /* Must be supplied by user */ &cavl_node_alloc_pkey, &cavl_node_free_pkey, 0, }; struct cavltree *cavl_new(struct cavltree_attr *attr, int abort_on_fail) { struct cavltree *t; if ( attr == NULL ) attr = &cavl_std_attr_skey; abort_unless(attr->kcmp != NULL); abort_unless(attr->node_alloc != NULL); abort_unless(attr->node_free != NULL); t = malloc(sizeof(*t)); if ( t == NULL ) { if ( abort_on_fail ) err("cavl_new: unable to allocate tree\n"); return NULL; } avl_init(&t->tree, attr->kcmp); t->abort_on_fail = abort_on_fail; t->node_alloc = attr->node_alloc; t->node_free = attr->node_free; t->ctx = attr->ctx; return t; } void cavl_free(struct cavltree *t) { struct anode *an; struct canode *can; abort_unless(t != NULL); while ( (an = avl_getroot(&t->tree)) != NULL ) { avl_rem(an); can = container(an, struct canode, node); (*t->node_free)(t, can); } free(t); } void *cavl_get(struct cavltree *t, void *key) { struct anode *an; abort_unless(t != NULL); abort_unless(key != NULL); an = avl_lkup(&t->tree, key, NULL); if ( an != NULL ) return container(an, struct canode, node)->data; return NULL; } int cavl_put(struct cavltree *t, void *key, void *data) { int dir; struct anode *an; struct canode *can; abort_unless(t != NULL); abort_unless(key != NULL); an = avl_lkup(&t->tree, key, &dir); if ( dir == CA_N ) { can = container(an, struct canode, node); can->data = data; return 1; } can = (*t->node_alloc)(t, key); if ( can == NULL ) { if ( t->abort_on_fail ) err("cavl_put: unable to allocate node\n"); return -1; } can->data = data; avl_ins(&t->tree, &can->node, an, dir); return 0; } void *cavl_del(struct cavltree *t, void *key) { struct anode *an; struct canode *can; void *data = NULL; abort_unless(t != NULL); abort_unless(key != NULL); an = avl_lkup(&t->tree, key, NULL); if ( an != NULL ) { can = container(an, struct canode, node); data = can->data; avl_rem(an); (*t->node_free)(t, can); } return data; } static void cavl_apply_wrap(void *p, void *ctx) { struct canode *can = p; struct apply_ctx *ac = ctx; (*ac->f)(can->data, ac->ctx); } void cavl_apply(struct cavltree *t, apply_f f, void *ctx) { struct apply_ctx ac; ac.ctx = t->ctx; ac.f = f; avl_apply(&t->tree, &cavl_apply_wrap, &ac); } /* Red-Black Trees */ static struct crbnode *crb_node_alloc_skey(struct crbtree *t, void *key) { char *kcpy; struct crbnode *crn; kcpy = strdup(key); if ( kcpy == NULL ) return NULL; crn = malloc(sizeof(*crn)); if ( crn == NULL ) { free(kcpy); return NULL; } rb_ninit(&crn->node, kcpy); return crn; } static void crb_node_free_skey(struct crbtree *t, struct crbnode *crn) { abort_unless(crn != NULL); abort_unless(crn->node.key != NULL); free(crn->node.key); free(crn); } struct crbtree_attr crb_std_attr_skey = { &cmp_str, &crb_node_alloc_skey, &crb_node_free_skey, 0, }; static struct crbnode *crb_node_alloc_rkey(struct crbtree *t, void *key) { struct crbnode *crn; struct raw *rkey = key; struct raw *rnode; abort_unless(rkey != NULL); crn = malloc(CAT_ALIGN_SIZE(sizeof(*crn)) + CAT_ALIGN_SIZE(sizeof(struct raw)) + rkey->len); if ( crn == NULL ) return NULL; rnode = (struct raw *)((byte_t *)crn + CAT_ALIGN_SIZE(sizeof(*crn))); rnode->len = rkey->len; if ( rkey->len > 0 ) { rnode->data = (byte_t *)rnode + CAT_ALIGN_SIZE(sizeof(*rnode)); memmove(rnode->data, rkey->data, rkey->len); } else { rnode->data = NULL; } rb_ninit(&crn->node, rnode); return crn; } static void crb_node_free_rkey(struct crbtree *t, struct crbnode *crn) { free(crn); } struct crbtree_attr crb_std_attr_rkey = { &cmp_raw, &crb_node_alloc_rkey, &crb_node_free_rkey, 0, }; static struct crbnode *crb_node_alloc_pkey(struct crbtree *t, void *key) { struct crbnode *crn; crn = malloc(sizeof(*crn)); if ( crn == NULL ) return NULL; rb_ninit(&crn->node, key); return crn; } static void crb_node_free_pkey(struct crbtree *t, struct crbnode *crn) { free(crn); } struct crbtree_attr crb_std_attr_pkey = { &cmp_ptr, &crb_node_alloc_pkey, &crb_node_free_pkey, 0, }; struct crbtree_attr crb_std_attr_bkey = { NULL, /* Must be supplied by user */ &crb_node_alloc_pkey, &crb_node_free_pkey, 0, }; struct crbtree *crb_new(struct crbtree_attr *attr, int abort_on_fail) { struct crbtree *t; if ( attr == NULL ) attr = &crb_std_attr_skey; abort_unless(attr->kcmp != NULL); abort_unless(attr->node_alloc != NULL); abort_unless(attr->node_free != NULL); t = malloc(sizeof(*t)); if ( t == NULL ) { if ( abort_on_fail ) err("crb_new: unable to allocate tree\n"); return NULL; } rb_init(&t->tree, attr->kcmp); t->abort_on_fail = abort_on_fail; t->node_alloc = attr->node_alloc; t->node_free = attr->node_free; t->ctx = attr->ctx; return t; } void crb_free(struct crbtree *t) { struct rbnode *rn; struct crbnode *crn; abort_unless(t != NULL); while ( (rn = rb_getroot(&t->tree)) != NULL ) { rb_rem(rn); crn = container(rn, struct crbnode, node); (*t->node_free)(t, crn); } free(t); } void *crb_get(struct crbtree *t, void *key) { struct rbnode *rn; abort_unless(t != NULL); abort_unless(key != NULL); rn = rb_lkup(&t->tree, key, NULL); if ( rn != NULL ) return container(rn, struct crbnode, node)->data; return NULL; } int crb_put(struct crbtree *t, void *key, void *data) { int dir; struct rbnode *rn; struct crbnode *crn; abort_unless(t != NULL); abort_unless(key != NULL); rn = rb_lkup(&t->tree, key, &dir); if ( dir == CRB_N ) { crn = container(rn, struct crbnode, node); crn->data = data; return 1; } crn = (*t->node_alloc)(t, key); if ( crn == NULL ) { if ( t->abort_on_fail ) err("crb_put: unable to allocate node\n"); return -1; } crn->data = data; rb_ins(&t->tree, &crn->node, rn, dir); return 0; } void *crb_del(struct crbtree *t, void *key) { struct rbnode *rn; struct crbnode *crn; void *data = NULL; abort_unless(t != NULL); abort_unless(key != NULL); rn = rb_lkup(&t->tree, key, NULL); if ( rn != NULL ) { crn = container(rn, struct crbnode, node); data = crn->data; rb_rem(rn); (*t->node_free)(t, crn); } return data; } static void crb_apply_wrap(void *p, void *ctx) { struct crbnode *crn = p; struct apply_ctx *ac = ctx; (*ac->f)(crn->data, ac->ctx); } void crb_apply(struct crbtree *t, apply_f f, void *ctx) { struct apply_ctx ac; ac.ctx = t->ctx; ac.f = f; rb_apply(&t->tree, &crb_apply_wrap, &ac); } /* Splay Trees */ static struct cstnode *cst_node_alloc_skey(struct cstree *t, void *key) { char *kcpy; struct cstnode *csn; kcpy = strdup(key); if ( kcpy == NULL ) return NULL; csn = malloc(sizeof(*csn)); if ( csn == NULL ) { free(kcpy); return NULL; } st_ninit(&csn->node, kcpy); return csn; } static void cst_node_free_skey(struct cstree *t, struct cstnode *csn) { abort_unless(csn != NULL); abort_unless(csn->node.key != NULL); free(csn->node.key); free(csn); } struct cstree_attr cst_std_attr_skey = { &cmp_str, &cst_node_alloc_skey, &cst_node_free_skey, 0, }; static struct cstnode *cst_node_alloc_rkey(struct cstree *t, void *key) { struct cstnode *csn; struct raw *rkey = key; struct raw *rnode; abort_unless(rkey != NULL); csn = malloc(CAT_ALIGN_SIZE(sizeof(*csn)) + CAT_ALIGN_SIZE(sizeof(struct raw)) + rkey->len); if ( csn == NULL ) return NULL; rnode = (struct raw *)((byte_t *)csn + CAT_ALIGN_SIZE(sizeof(*csn))); rnode->len = rkey->len; if ( rkey->len > 0 ) { rnode->data = (byte_t *)rnode + CAT_ALIGN_SIZE(sizeof(*rnode)); memmove(rnode->data, rkey->data, rkey->len); } else { rnode->data = NULL; } st_ninit(&csn->node, rnode); return csn; } static void cst_node_free_rkey(struct cstree *t, struct cstnode *csn) { free(csn); } struct cstree_attr cst_std_attr_rkey = { &cmp_raw, &cst_node_alloc_rkey, &cst_node_free_rkey, 0, }; static struct cstnode *cst_node_alloc_pkey(struct cstree *t, void *key) { struct cstnode *csn; csn = malloc(sizeof(*csn)); if ( csn == NULL ) return NULL; st_ninit(&csn->node, key); return csn; } static void cst_node_free_pkey(struct cstree *t, struct cstnode *csn) { free(csn); } struct cstree_attr cst_std_attr_pkey = { &cmp_ptr, &cst_node_alloc_pkey, &cst_node_free_pkey, 0, }; struct cstree_attr cst_std_attr_bkey = { NULL, /* Must be supplied by user */ &cst_node_alloc_pkey, &cst_node_free_pkey, 0, }; struct cstree *cst_new(struct cstree_attr *attr, int abort_on_fail) { struct cstree *t; if ( attr == NULL ) attr = &cst_std_attr_skey; abort_unless(attr->kcmp != NULL); abort_unless(attr->node_alloc != NULL); abort_unless(attr->node_free != NULL); t = malloc(sizeof(*t)); if ( t == NULL ) { if ( abort_on_fail ) err("cst_new: unable to allocate tree\n"); return NULL; } st_init(&t->tree, attr->kcmp); t->abort_on_fail = abort_on_fail; t->node_alloc = attr->node_alloc; t->node_free = attr->node_free; t->ctx = attr->ctx; return t; } void cst_free(struct cstree *t) { struct stnode *sn; struct cstnode *csn; abort_unless(t != NULL); while ( (sn = st_getroot(&t->tree)) != NULL ) { st_rem(sn); csn = container(sn, struct cstnode, node); (*t->node_free)(t, csn); } free(t); } void *cst_get(struct cstree *t, void *key) { struct stnode *sn; abort_unless(t != NULL); abort_unless(key != NULL); sn = st_lkup(&t->tree, key); if ( sn != NULL ) return container(sn, struct cstnode, node)->data; return NULL; } int cst_put(struct cstree *t, void *key, void *data) { struct stnode *sn; struct cstnode *csn; abort_unless(t != NULL); abort_unless(key != NULL); sn = st_lkup(&t->tree, key); if ( sn != NULL ) { csn = container(sn, struct cstnode, node); csn->data = data; return 1; } csn = (*t->node_alloc)(t, key); if ( csn == NULL ) { if ( t->abort_on_fail ) err("cst_put: unable to allocate node\n"); return -1; } csn->data = data; st_ins(&t->tree, &csn->node); return 0; } void *cst_del(struct cstree *t, void *key) { struct stnode *sn; struct cstnode *csn; void *data = NULL; abort_unless(t != NULL); abort_unless(key != NULL); sn = st_lkup(&t->tree, key); if ( sn != NULL ) { csn = container(sn, struct cstnode, node); data = csn->data; st_rem(sn); (*t->node_free)(t, csn); } return data; } static void cst_apply_wrap(void *p, void *ctx) { struct cstnode *csn = p; struct apply_ctx *ac = ctx; (*ac->f)(csn->data, ac->ctx); } void cst_apply(struct cstree *t, apply_f f, void *ctx) { struct apply_ctx ac; ac.ctx = t->ctx; ac.f = f; st_apply(&t->tree, &cst_apply_wrap, &ac); } /* Heap operations */ struct heap *hp_new(size_t size, cmp_f cmp) { struct heap *hp; void **elem = NULL; abort_unless(cmp); abort_unless(SMAX / sizeof(void *) >= size); hp = malloc(sizeof(struct heap)); if ( hp == NULL ) return NULL; if ( size > 0 ) { elem = malloc(size * sizeof(void*)); if ( elem == NULL ) { free(hp); return NULL; } } hp_init(hp, elem, size, 0, cmp, &stdmm); return hp; } void hp_free(struct heap *hp) { abort_unless(hp != NULL); mem_free(&stdmm, hp->elem); free(hp); } /* Ring operations */ #define CKRING(r) do { \ abort_unless(r); \ abort_unless(((r)->alloc > 0) && ((r)->start < (r)->alloc)); \ abort_unless((r)->len <= (r)->alloc); \ } while (0) char * ring_alloc(struct ring *r, size_t len) { size_t osiz, last, toend; CKRING(r); if (len > CAT_MAXGROW - r->len) err("ring_alloc: request for %ld bytes too much\n", len); last = ring_last(r); if ( r->alloc - r->len >= len ) { if (len > r->alloc - last) { memmove(r->data, r->data + r->start, r->len); r->start = 0; } return (char *)r->data + r->len; } osiz = r->alloc; /* XXX extra (void *) cast is to shut up the compiler */ if ( grow(&r->data, &r->alloc, r->len + len) < 0 ) err("ring_alloc: out of memory\n"); if ( last < r->start ) { toend = osiz - r->start; memmove(r->data + r->start + (r->alloc - osiz), r->data + r->start, toend); r->start += r->alloc - osiz; } else if ( len > r->alloc - last ) { memmove(r->data, r->data + r->start, r->len); r->start = 0; last = r->len; } return (char *)r->data + last; } int ring_fmt(struct ring *r, const char *fmt, ...) { size_t a; int rv; va_list ap; char *d; abort_unless(r); a = ring_avail(r); while ( 1 ) { va_start(ap, fmt); d = ring_alloc(r, a); if ( !d ) return -1; rv = vsnprintf(d, a, fmt, ap); va_end(ap); if ( rv > a ) a = rv; else if ( rv < 0 ) a <<= 1; else break; } r->len += rv; return rv; } #undef CKRING /* Matching functions */ struct kmppat * kmp_pnew(struct memmgr *mm, struct raw *pat) { struct std_kmppat *kmp; abort_unless(pat && pat->data && pat->len); abort_unless(mm != NULL); kmp = mem_get(mm, sizeof(*kmp) + pat->len * sizeof(ulong)); if ( kmp != NULL ) { kmp_pinit(&kmp->pattern, pat, (ulong *)(kmp + 1)); kmp->mm = mm; return &kmp->pattern; } else { return NULL; } } void kmp_free(struct kmppat *kmp) { struct std_kmppat *base; struct memmgr *mm; abort_unless(kmp != NULL); base = container(kmp, struct std_kmppat, pattern); mm = base->mm; abort_unless(mm != NULL); mem_free(mm, base); } struct bmpat * bm_pnew(struct memmgr *mm, struct raw *pat) { struct bmpat *bmp; ulong *scratch; abort_unless(pat && pat->data && pat->len); scratch = mem_get(mm, pat->len * sizeof(ulong)); if ( scratch == NULL ) return NULL; bmp = mem_get(mm, sizeof(*bmp) + pat->len * sizeof(ulong)); if ( bmp != NULL ) bm_pinit(bmp, pat, (ulong *)(bmp + 1), scratch); free(scratch); return bmp; } void bm_free(struct bmpat *bmp) { struct std_bmpat *base; struct memmgr *mm; abort_unless(bmp != NULL); base = container(bmp, struct std_bmpat, pattern); mm = base->mm; abort_unless(mm != NULL); mem_free(mm, base); } struct sfxtree *sfx_new(struct memmgr *mm, struct raw *str) { struct sfxtree *sfx; if ( (sfx = mem_get(mm, sizeof(*sfx))) != NULL ) { if ( sfx_init(sfx, str, mm) < 0 ) { sfx_free(sfx); sfx = NULL; } } return sfx; } void sfx_free(struct sfxtree *sfx) { sfx_clear(sfx); free(sfx); } /* Safe Bit Set operations */ struct safebitset *sbs_new(struct memmgr *mm, uint nbits) { struct safebitset *set; unsigned len = BITSET_LEN(nbits); abort_unless(mm != NULL); if ( (set = mem_get(mm, sizeof(struct safebitset))) == NULL ) return NULL; set->mm = mm; set->nbits = nbits; set->len = len; if ( len == 0 ) len = 1; if ( (set->set = mem_get(mm, sizeof(bitset_t) * len)) == NULL ) { mem_free(mm, set); return NULL; } sbs_zero(set); return set; } void sbs_free(struct safebitset *set) { struct memmgr *mm; abort_unless(set); abort_unless(set->set); abort_unless(set->mm); abort_unless(BITSET_LEN(set->nbits) == set->len); mm = set->mm; mem_free(mm, set->set); mem_free(mm, set); } void sbs_zero(struct safebitset *set) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); bset_zero(set->set, set->nbits); } void sbs_fill(struct safebitset *set) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); bset_fill(set->set, set->nbits); } uint sbs_copy(struct safebitset *dst, struct safebitset *src) { uint nbits; abort_unless(dst); abort_unless(dst->set); abort_unless(BITSET_LEN(dst->nbits) == dst->len); abort_unless(src); abort_unless(src->set); abort_unless(BITSET_LEN(src->nbits) == src->len); nbits = dst->nbits; if ( nbits > src->nbits ) nbits = src->nbits; bset_copy(dst->set, src->set, nbits); return nbits; } int sbs_test(struct safebitset *set, uint index) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); if ( index > set->nbits ) err("sbs_test: index out of bounds (%u > %u)\n", index, set->nbits); return bset_test(set->set, index); } void sbs_set(struct safebitset *set, uint index) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); if ( index > set->nbits ) err("sbs_set: index out of bounds (%u > %u)\n", index, set->nbits); bset_set(set->set, index); } void sbs_clr(struct safebitset *set, uint index) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); if ( index > set->nbits ) err("sbs_clr: index out of bounds (%u > %u)\n", index, set->nbits); bset_clr(set->set, index); } void sbs_flip(struct safebitset *set, uint index) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); if ( index > set->nbits ) err("sbs_clr: index out of bounds (%u > %u)\n", index, set->nbits); bset_flip(set->set, index); } void sbs_set_to(struct safebitset *set, uint index, int val) { abort_unless(set); abort_unless(set->set); abort_unless(BITSET_LEN(set->nbits) == set->len); if ( index > set->nbits ) err("sbs_set_to: index out of bounds (%u > %u)\n", index, set->nbits); bset_set_to(set->set, index, val); }
github188/catlib
src/inport.c
<reponame>github188/catlib<filename>src/inport.c /* * inport.c -- generic API for an input stream. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/inport.h> #include <limits.h> #include <string.h> /* ------ Core API ------ */ int inp_read(struct inport *in, void *buf, int len) { if ( in == NULL || in->read == NULL || buf == NULL || len <= 0 ) return -1; return (*in->read)(in, buf, len); } int inp_getc(struct inport *in) { char ch; int rv; rv = inp_read(in, &ch, 1); if ( rv <= 0 ) return -1; return ch; } int inp_close(struct inport *in) { if ( in == NULL ) return -1; if ( in->close == NULL ) return 0; return (*in->close)(in); } /* ------ Constant String Inport ------ */ static int csinp_read(struct inport *in, void *buf, int len) { struct cstr_inport *csi = (struct cstr_inport *)in; abort_unless(csi->str != NULL); abort_unless(len > 0); if ( csi->off >= csi->slen ) return 0; if ( csi->slen - csi->off < len ) len = csi->slen - csi->off; memcpy(buf, csi->str + csi->off, len); csi->off += len; return len; } static int csinp_close(struct inport *in) { struct cstr_inport *csi = (struct cstr_inport *)in; csinp_clear(csi); return 0; } void csinp_init(struct cstr_inport *csi, const char *s) { abort_unless(csi); csi->in.read = csinp_read; csi->in.close = csinp_close; csi->str = s; csi->slen = (s == NULL) ? 0 : strlen(s); csi->off = 0; } void csinp_init_len(struct cstr_inport *csi, const char *s, size_t len) { abort_unless(csi); abort_unless((s != NULL) || (len > 0)); csi->in.read = csinp_read; csi->str = s; csi->slen = len; csi->off = 0; } void csinp_reset(struct cstr_inport *csi) { abort_unless(csi); csi->off = 0; } void csinp_clear(struct cstr_inport *csi) { csinp_init(csi, NULL); } /* ------ Null Inport ------ */ void null_inport_init(struct inport *in) { } struct inport null_inport = { NULL, NULL };
github188/catlib
include/cat/bitops.h
/* * bitops.h -- Bit manipulation operations. * * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #ifndef __bitops_h #define __bitops_h #include <cat/cat.h> #include <cat/archops.h> uint32_t rup2_32(uint32_t x, uint lg2p); uint32_t rdp2_32(uint32_t x, uint lg2p); uint32_t compress_l32(uint32_t x, uint32_t mask); uint32_t compress_r32(uint32_t x, uint32_t mask); uint32_t SAG32(uint32_t x, uint32_t maskleft); int arr_to_SAG_permvec32(uint8_t arr[32], uint32_t permvec[5]); uint32_t permute32_SAG(uint32_t bits, uint32_t permvec[5]); uint32_t bitgather32(uint32_t bits, uint8_t pos[32]); #if CAT_64BIT uint64_t rup2_64(uint64_t x, uint lg2p); uint64_t rdp2_64(uint64_t x, uint lg2p); uint64_t compress_l64(uint64_t x, uint64_t mask); uint64_t compress_r64(uint64_t x, uint64_t mask); uint64_t SAG64(uint64_t x, uint64_t maskleft); int arr_to_SAG_permvec64(uint8_t arr[64], uint64_t permvec[6]); uint64_t permute64_SAG(uint64_t bits, uint64_t permvec[6]); uint64_t bitgather64(uint64_t bits, uint8_t pos[64]); #endif #endif /* __bitops_h */
github188/catlib
test/testcsv.c
<filename>test/testcsv.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <cat/csv.h> #include <cat/list.h> #include <stdlib.h> int main(int argc, char *argv[]) { char farr[32] = { 0 }; int i, j; char buf[20]; int code; struct csv_state csv; for ( i = 1 ; i < argc ; ++i ) { j = atoi(argv[i]); if ( j <= 0 || j > sizeof(farr) ) exit(-1); farr[j-1] = 1; } csv_init(&csv, (int (*)())getchar, NULL); i = 0; while ( (code = csv_next(&csv, buf, sizeof(buf), 0)) != CSV_EOF ) { if ( code == CSV_CNT ) code = csv_clear_field(&csv); if ( i < sizeof(farr) && farr[i++] ) printf("%19s ", buf); if ( code == CSV_REC ) { printf("\n"); i = 0; } } return 0; }
github188/catlib
include/cat/crypto.h
<filename>include/cat/crypto.h<gh_stars>1-10 /* * cat/crypto.h -- Cryptographic algorithms * * by <NAME> * * Copyright 2009-2015 -- See accompanying license * */ #ifndef __cat_crypto_h #define __cat_crypto_h #include <cat/cat.h> /* ARC4 Stream Cipher */ struct arc4ctx { uint i; uint j; byte_t s[256]; }; void arc4_init(struct arc4ctx *arc4, const void *key, ulong len); void arc4_gen(struct arc4ctx *arc4, void *out, ulong len); void arc4_encrypt(struct arc4ctx *arc4, const void *in, void *out, ulong len); /* SHA-2 256 hash function */ struct sha256ctx { ulong llo; /* length_lo: in bytes until fini */ ulong lhi; /* length_hi: in bytes until fini */ ulong w[64]; /* 512-bits message + derived */ ulong h[8]; /* current hash */ }; /* only operates on byte-level granularity */ void sha256_init(struct sha256ctx *s); void sha256_add(struct sha256ctx *s, void *p, ulong len); void sha256_fini(struct sha256ctx *s, byte_t hash[32]); void sha256(void *in, ulong len, byte_t hash[32]); /* SipHash hash function */ /* Each ulong[2] array is a little-endian 64-bit word */ struct siphashctx { uint nbytes; ulong state[2]; ulong v0[2]; ulong v1[2]; ulong v2[2]; ulong v3[2]; }; void siphash_init(struct siphashctx *shc, byte_t key[16]); void siphash24_add(struct siphashctx *shc, const void *p, ulong len); void siphash24_fini(struct siphashctx *shc, byte_t hash[8]); void siphash24(byte_t key[16], const void *p, ulong len, byte_t hash[8]); struct ht_sh24_ctx { byte_t key[16]; }; void ht_sh24_init(struct ht_sh24_ctx *hsc, const void *k, ulong len); uint ht_sh24_shash(const void *p, void *hsc); uint ht_sh24_rhash(const void *p, void *hsc); #endif /* __cat_crypto_h */
github188/catlib
include/cat/graph.h
<reponame>github188/catlib /* * graph.h -- Generic graph data structure. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __graph_h #define __graph_h #include <cat/cat.h> #include <cat/mem.h> #include <cat/list.h> struct gr_edge_arr { struct gr_edge ** arr; uint fill; uint len; }; struct gr_node { struct list entry; struct graph * graph; struct gr_edge_arr out; struct gr_edge_arr in; attrib_t grn_u; }; #define gr_node_val grn_u.int_val #define gr_node_ptr grn_u.ptr_val #define gr_node_data grn_u.bytes struct gr_edge { struct list entry; struct gr_node * n1; struct gr_node * n2; attrib_t gre_u; }; #define gr_edge_val gre_u.int_val #define gr_edge_ptr gre_u.ptr_val #define gr_edge_data gre_u.bytes struct graph { struct list nodes; struct list edges; int isbi; uint nsize; uint esize; struct memmgr * mm; }; struct graph * gr_new(struct memmgr *mm, int isbi, uint nxsize, uint exsize); struct gr_node * gr_add_node(struct graph *g); struct gr_edge * gr_add_edge(struct gr_node *src, struct gr_node *dst); struct gr_edge * gr_find_edge(struct gr_node *from, struct gr_node *to); void gr_del_node(struct gr_node *node); void gr_del_edge(struct gr_edge *edge); void gr_free(struct graph *g); struct gr_node * gr_edge_dst(const struct gr_node *node, const struct gr_edge *edge); #endif /* __graph_h */
github188/catlib
include/cat/socks5.h
/* * socks5.h -- SOCKS5 protocol library. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __anonsocks_h #define __anonsocks_h #include <cat/cat.h> #if CAT_HAS_POSIX #include <sys/types.h> #include <sys/socket.h> #define SOCKS5_CT_CONNECT 1 #define SOCKS5_CT_BIND 2 #define SOCKS5_CT_UDP 3 #define SOCKS5_AT_IPV4 1 #define SOCKS5_AT_DN 3 #define SOCKS5_AT_IPV6 4 #define SOCKS5_MAXLEN 264 #define SOCKS5_RC_OK 0 /* succeeded */ #define SOCKS5_RC_FAIL 1 /* general SOCKS server failure */ #define SOCKS5_RC_DISALLOWED 2 /* connection not allowed by ruleset */ #define SOCKS5_RC_NUNREACH 3 /* Network unreachable */ #define SOCKS5_RC_HUNREACH 4 /* Host unreachable */ #define SOCKS5_RC_ECONN 5 /* Connection refused */ #define SOCKS5_RC_ETTL 6 /* TTL expired */ #define SOCKS5_RC_CTUNSUPP 7 /* Command not supported */ #define SOCKS5_RC_ATUNSUPP 8 /* Address type not supported */ /* return codes returned by socks5_recvresp() */ #define SOCKS5_RRC_OK 0 /* succeeded */ #define SOCKS5_RRC_SYSERR -1 /* system error */ #define SOCKS5_RRC_FAIL -2 /* general SOCKS server failure */ #define SOCKS5_RRC_DISALLOWED -3 /* connection not allowed by ruleset */ #define SOCKS5_RRC_NUNREACH -4 /* Network unreachable */ #define SOCKS5_RRC_HUNREACH -5 /* Host unreachable */ #define SOCKS5_RRC_ECONN -6 /* Connection refused */ #define SOCKS5_RRC_ETTL -7 /* TTL expired */ #define SOCKS5_RRC_CTUNSUPP -8 /* Command not supported */ #define SOCKS5_RRC_ATUNSUPP -9 /* Address type not supported */ struct socks5addr { byte_t type; byte_t len; union { byte_t v4addr[4]; byte_t v6addr[16]; byte_t dn[256]; } addr_u; ushort port; }; void socks5_sa_to_s5a(struct socks5addr *s5a, struct sockaddr *sa); void socks5_dn_to_s5a(struct socks5addr *s5a, char *domainname, ushort port); int socks5_anon_probe(int fd); int socks5_recvresp(int fd, int cmd, int atype, struct socks5addr *outsa); int socks5_sendreq(int fd, int cmd, struct socks5addr *s5a); int socks5_anon_conn(int fd, struct socks5addr *insa, struct socks5addr *outsa); #endif /* CAT_HAS_POSIX */ #endif /* __anonsocks_h */
github188/catlib
test/testsocks5.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <cat/net.h> #include <cat/err.h> #include <cat/socks5.h> int main(int argc, char *argv[]) { int fd; int rv; char line[256]; FILE *in, *out; struct socks5addr insa, outsa; struct sockaddr_storage ss; if ( argc < 4 ) err("usage: %s [proxy addr] [target addr] [target port]\n", argv[0]); if ( (fd = tcp_cli(argv[1], "1080")) < 0 ) errsys("tcp_cli -- "); if ( net_resolv(argv[2], argv[3], "tcp", &ss) < 0 ) errsys("net_resolv -- "); socks5_sa_to_s5a(&insa, (struct sockaddr *)&ss); if ( (rv = socks5_anon_conn(fd, &insa, &outsa)) < 0 ) err("Socks5 error: %d\n", rv); if ( (in = fdopen(fd, "r")) == NULL ) errsys("fdopen read"); if ( (out = fdopen(fd, "w")) == NULL ) errsys("fdopen write"); while ( fgets(line, sizeof(line), stdin) ) { printf("Sending: %s", line); fputs(line, out); fflush(out); fgets(line, sizeof(line), in); printf("Received: %s", line); } return 0; }
github188/catlib
include/cat/stdcsv.h
/* * stdcsv.h -- Nicer way to interact with CSV files. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __stdcsv_h #define __stdcsv_h #include <cat/cat.h> #if CAT_HAS_POSIX #include <cat/csv.h> struct csv_record { ulong cr_nfields; char ** cr_fields; }; int csv_fopen(struct csv_state *csv, const char *filename); int csv_fclose(struct csv_state *csv); int csv_read_field(struct csv_state *csv, char **field); int csv_read_rec(struct csv_state *csv, struct csv_record *cr); void csv_free_rec(struct csv_record *cr); #endif /* CAT_HAS_POSIX */ #endif /* __stdcsv_h */
github188/catlib
src/rbtree.c
/* * cat/rbtree.c -- Red-Black tree implementation * * by <NAME> * * Copyright 2004-2012 -- See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_RB_DO_DECL #define CAT_USE_INLINE 0 #define CAT_RB_DO_DECL 1 #include <cat/rbtree.h>
github188/catlib
include/cat/cb.h
<filename>include/cat/cb.h /* * cat/cb.h -- Event handling and dispatch * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_cb_h #define __cat_cb_h #include <cat/cat.h> #include <cat/list.h> struct callback; typedef int (*callback_f)(void *arg, struct callback *cb); struct callback { struct list entry; void * ctx; callback_f func; }; /* cb_run returns 0 if all invocations return 0. Otherwise stops and returns */ /* immediately on non-zero return values */ void cb_init(struct callback *cb, callback_f f, void *ctx); int cb_call(struct callback *cb, void *arg); void cb_reg(struct list *cblist, struct callback *cb); void cb_unreg(struct callback *cb); int cb_run(struct list *cblist, void *event); #endif /* __cat_cb_h */
erpapa/Viry3D
lib/src/graphics/Mesh.h
<reponame>erpapa/Viry3D /* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Object.h" #include "Color.h" #include "container/Vector.h" #include "math/Vector2.h" #include "math/Matrix4x4.h" #include "private/backend/DriverApi.h" namespace Viry3D { class Mesh : public Object { public: struct Vertex { Vector3 vertex; Color color; Vector2 uv; Vector2 uv2; Vector3 normal; Vector4 tangent; Vector4 bone_weights; Vector4 bone_indices; }; struct Submesh { int index_first; int index_count; }; struct BlendShapeFrame { float weight; Vector<Vector3> vertices; Vector<Vector3> normals; Vector<Vector3> tangents; }; struct BlendShape { String name; Vector<BlendShapeFrame> frames; }; public: static void Init(); static void Done(); static const Ref<Mesh>& GetSharedQuadMesh(); static Ref<Mesh> LoadFromFile(const String& path); Mesh(Vector<Vertex>&& vertices, Vector<unsigned int>&& indices, const Vector<Submesh>& submeshes = Vector<Submesh>(), bool uint32_index = false, bool dynamic = false); virtual ~Mesh(); void Update(Vector<Vertex>&& vertices, Vector<unsigned int>&& indices, const Vector<Submesh>& submeshes = Vector<Submesh>()); const Vector<Vertex>& GetVertices() const { return m_vertices; } const Vector<unsigned int>& GetIndices() const { return m_indices; } const Vector<Submesh>& GetSubmeshes() const { return m_submeshes; } const Vector<Matrix4x4>& GetBindposes() const { return m_bindposes; } const Vector<BlendShape>& GetBlendShapes() const { return m_blend_shapes; } const filament::backend::AttributeArray& GetAttributes() const { return m_attributes; } uint32_t GetEnabledAttributes() const { return m_enabled_attributes; } const filament::backend::VertexBufferHandle& GetVertexBuffer() const { return m_vb; } const filament::backend::IndexBufferHandle& GetIndexBuffer() const { return m_ib; } const Vector<filament::backend::RenderPrimitiveHandle>& GetPrimitives() const { return m_primitives; } private: void SetBindposes(Vector<Matrix4x4>&& bindposes) { m_bindposes = std::move(bindposes); } void SetBlendShapes(Vector<BlendShape>&& blend_shapes) { m_blend_shapes = std::move(blend_shapes); } private: static Ref<Mesh> m_shared_quad_mesh; Vector<Vertex> m_vertices; Vector<unsigned int> m_indices; int m_buffer_vertex_count; int m_buffer_index_count; Vector<Submesh> m_submeshes; Vector<Matrix4x4> m_bindposes; Vector<BlendShape> m_blend_shapes; bool m_uint32_index; filament::backend::AttributeArray m_attributes; uint32_t m_enabled_attributes; filament::backend::VertexBufferHandle m_vb; filament::backend::IndexBufferHandle m_ib; Vector<filament::backend::RenderPrimitiveHandle> m_primitives; }; }
erpapa/Viry3D
lib/src/graphics/SkinnedMeshRenderer.h
<reponame>erpapa/Viry3D /* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "MeshRenderer.h" #include "container/Map.h" namespace Viry3D { class SkinnedMeshRenderer : public MeshRenderer { public: SkinnedMeshRenderer(); virtual ~SkinnedMeshRenderer(); virtual void SetMesh(const Ref<Mesh>& mesh); const Vector<String>& GetBonePaths() const { return m_bone_paths; } void SetBonePaths(const Vector<String>& bones) { m_bone_paths = bones; } Ref<Transform> GetBonesRoot() const { return m_bones_root.lock(); } void SetBonesRoot(const Ref<Transform>& node) { m_bones_root = node; } float GetBlendShapeWeight(const String& name); void SetBlendShapeWeight(const String& name, float weight); const filament::backend::UniformBufferHandle& GetBonesUniformBuffer() const { return m_bones_uniform_buffer; } virtual Vector<filament::backend::RenderPrimitiveHandle> GetPrimitives(); protected: virtual void Prepare(); private: void FindBones(); private: struct BlendShapeWeight { int index; float weight; }; private: Vector<String> m_bone_paths; WeakRef<Transform> m_bones_root; Vector<WeakRef<Transform>> m_bones; Map<String, BlendShapeWeight> m_blend_shape_weights; bool m_blend_shape_dirty; filament::backend::UniformBufferHandle m_bones_uniform_buffer; filament::backend::VertexBufferHandle m_vb; Vector<filament::backend::RenderPrimitiveHandle> m_primitives; int m_vb_vertex_count; Vector<Mesh::Submesh> m_submeshes; }; }
erpapa/Viry3D
lib/src/animation/Animation.h
/* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Component.h" #include "AnimationCurve.h" #include "container/List.h" namespace Viry3D { enum class AnimationCurvePropertyType { Unknown = 0, LocalPositionX, LocalPositionY, LocalPositionZ, LocalRotationX, LocalRotationY, LocalRotationZ, LocalRotationW, LocalScaleX, LocalScaleY, LocalScaleZ, BlendShape, }; struct AnimationCurveProperty { AnimationCurvePropertyType type; String name; AnimationCurve curve; }; struct AnimationCurveWrapper { String path; Vector<AnimationCurveProperty> properties; }; enum class AnimationWrapMode { Default = 0, Once = 1, Loop = 2, PingPong = 4, ClampForever = 8, }; class AnimationClip : public Object { public: AnimationClip(): length(0), fps(0), wrap_mode(AnimationWrapMode::Default) { } virtual ~AnimationClip() { } public: String name; float length; float fps; AnimationWrapMode wrap_mode; Vector<AnimationCurveWrapper> curves; }; enum class FadeState { In, Normal, Out, }; struct AnimationState { int clip_index; float play_start_time; Vector<Transform*> targets; FadeState fade_state; float fade_start_time; float fade_length; float start_weight; float weight; }; class Animation : public Component { public: Animation(); virtual ~Animation(); void SetClips(const Vector<Ref<AnimationClip>>& clips); int GetClipCount() const { return m_clips.Size(); } const String& GetClipName(int index) const; void Play(int index, float fade_length = 0.3f); void Stop(); protected: virtual void Update(); private: void Sample(AnimationState& state, float time, float weight, bool first_state, bool last_state); private: Vector<Ref<AnimationClip>> m_clips; List<AnimationState> m_states; }; }
erpapa/Viry3D
lib/src/graphics/Renderer.h
<filename>lib/src/graphics/Renderer.h /* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Component.h" #include "Material.h" #include "container/List.h" #include "container/Vector.h" #include "math/Vector4.h" #include "private/backend/DriverApi.h" namespace Viry3D { class Renderer : public Component { public: static const List<Renderer*>& GetRenderers() { return m_renderers; } static void PrepareAll(); Renderer(); virtual ~Renderer(); Ref<Material> GetMaterial() const; void SetMaterial(const Ref<Material>& material); const Vector<Ref<Material>>& GetMaterials() const { return m_materials; } void SetMaterials(const Vector<Ref<Material>>& materials); bool IsCastShadow() const { return m_cast_shadow; } void EnableCastShadow(bool enable); bool IsRecieveShadow() const { return m_recieve_shadow; } void EnableRecieveShadow(bool enable); int GetLightmapIndex() const { return m_lightmap_index; } void SetLightmapIndex(int index); const Vector4& GetLightmapScaleOffset() const { return m_lightmap_scale_offset; } void SetLightmapScaleOffset(const Vector4& vec); const filament::backend::UniformBufferHandle& GetTransformUniformBuffer() const { return m_transform_uniform_buffer; } virtual Vector<filament::backend::RenderPrimitiveHandle> GetPrimitives(); protected: virtual void Prepare(); virtual void OnResize(int width, int height) { } private: friend class Camera; private: static List<Renderer*> m_renderers; Vector<Ref<Material>> m_materials; bool m_cast_shadow; bool m_recieve_shadow; Vector4 m_lightmap_scale_offset; int m_lightmap_index; filament::backend::UniformBufferHandle m_transform_uniform_buffer; }; }
erpapa/Viry3D
lib/src/math/Vector3.h
<gh_stars>0 /* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "string/String.h" namespace Viry3D { struct Vector2; struct Vector3 { static const Vector3& Zero(); static const Vector3& One(); static Vector3 Normalize(const Vector3& value); static float Magnitude(const Vector3& v); static float SqrMagnitude(const Vector3& v); static float Distance(const Vector3& a, const Vector3& b); static Vector3 Max(const Vector3& a, const Vector3& b); static Vector3 Min(const Vector3& a, const Vector3& b); static Vector3 Lerp(const Vector3& from, const Vector3& to, float t, bool clamp_01 = true); static float Angle(const Vector3& from, const Vector3& to); static float Dot(const Vector3& a, const Vector3& b); explicit Vector3(float x = 0, float y = 0, float z = 0); Vector3(const Vector2& v2); Vector3 operator -() const; Vector3 operator +(const Vector3& v) const; Vector3& operator +=(const Vector3& v); Vector3 operator -(const Vector3& v) const; Vector3 operator *(const Vector3& v) const; Vector3 operator *(float v) const; Vector3 operator *=(float v); Vector3 operator /(float v) const; Vector3 operator /=(float v); bool operator !=(const Vector3& v) const; bool operator ==(const Vector3& v) const; float Dot(const Vector3& v) const; String ToString() const; void Normalize(); Vector3 Normalized() const; float Magnitude() const; float SqrMagnitude() const; float x; float y; float z; }; }
erpapa/Viry3D
lib/src/graphics/Shader.h
/* * Viry3D * Copyright 2014-2019 by Stack - <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Object.h" #include "container/Vector.h" #include "container/List.h" #include "container/Map.h" #include "private/backend/DriverApi.h" namespace Viry3D { class Shader : public Object { public: enum class BindingPoint { PerView = 0, PerRenderer = 1, PerRendererBones = 2, PerMaterialVertex = 3, PerMaterialFragment = 4, PerLightVertex = 5, PerLightFragment = 6, Count = filament::backend::CONFIG_UNIFORM_BINDING_COUNT, }; enum class AttributeLocation { Vertex = 0, Color = 1, UV = 2, UV2 = 3, Normal = 4, Tangent = 5, BoneWeights = 6, BoneIndices = 7, Count = filament::backend::MAX_VERTEX_ATTRIBUTE_COUNT }; enum class Queue { Background = 1000, Geometry = 2000, AlphaTest = 2450, Transparent = 3000, Overlay = 4000, }; enum class LightMode { None = 0, Forward = 1, }; struct Member { String name; int offset; int size; }; struct Uniform { String name; int binding; Vector<Member> members; int size; }; struct Sampler { String name; int binding; }; struct SamplerGroup { String name; int binding; Vector<Sampler> samplers; }; struct Pass { String vs; String fs; int queue = (int) Queue::Geometry; LightMode light_mode = LightMode::None; Vector<Uniform> uniforms; Vector<SamplerGroup> samplers; filament::backend::PipelineState pipeline; }; static void Init(); static void Done(); static Ref<Shader> Find(const String& name, const Vector<String>& keywords = Vector<String>(), bool light_add = false); virtual ~Shader(); const List<String>& GetKeywords() const { return m_keywords; } int GetPassCount() const { return m_passes.Size(); } const Pass& GetPass(int index) const { return m_passes[index]; } int GetQueue() const { return m_queue; } private: Shader(const String& name, bool light_add); void Load(const String& src, const List<String>& keywords); void Compile(); private: static Map<String, Ref<Shader>> m_shaders; List<String> m_keywords; bool m_light_add; Vector<Pass> m_passes; int m_queue; }; }
RbBtSn0w/SWMoabCache
RBSMoabCache/RBSMoabCache.h
<reponame>RbBtSn0w/SWMoabCache<gh_stars>1-10 // // RBSMoabCache.h // // Copyright (c) <2014-2017> RbBtSn0w // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef enum { RBSMoabCacheErrorDirectoryIsFile = 1001 } RBSMoabCacheError; extern NSString * RBSMoabCacheErrorDomain; @interface RBSMoabCache : NSObject /** The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** The maximum number of objects the cache should hold. */ @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; #pragma mark - Methods /** Designated initializer. You can custom the file document path. @param name Used to name internal NSCache instance and to name a folder which is used to store cached values persistently. @param error Will be assigned if something went wrong during initializing. @param directory Will create document by NSSearchPathDirectory. @return An instance of RBSMoabCache */ - (nullable instancetype)initWithName:(NSString *)name error:(NSError *__autoreleasing *)error searchPathDirectory:(NSSearchPathDirectory) directory; /** Designated initializer. Default document by NSCachesDirectory. @param name Used to name internal NSCache instance and to name a folder which is used to store cached values persistently. @param error Will be assigned if something went wrong during initializing. @return An instance of MoabCache */ - (nullable instancetype)initWithName:(NSString *)name error:(NSError *__autoreleasing *)error; /** Instance's name. @return cache name */ - (NSString *)name; /** Caches the object. @param object Object which is to be cached. It should conform to NSCoding protocol. Passing nil will delete corresponding object. @param key the key which should be used for the object above. */ - (void)setObject:(id<NSCoding>)object forKey:(NSString *)key; /** Indicates whether object exists for the key or not. @param key The key of the object. @return Boolean indicating if an object is stored in the cache. */ - (BOOL)objectExistsForKey:(NSString *)key; /** Returns an object for the corresponding key. @param key The key of the object. @return An object or nil if the object is not in the cache */ - (nullable id)objectForKey:(NSString *)key; /** Removes an object from the cache. @param key Object's key */ - (void)removeObjectForKey:(NSString *)key; /** Removes all objects from the cache and persistent store. */ - (void)removeAllObjects; /** Removes all objects from in-memory cache. */ - (void)clearMemory; /* Subscripting support */ - (void)setObject:(id)obj forKeyedSubscript:(NSString *)key; - (nullable id)objectForKeyedSubscript:(NSString *)key; /** Returnes object's file path. @param key The key of the object. @return If object exists, nil otherwise. @exception MoabCacheKeyIsNilException will be raised if the key provided is nil. */ - (nullable NSString *)pathForObjectForKey:(NSString *)key; /** Removes all objects from names, Only by NSCachesDirectory document. */ + (void)removeAllNameCache; /** Removes all objects from names, Only by NSCachesDirectory document. @param directory Removes by NSSearchPathDirectory document. */ + (void)removeAllNameCacheBySearchPathDirectory:(NSSearchPathDirectory) directory; /** Statistics cache folder size @return size is long long */ + (long long)statisticsCacheFolderSize; @end NS_ASSUME_NONNULL_END
RbBtSn0w/SWMoabCache
RBSMoabCacheExample/SWMoabCacheExample/ViewController.h
<reponame>RbBtSn0w/SWMoabCache<gh_stars>1-10 // // ViewController.h // RBSMoabCacheExample // // Created by <NAME> on 4/15/17. // Copyright © 2017 RbBtSn0w. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
lzx8589561/X-UI
main/ui/page/start_up/start_up_view.c
#include "start_up_view.h" #include "../../resource/resource_pool.h" #include "../../ui_page_manager.h" #define COLOR_ORANGE lv_color_hex(0xff931e) void startup_view_create(lv_obj_t* root) { lv_obj_remove_style_all(root); lv_obj_set_size(root, LV_HOR_RES, LV_VER_RES); lv_obj_t* cont = lv_obj_create(root); lv_obj_remove_style_all(cont); lv_obj_clear_flag(cont, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_size(cont, 110, 50); lv_obj_set_style_border_color(cont, COLOR_ORANGE, 0); lv_obj_set_style_border_side(cont, LV_BORDER_SIDE_BOTTOM, 0); lv_obj_set_style_border_width(cont, 3, 0); lv_obj_set_style_border_post(cont, true, 0); lv_obj_center(cont); startup_view_ui->cont = cont; lv_obj_t* label = lv_label_create(cont); lv_obj_set_style_text_font(label, resource_pool_get_font("agencyb_36"), 0); lv_obj_set_style_text_color(label, lv_color_white(), 0); lv_label_set_text(label, "X-TRACK"); lv_obj_center(label); startup_view_ui->labelLogo = label; startup_view_ui->anim_timeline = lv_anim_timeline_create(); #define ANIM_DEF(start_time, obj, attr, start, end) \ {start_time, obj, LV_ANIM_EXEC(attr), start, end, 500, lv_anim_path_ease_out, true} lv_anim_timeline_wrapper_t wrapper[] = { ANIM_DEF(0, startup_view_ui->cont, width, 0, lv_obj_get_style_width(startup_view_ui->cont, 0)), ANIM_DEF(500, startup_view_ui->labelLogo, y, lv_obj_get_style_height(startup_view_ui->cont, 0), lv_obj_get_y(startup_view_ui->labelLogo)), LV_ANIM_TIMELINE_WRAPPER_END }; lv_anim_timeline_add_wrapper(startup_view_ui->anim_timeline, wrapper); } void startup_view_delete() { if(startup_view_ui->anim_timeline) { lv_anim_timeline_del(startup_view_ui->anim_timeline); startup_view_ui->anim_timeline = NULL; } }
lzx8589561/X-UI
components/lvgl_esp32_drivers/lvgl_touch/gt911.h
<filename>components/lvgl_esp32_drivers/lvgl_touch/gt911.h #ifndef __GT911_H /* * Copyright © 2021 Sturnus Inc. * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the “Software”), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #define __GT911_H #include <stdint.h> #include <stdbool.h> #ifdef LV_LVGL_H_INCLUDE_SIMPLE #include "lvgl.h" #else #include "lvgl/lvgl.h" #endif #ifdef __cplusplus extern "C" { #endif #define GT911_I2C_SLAVE_ADDR 0x5D #define GT911_PRODUCT_ID_LEN 4 /* Register Map of GT911 */ #define GT911_PRODUCT_ID1 0x8140 #define GT911_PRODUCT_ID2 0x8141 #define GT911_PRODUCT_ID3 0x8142 #define GT911_PRODUCT_ID4 0x8143 #define GT911_FIRMWARE_VER_L 0x8144 #define GT911_FIRMWARE_VER_H 0x8145 #define GT911_X_COORD_RES_L 0x8146 #define GT911_X_COORD_RES_H 0x8147 #define GT911_Y_COORD_RES_L 0x8148 #define GT911_Y_COORD_RES_H 0x8149 #define GT911_VENDOR_ID 0x814A #define GT911_STATUS_REG 0x814E #define GT911_STATUS_REG_BUF 0x80 #define GT911_STATUS_REG_LARGE 0x40 #define GT911_STATUS_REG_PROX_VALID 0x20 #define GT911_STATUS_REG_HAVEKEY 0x10 #define GT911_STATUS_REG_PT_MASK 0x0F #define GT911_TRACK_ID1 0x814F #define GT911_PT1_X_COORD_L 0x8150 #define GT911_PT1_X_COORD_H 0x8151 #define GT911_PT1_Y_COORD_L 0x8152 #define GT911_PT1_Y_COORD_H 0x8153 #define GT911_PT1_X_SIZE_L 0x8154 #define GT911_PT1_X_SIZE_H 0x8155 typedef struct { bool inited; char product_id[GT911_PRODUCT_ID_LEN]; uint16_t max_x_coord; uint16_t max_y_coord; uint8_t i2c_dev_addr; } gt911_status_t; /** * @brief Initialize for GT911 communication via I2C * @param dev_addr: Device address on communication Bus (I2C slave address of GT911). * @retval None */ void gt911_init(uint8_t dev_addr); /** * @brief Get the touch screen X and Y positions values. Ignores multi touch * @param drv: * @param data: Store data here * @retval Always false */ bool gt911_read(lv_indev_drv_t *drv, lv_indev_data_t *data); #ifdef __cplusplus } #endif #endif /* __GT911_H */
lzx8589561/X-UI
main/ui/page/start_up/start_up.h
<gh_stars>1-10 #ifndef __STARTUP_PRESENTER_H #define __STARTUP_PRESENTER_H #ifdef __cplusplus extern "C" { #endif #include "lvgl/lvgl.h" /** * 定义页面单独的一些交互实体 */ #ifdef __cplusplus } /*extern "C"*/ #endif #endif
lzx8589561/X-UI
lv_sim_visual_studio/LVGL.Simulator/lvgl/src/extra/libs/lv_libs.h
<reponame>lzx8589561/X-UI /** * @file lv_libs.h * */ #ifndef LV_LIBS_H #define LV_LIBS_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include "bmp/lv_bmp.h" #include "fsdrv/lv_fsdrv.h" #include "png/lv_png.h" #include "gif/lv_gif.h" #include "qrcode/lv_qrcode.h" #include "sjpg/lv_sjpg.h" #include "freetype/lv_freetype.h" #include "rlottie/lv_rlottie.h" /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * GLOBAL PROTOTYPES **********************/ /********************** * MACROS **********************/ #if LV_USE_LOG && LV_LOG_TRACE_LAYOUT # define LV_TRACE_LAYOUT(...) LV_LOG_TRACE( __VA_ARGS__) #else # define LV_TRACE_LAYOUT(...) #endif #ifdef __cplusplus } /*extern "C"*/ #endif #endif /*LV_LAYOUTS_H*/
lzx8589561/X-UI
main/ui/ui_page_manager.h
<gh_stars>1-10 #ifndef UI_PAGE_MANAGER_H #define UI_PAGE_MANAGER_H #ifdef __cplusplus extern "C" { #endif #include "lvgl/lvgl.h" /** --- common --- */ #ifndef ARRAY_SIZE # define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif /** --- stack ---*/ #define STACK_INIT_SIZE 10 #define STACK_INCREASE_SIZE 15 typedef struct pm_stack_node_t{ void* data; }pm_stack_node_t; typedef struct pm_stack_t { pm_stack_node_t *node; unsigned long length; unsigned long size; }pm_stack_t; pm_stack_t *stack_init(); void *stack_pop(pm_stack_t *stack); void *stack_top(pm_stack_t *stack); void *stack_get(pm_stack_t *stack, int index); int stack_empty(pm_stack_t *stack); int stack_push(pm_stack_t *stack, void *data); /** --- stack ---*/ /** --- array_list ---*/ //链表初始化大小 #define PM_ARRAY_LIST_INIT_SIZE 10 //链表存满每次增加的大小 #define PM_ARRAY_LIST_INCREASE_SIZE 15 typedef struct pm_array_node_t{ void* data;//数据域 }pm_array_node_t; //定义链表结构 typedef struct pm_array_list_t{ pm_array_node_t *node; unsigned long length; unsigned long size; }pm_array_list_t; pm_array_list_t* pm_array_list_init(); int pm_array_list_insert(pm_array_list_t* p_list, void* p_data, long index); void* pm_array_list_get(pm_array_list_t* p_list, unsigned long index); void pm_array_list_remove(pm_array_list_t* p_list, unsigned long index); void pm_array_list_remove_p(pm_array_list_t *p_list, void *p_data); void pm_array_list_clear(pm_array_list_t* p_list); void pm_array_list_free(pm_array_list_t* p_list); void pm_array_list_init_semaphore(pm_array_list_t* pList); /** --- array_list ---*/ /** --- common --- */ typedef struct page_base_t *page_base_handler; /** --- pageBase --- */ /* Page state */ typedef enum { PAGE_STATE_IDLE, PAGE_STATE_LOAD, PAGE_STATE_WILL_APPEAR, PAGE_STATE_DID_APPEAR, PAGE_STATE_ACTIVITY, PAGE_STATE_WILL_DISAPPEAR, PAGE_STATE_DID_DISAPPEAR, PAGE_STATE_UNLOAD, _PAGE_STATE_LAST } pm_page_state_t; /* Data area */ typedef struct { void *ptr; uint32_t size; } pm_page_stash_t; /* Page switching animation properties */ typedef struct { uint8_t type; uint16_t time; lv_anim_path_cb_t path; } pm_page_anim_attr_t; struct page_base_t { lv_obj_t *root; // UI root node const char *name; // Page name uint16_t id; // Page ID void *user_data; // User data pointer /* Private data, Only page manager access */ struct { bool req_enable_cache; // Cache enable request bool req_disable_auto_cache; // Automatic cache management enable request bool is_disable_auto_cache; // Whether it is automatic cache management bool is_cached; // Cache enable pm_page_stash_t stash; // Stash area pm_page_state_t state; // Page state /* Animation state */ struct { bool is_enter; // Whether it is the entering party bool is_busy; // Whether the animation is playing pm_page_anim_attr_t attr; // Animation properties } anim; } priv; /* Synchronize user-defined attribute configuration */ void (*on_custom_attr_config)(page_base_handler pb); /* Page load */ void (*on_view_load)(page_base_handler pb); /* Page load complete */ void (*on_view_did_load)(page_base_handler pb); /* Page will be displayed soon */ void (*on_view_will_appear)(page_base_handler pb); /* The page is displayed */ void (*on_view_did_appear)(page_base_handler pb); /* Page is about to disappear */ void (*on_view_will_disappear)(page_base_handler pb); /* Page disappeared complete */ void (*on_view_did_disappear)(page_base_handler pb); /* Page uninstall complete */ void (*on_view_did_unload)(page_base_handler pb); }; /* Set whether to manually manage the cache */ void set_custom_cache_enable(page_base_handler pb, bool en); /* Set whether to enable automatic cache */ void set_custom_auto_cache_enable(page_base_handler pb, bool en); /* Set custom animation properties */ void set_custom_load_anim_type(page_base_handler pb, uint8_t anim_type, uint16_t time, lv_anim_path_cb_t path ); /* Get the data in the stash area */ bool pm_get_stash(page_base_handler pb, void *ptr, uint32_t size); /** --- pageBase ---*/ /* Animated setter */ typedef void(*lv_anim_setter_t)(void *, int32_t); /* Animated getter */ typedef int32_t(*lv_anim_getter_t)(void *); /* Page dragging direction */ typedef enum { ROOT_DRAG_DIR_NONE, ROOT_DRAG_DIR_HOR, ROOT_DRAG_DIR_VER, } root_drag_dir_t; /* Animation switching record */ typedef struct { /* As the entered party */ struct { int32_t start; int32_t end; } enter; /* As the exited party */ struct { int32_t start; int32_t end; } exit; } anim_value_t; /* Page switching animation type */ typedef enum { /* Default (global) animation type */ LOAD_ANIM_GLOBAL = 0, /* New page overwrites old page */ LOAD_ANIM_OVER_LEFT, LOAD_ANIM_OVER_RIGHT, LOAD_ANIM_OVER_TOP, LOAD_ANIM_OVER_BOTTOM, /* New page pushes old page */ LOAD_ANIM_MOVE_LEFT, LOAD_ANIM_MOVE_RIGHT, LOAD_ANIM_MOVE_TOP, LOAD_ANIM_MOVE_BOTTOM, /* The new interface fades in, the old page fades out */ LOAD_ANIM_FADE_ON, /* No animation */ LOAD_ANIM_NONE, _LOAD_ANIM_LAST = LOAD_ANIM_NONE } load_anim_t; /* Page loading animation properties */ typedef struct { lv_anim_setter_t setter; lv_anim_getter_t getter; root_drag_dir_t drag_dir; anim_value_t push; anim_value_t pop; } load_anim_attr_t; /* Loader */ page_base_handler pm_install(const char *class_name, const char *app_name); bool pm_uninstall(const char *app_name); bool pm_register(page_base_handler base, const char *name); bool pm_unregister(const char *name); /* Router */ page_base_handler pm_push(const char *name, const pm_page_stash_t *stash); page_base_handler pm_pop(); bool pm_back_home(); const char *pm_get_page_prev_name(); /* Global Anim */ void pm_set_global_load_anim_type( load_anim_t anim, uint16_t time, lv_anim_path_cb_t path ); /** --- Factory ---*/ #define APP_CLASS_MATCH(class_name)\ do{\ if (strcmp(name, #class_name) == 0)\ {\ extern page_base_handler ui_page_register_##class_name();\ return ui_page_register_##class_name();\ }\ }while(0) extern page_base_handler pm_create_page(const char *name); #define UI_PAGE_FUN_INIT() \ do{ \ if(pb == NULL){\ pb = calloc(1, sizeof(struct page_base_t));\ pb->on_custom_attr_config = on_custom_attr_config;\ pb->on_view_load = on_view_load;\ pb->on_view_did_load = on_view_did_load;\ pb->on_view_will_appear = on_view_will_appear;\ pb->on_view_did_appear = on_view_did_appear;\ pb->on_view_will_disappear = on_view_will_disappear;\ pb->on_view_did_disappear = on_view_did_disappear;\ pb->on_view_did_unload = on_view_did_unload;\ }\ }while(0) /** --- Factory ---*/ /** --- ResourceManager ---*/ typedef struct resource_manager_t *resource_manager_handler; struct resource_manager_t { /** ResourceNode_t */ pm_array_list_t *node_pool; void *default_ptr; }; bool rm_add_resource(resource_manager_handler rm, const char *name, void *ptr); bool rm_remove_resource(resource_manager_handler rm, const char *name); void *rm_get_resource(resource_manager_handler rm, const char *name); void rm_set_default(resource_manager_handler rm, void *ptr); /** --- ResourceManager ---*/ /** --- lv_obj_ext_func ---*/ #ifndef __LV_OBJ_EXT_FUNC_H #define __LV_OBJ_EXT_FUNC_H #define LV_ANIM_TIME_DEFAULT 400 #define LV_ANIM_EXEC(attr) (lv_anim_exec_xcb_t)lv_obj_set_##attr void lv_obj_set_opa_scale(lv_obj_t *obj, int16_t opa); int16_t lv_obj_get_opa_scale(lv_obj_t *obj); void lv_label_set_text_add(lv_obj_t *label, const char *text); void lv_obj_add_anim( lv_obj_t *obj, lv_anim_t *a, lv_anim_exec_xcb_t exec_cb, int32_t start, int32_t end, uint16_t time, uint32_t delay, lv_anim_ready_cb_t ready_cb, lv_anim_path_cb_t path_cb ); void lv_obj_add_anim_def( lv_obj_t *obj, lv_anim_t *a, lv_anim_exec_xcb_t exec_cb, int32_t start, int32_t end ); #define LV_OBJ_ADD_ANIM(obj, attr, target, time)\ do{\ lv_obj_add_anim(\ (obj), NULL,\ (lv_anim_exec_xcb_t)lv_obj_set_##attr,\ lv_obj_get_##attr(obj),\ (target),\ (time),\ (0),\ (NULL),\ (lv_anim_path_ease_out)\ );\ }while(0) #define LV_OBJ_ADD_DELAY_ANIM(obj, attr, target, delay, time)\ do{\ lv_obj_add_anim(\ (obj), NULL,\ (lv_anim_exec_xcb_t)lv_obj_set_##attr,\ lv_obj_get_##attr(obj),\ (target),\ (time),\ (delay),\ (NULL),\ (lv_anim_path_ease_out)\ );\ }while(0) lv_indev_t *lv_get_indev(lv_indev_type_t type); #endif /** --- lv_obj_ext_func ---*/ /** --- lv_anim_timeline_wrapper ---*/ /*Data of anim_timeline*/ typedef struct { uint32_t start_time; lv_obj_t *obj; lv_anim_exec_xcb_t exec_cb; int32_t start; int32_t end; uint16_t duration; lv_anim_path_cb_t path_cb; bool early_apply; } lv_anim_timeline_wrapper_t; /********************** * GLOBAL PROTOTYPES **********************/ /** * Start animation according to the timeline * @param anim_timeline timeline array address * @param playback whether to play in reverse * @return timeline total time spent */ void lv_anim_timeline_add_wrapper(lv_anim_timeline_t *at, const lv_anim_timeline_wrapper_t *wrapper); /********************** * MACROS **********************/ #define LV_ANIM_TIMELINE_WRAPPER_END {0, NULL} /** --- lv_anim_timeline_wrapper ---*/ /** --- lv_label_anim_effect ---*/ typedef struct { lv_obj_t *label_1; lv_obj_t *label_2; lv_anim_t anim_now; lv_anim_t anim_next; lv_coord_t y_offset; uint8_t value_last; } lv_label_anim_effect_t; void lv_label_anim_effect_init( lv_label_anim_effect_t *effect, lv_obj_t *cont, lv_obj_t *label_copy, uint16_t anim_time ); void lv_label_anim_effect_check_value( lv_label_anim_effect_t *effect, uint8_t value, lv_anim_enable_t anim_enable ); /** --- lv_label_anim_effect ---*/ /** --- data_center --- */ typedef struct { const char *topic; void *data; uint32_t length; uint16_t msg_type; bool sync; void *sync_result; }dc_data_msg_t; typedef struct { const char *topic; pm_array_list_t *subscribe_list; } dc_topic_subscribe_t; typedef void (*dc_callback)(dc_data_msg_t *data_msg); /** * 订阅 * @param topic 主题 * @param c 消息处理回调 */ void dc_subscribe(const char *topic,dc_callback c); /** * 取消订阅 * @param topic 主题 * @param c 消息处理回调 */ void dc_unsubscribe(const char *topic,dc_callback c); /** * 推送消息到主题(异步) * @param data_msg 消息 */ void dc_publish(dc_data_msg_t *data_msg); /** * 同步请求 * @param data_msg 消息 */ void dc_sync_req(dc_data_msg_t *data_msg); /** * 创建消息 * @param topic 主题 * @return 消息体 */ dc_data_msg_t *dc_create_msg(const char *topic); /** * 数据中心loop(主线程处理,需与UI在一个线程中) */ void data_center(); /** --- data_center --- */ void ui_page_manager_init(); #ifdef __cplusplus } /*extern "C"*/ #endif #endif //UI_PAGE_MANAGER_H
lzx8589561/X-UI
main/ui/resource/resource_pool.c
#include "resource_pool.h" #include "../ui_page_manager.h" #include <stdlib.h> static resource_manager_handler font_; static resource_manager_handler image_; #define IMPORT_FONT(name) \ do{\ LV_FONT_DECLARE(font_##name)\ rm_add_resource(font_, #name, (void*)&font_##name);\ }while(0) #define IMPORT_IMG(name) \ do{\ LV_IMG_DECLARE(img_src_##name)\ rm_add_resource(image_, #name, (void*)&img_src_##name);\ }while (0) static void resource_init() { /* Import Fonts */ IMPORT_FONT(bahnschrift_13); IMPORT_FONT(bahnschrift_17); IMPORT_FONT(bahnschrift_32); IMPORT_FONT(bahnschrift_65); IMPORT_FONT(agencyb_36); /* Import Images */ IMPORT_IMG(alarm); IMPORT_IMG(battery); IMPORT_IMG(battery_info); IMPORT_IMG(bicycle); IMPORT_IMG(compass); IMPORT_IMG(gps_arrow_default); IMPORT_IMG(gps_arrow_dark); IMPORT_IMG(gps_arrow_light); IMPORT_IMG(gps_pin); IMPORT_IMG(gyroscope); IMPORT_IMG(locate); IMPORT_IMG(map_location); IMPORT_IMG(menu); IMPORT_IMG(origin_point); IMPORT_IMG(pause); IMPORT_IMG(satellite); IMPORT_IMG(sd_card); IMPORT_IMG(start); IMPORT_IMG(stop); IMPORT_IMG(storage); IMPORT_IMG(system_info); IMPORT_IMG(time_info); IMPORT_IMG(trip); } void resource_pool_init() { font_ = calloc(1, sizeof(struct resource_manager_t)); font_->node_pool = pm_array_list_init(); image_ = calloc(1, sizeof(struct resource_manager_t)); image_->node_pool = pm_array_list_init(); resource_init(); font_->default_ptr = ((void*)&lv_font_montserrat_14); } lv_font_t* resource_pool_get_font(const char* name) { return (lv_font_t*) rm_get_resource(font_, name); } const void* resource_pool_get_image(const char* name) { return rm_get_resource(image_, name); }
lzx8589561/X-UI
main/ui/page/dialplate/dialplate_view.c
<reponame>lzx8589561/X-UI #include "dialplate_view.h" #include "../../resource/resource_pool.h" #include "../../ui_page_manager.h" void dialplate_view_bottom_info_create(lv_obj_t* par); void dialplate_view_top_info_create(lv_obj_t* par); void dialplate_view_btn_cont_create(lv_obj_t* par); void dialplate_view_sub_info_grp_create(lv_obj_t* par, SubInfo_t* info, const char* unitText); lv_obj_t* dialplate_view_btn_create(lv_obj_t* par, const void* img_src, lv_coord_t x_ofs); void dialplate_view_create(lv_obj_t* root) { lv_obj_remove_style_all(root); lv_obj_set_size(root, LV_HOR_RES, LV_VER_RES); dialplate_view_bottom_info_create(root); dialplate_view_top_info_create(root); dialplate_view_btn_cont_create(root); dialplate_view_ui->anim_timeline = lv_anim_timeline_create(); #define ANIM_DEF(start_time, obj, attr, start, end) \ {start_time, obj, LV_ANIM_EXEC(attr), start, end, 500, lv_anim_path_ease_out, true} #define ANIM_OPA_DEF(start_time, obj) \ ANIM_DEF(start_time, obj, opa_scale, LV_OPA_TRANSP, LV_OPA_COVER) lv_coord_t y_tar_top = lv_obj_get_y(dialplate_view_ui->topInfo.cont); lv_coord_t y_tar_bottom = lv_obj_get_y(dialplate_view_ui->bottomInfo.cont); lv_coord_t h_tar_btn = lv_obj_get_height(dialplate_view_ui->btnCont.btnRec); lv_anim_timeline_wrapper_t wrapper[] = { ANIM_DEF(0, dialplate_view_ui->topInfo.cont, y, -lv_obj_get_height(dialplate_view_ui->topInfo.cont), y_tar_top), ANIM_DEF(200, dialplate_view_ui->bottomInfo.cont, y, -lv_obj_get_height(dialplate_view_ui->bottomInfo.cont), y_tar_bottom), ANIM_OPA_DEF(200, dialplate_view_ui->bottomInfo.cont), ANIM_DEF(500, dialplate_view_ui->btnCont.btnMap, height, 0, h_tar_btn), ANIM_DEF(600, dialplate_view_ui->btnCont.btnRec, height, 0, h_tar_btn), ANIM_DEF(700, dialplate_view_ui->btnCont.btnMenu, height, 0, h_tar_btn), LV_ANIM_TIMELINE_WRAPPER_END }; lv_anim_timeline_add_wrapper(dialplate_view_ui->anim_timeline, wrapper); } void dialplate_view_delete() { if(dialplate_view_ui->anim_timeline) { lv_anim_timeline_del(dialplate_view_ui->anim_timeline); dialplate_view_ui->anim_timeline = NULL; } } void dialplate_view_top_info_create(lv_obj_t* par) { lv_obj_t* cont = lv_obj_create(par); lv_obj_remove_style_all(cont); lv_obj_set_size(cont, LV_HOR_RES, 142); lv_obj_set_style_bg_opa(cont, LV_OPA_COVER, 0); lv_obj_set_style_bg_color(cont, lv_color_hex(0x333333), 0); lv_obj_set_style_radius(cont, 27, 0); lv_obj_set_y(cont, -36); dialplate_view_ui->topInfo.cont = cont; lv_obj_t* label = lv_label_create(cont); lv_obj_set_style_text_font(label, resource_pool_get_font("bahnschrift_65"), 0); lv_obj_set_style_text_color(label, lv_color_white(), 0); lv_label_set_text(label, "00"); lv_obj_align(label, LV_ALIGN_TOP_MID, 0, 63); dialplate_view_ui->topInfo.labelSpeed = label; label = lv_label_create(cont); lv_obj_set_style_text_font(label, resource_pool_get_font("bahnschrift_17"), 0); lv_obj_set_style_text_color(label, lv_color_white(), 0); lv_label_set_text(label, "km/h"); lv_obj_align_to(label, dialplate_view_ui->topInfo.labelSpeed, LV_ALIGN_OUT_BOTTOM_MID, 0, 8); dialplate_view_ui->topInfo.labelUint = label; } void dialplate_view_bottom_info_create(lv_obj_t* par) { lv_obj_t* cont = lv_obj_create(par); lv_obj_remove_style_all(cont); lv_obj_set_style_bg_color(cont, lv_color_black(), 0); lv_obj_set_size(cont, LV_HOR_RES, 90); lv_obj_align(cont, LV_ALIGN_TOP_MID, 0, 106); lv_obj_set_flex_flow(cont, LV_FLEX_FLOW_ROW_WRAP); lv_obj_set_flex_align( cont, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER ); dialplate_view_ui->bottomInfo.cont = cont; const char* unitText[4] = { "AVG", "Time", "Trip", "ABCalorie" }; for (int i = 0; i < ARRAY_SIZE(dialplate_view_ui->bottomInfo.labelInfoGrp); i++) { dialplate_view_sub_info_grp_create( cont, &(dialplate_view_ui->bottomInfo.labelInfoGrp[i]), unitText[i] ); } } void dialplate_view_sub_info_grp_create(lv_obj_t* par, SubInfo_t* info, const char* unitText) { lv_obj_t* cont = lv_obj_create(par); lv_obj_remove_style_all(cont); lv_obj_set_size(cont, 93, 39); lv_obj_set_flex_flow(cont, LV_FLEX_FLOW_COLUMN); lv_obj_set_flex_align( cont, LV_FLEX_ALIGN_SPACE_AROUND, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER ); lv_obj_t* label = lv_label_create(cont); lv_obj_set_style_text_font(label, resource_pool_get_font("bahnschrift_17"), 0); lv_obj_set_style_text_color(label, lv_color_white(), 0); info->lableValue = label; label = lv_label_create(cont); lv_obj_set_style_text_font(label, resource_pool_get_font("bahnschrift_13"), 0); lv_obj_set_style_text_color(label, lv_color_hex(0xb3b3b3), 0); lv_label_set_text(label, unitText); info->lableUnit = label; info->cont = cont; } void dialplate_view_btn_cont_create(lv_obj_t* par) { lv_obj_t* cont = lv_obj_create(par); lv_obj_remove_style_all(cont); lv_obj_set_size(cont, LV_HOR_RES, 40); lv_obj_align_to(cont, dialplate_view_ui->bottomInfo.cont, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); /*lv_obj_set_flex_flow(cont, LV_FLEX_FLOW_ROW); lv_obj_set_flex_place( cont, LV_FLEX_PLACE_SPACE_AROUND, LV_FLEX_PLACE_CENTER, LV_FLEX_PLACE_CENTER );*/ dialplate_view_ui->btnCont.cont = cont; dialplate_view_ui->btnCont.btnMap = dialplate_view_btn_create(cont, resource_pool_get_image("locate"), -80); dialplate_view_ui->btnCont.btnRec = dialplate_view_btn_create(cont, resource_pool_get_image("start"), 0); dialplate_view_ui->btnCont.btnMenu = dialplate_view_btn_create(cont, resource_pool_get_image("menu"), 80); } lv_obj_t* dialplate_view_btn_create(lv_obj_t* par, const void* img_src, lv_coord_t x_ofs) { lv_obj_t* obj = lv_obj_create(par); lv_obj_remove_style_all(obj); lv_obj_set_size(obj, 40, 31); lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE); lv_obj_align(obj, LV_ALIGN_CENTER, x_ofs, 0); lv_obj_set_style_bg_img_src(obj, img_src, 0); lv_obj_set_style_bg_opa(obj, LV_OPA_COVER, 0); lv_obj_set_style_width(obj, 45, LV_STATE_PRESSED); lv_obj_set_style_height(obj, 25, LV_STATE_PRESSED); lv_obj_set_style_bg_color(obj, lv_color_hex(0x666666), 0); lv_obj_set_style_bg_color(obj, lv_color_hex(0xbbbbbb), LV_STATE_PRESSED); lv_obj_set_style_bg_color(obj, lv_color_hex(0xff931e), LV_STATE_FOCUSED); lv_obj_set_style_radius(obj, 9, 0); static lv_style_transition_dsc_t tran; static const lv_style_prop_t prop[] = { LV_STYLE_WIDTH, LV_STYLE_HEIGHT, LV_STYLE_PROP_INV}; lv_style_transition_dsc_init( &tran, prop, lv_anim_path_ease_out, 200, 0, NULL ); lv_obj_set_style_transition(obj, &tran, LV_STATE_PRESSED); lv_obj_set_style_transition(obj, &tran, LV_STATE_FOCUSED); lv_obj_update_layout(obj); return obj; } void dialplate_view_appear_anim_start(bool reverse) { lv_anim_timeline_set_reverse(dialplate_view_ui->anim_timeline, reverse); lv_anim_timeline_start(dialplate_view_ui->anim_timeline); }
lzx8589561/X-UI
main/ui/page/start_up/start_up_view.h
#ifndef __STARTUP_VIEW_H #define __STARTUP_VIEW_H #ifdef __cplusplus extern "C" { #endif #include "lvgl/lvgl.h" typedef struct startup_view_t *startup_view_handler; struct startup_view_t{ lv_obj_t *cont; lv_obj_t *labelLogo; lv_anim_timeline_t *anim_timeline; }; void startup_view_create(lv_obj_t *root); void startup_view_delete(); extern startup_view_handler startup_view_ui; #ifdef __cplusplus } /*extern "C"*/ #endif #endif // !__VIEW_H
lzx8589561/X-UI
main/ui/page/status_bar/status_bar.h
#ifndef __STATUS_BAR_H #define __STATUS_BAR_H #ifdef __cplusplus extern "C" { #endif #include "lvgl/lvgl.h" typedef enum { STATUS_BAR_STYLE_TRANSP, STATUS_BAR_STYLE_BLACK, STATUS_BAR_STYLE_MAX } status_bar_style_t; void status_bar_init(lv_obj_t* par); void status_bar_set_style(status_bar_style_t style); void status_bar_appear(bool en); #ifdef __cplusplus } /*extern "C"*/ #endif #endif
lzx8589561/X-UI
main/controller/dialplate_controller.h
#ifndef DIALPLATE_CONTROLLER_H #define DIALPLATE_CONTROLLER_H void dialplate_controller_init(); #endif //DIALPLATE_CONTROLLER_H
lzx8589561/X-UI
main/ui/resource/resource_pool.h
<filename>main/ui/resource/resource_pool.h #ifndef RESOURCE_POOL_H #define RESOURCE_POOL_H #ifdef __cplusplus extern "C" { #endif #include "lvgl/lvgl.h" void resource_pool_init(); lv_font_t* resource_pool_get_font(const char* name); const void* resource_pool_get_image(const char* name); #ifdef __cplusplus } /*extern "C"*/ #endif #endif //RESOURCE_POOL_H
lzx8589561/X-UI
main/ui/app_entity_def.h
#ifndef APP_ENTITY_DEF_H #define APP_ENTITY_DEF_H #ifdef __cplusplus extern "C" { #endif /** * 定义全局实体 */ /** * 测试传输消息 */ typedef enum { TEST_MSG_TEST_DATA, TEST_MSG_SYNC_TEST_DATA }test_msg_t; /** * 定义UI所需的数据格式 */ typedef struct { int attr1; int attr2; int attr3; }test_data_t; #ifdef __cplusplus } /*extern "C"*/ #endif #endif //APP_ENTITY_DEF_H
lzx8589561/X-UI
main/ui/page/dialplate/dialplate.c
<filename>main/ui/page/dialplate/dialplate.c #include <stdio.h> #include <stdlib.h> #include "../../ui_page_manager.h" #include "../status_bar/status_bar.h" #include "dialplate_view.h" #include "dialplate.h" #include "../../app_entity_def.h" static page_base_handler pb = NULL; dialplate_view_heandler dialplate_view_ui = NULL; static lv_obj_t *lastFocus = NULL; static lv_timer_t *timer = NULL; static test_data_t *test_data = NULL; void dialplate_update(); void dialplateon_timer_update(lv_timer_t *timer); void dialplate_attach_event(lv_obj_t *obj); static void on_data_event(dc_data_msg_t *d); static void on_custom_attr_config() { set_custom_load_anim_type(pb, LOAD_ANIM_NONE, 500, lv_anim_path_ease_out); } static void on_view_load() { test_data = calloc(1, sizeof(test_data_t)); dialplate_view_ui = calloc(1, sizeof(struct dialplate_view_t)); dialplate_view_create(pb->root); dialplate_attach_event(dialplate_view_ui->btnCont.btnMap); dialplate_attach_event(dialplate_view_ui->btnCont.btnRec); dialplate_attach_event(dialplate_view_ui->btnCont.btnMenu); // 订阅主题 dc_subscribe("test_topic", on_data_event); } static void on_view_did_load() { } static void on_view_will_appear() { lv_group_focus_obj(dialplate_view_ui->btnCont.btnRec); status_bar_set_style(STATUS_BAR_STYLE_TRANSP); dialplate_update(); dialplate_view_appear_anim_start(false); } static void on_view_did_appear() { timer = lv_timer_create(dialplateon_timer_update, 1000, NULL); } static void on_view_will_disappear() { lv_timer_del(timer); } static void on_view_did_disappear() { } static void on_view_did_unload() { dialplate_view_delete(); // 清除页面指针 free(dialplate_view_ui); // 取消订阅 dc_unsubscribe("test_topic", on_data_event); } static void on_data_event(dc_data_msg_t *d) { if (strcmp(d->topic, "test_topic") == 0) { if (d->msg_type == TEST_MSG_TEST_DATA) { test_data_t *ptr = (test_data_t *) d->data; *test_data = *ptr; } } } void dialplate_on_btn_clicked(lv_obj_t *btn) { if (btn == dialplate_view_ui->btnCont.btnMap) { } else if (btn == dialplate_view_ui->btnCont.btnMenu) { // 点击菜单按钮 取消订阅 dc_unsubscribe("test_topic", on_data_event); } else if (btn == dialplate_view_ui->btnCont.btnRec) { // 点击录制按钮 订阅主题 dc_subscribe("test_topic", on_data_event); } } void dialplate_on_event(lv_event_t *event) { lv_obj_t *obj = lv_event_get_target(event); lv_event_code_t code = lv_event_get_code(event); if (code == LV_EVENT_SHORT_CLICKED) { dialplate_on_btn_clicked(obj); } } void dialplate_attach_event(lv_obj_t *obj) { lv_obj_add_event_cb(obj, dialplate_on_event, LV_EVENT_ALL, NULL); } void dialplateon_timer_update(lv_timer_t *timer) { dialplate_update(); } void dialplate_update() { // 同步请求 dc_data_msg_t msg = { .topic = "test_topic", .msg_type = TEST_MSG_SYNC_TEST_DATA, .data = "hello", }; dc_sync_req(&msg); char buf[16] = "0"; if(msg.sync_result){ sprintf(buf, "%s", (char *) msg.sync_result); // 释放发来的数据 free(msg.sync_result); } lv_label_set_text_fmt(dialplate_view_ui->topInfo.labelSpeed, "%s", buf); lv_label_set_text_fmt(dialplate_view_ui->bottomInfo.labelInfoGrp[0].lableValue, "%d km/h", 0); lv_label_set_text_fmt( dialplate_view_ui->bottomInfo.labelInfoGrp[1].lableValue, "a1:%d", test_data->attr1 ); lv_label_set_text_fmt( dialplate_view_ui->bottomInfo.labelInfoGrp[2].lableValue, "a2:%d", test_data->attr2 ); lv_label_set_text_fmt( dialplate_view_ui->bottomInfo.labelInfoGrp[3].lableValue, "a3:%d", test_data->attr3 ); } page_base_handler ui_page_register_dialplate() { UI_PAGE_FUN_INIT(); return pb; }
lzx8589561/X-UI
main/ui/page/status_bar/status_bar.c
<filename>main/ui/page/status_bar/status_bar.c #include <stdio.h> #include <stdlib.h> #include "status_bar.h" #define BATT_USAGE_HEIGHT (lv_obj_get_style_height(ui.battery.img, 0) - 6) #define BATT_USAGE_WIDTH (lv_obj_get_style_width(ui.battery.img, 0) - 4) #define STATUS_BAR_HEIGHT 22 #include "../../resource/resource_pool.h" #include "../../ui_page_manager.h" #include "../../app_entity_def.h" static void status_bar_anim_create(lv_obj_t* contBatt); static test_data_t *test_data = NULL; struct { lv_obj_t* cont; struct { lv_obj_t* img; lv_obj_t* label; } satellite; lv_obj_t* imgSD; lv_obj_t* labelClock; lv_obj_t* labelRec; struct { lv_obj_t* img; lv_obj_t* objUsage; lv_obj_t* label; } battery; } ui; static void status_bar_con_batt_set_opa(lv_obj_t* obj, int32_t opa) { lv_obj_set_style_opa(obj, opa, 0); } static void status_bar_on_anim_opa_finish(lv_anim_t* a) { lv_obj_t* obj = (lv_obj_t*)a->var; status_bar_con_batt_set_opa(obj, LV_OPA_COVER); status_bar_anim_create(obj); } static void status_bar_on_anim_height_finish(lv_anim_t* a) { lv_anim_t a_opa; lv_anim_init(&a_opa); lv_anim_set_var(&a_opa, a->var); lv_anim_set_exec_cb(&a_opa, (lv_anim_exec_xcb_t) status_bar_con_batt_set_opa); lv_anim_set_ready_cb(&a_opa, status_bar_on_anim_opa_finish); lv_anim_set_values(&a_opa, LV_OPA_COVER, LV_OPA_TRANSP); lv_anim_set_early_apply(&a_opa, true); lv_anim_set_delay(&a_opa, 500); lv_anim_set_time(&a_opa, 500); lv_anim_start(&a_opa); } static void status_bar_anim(void *var, int32_t v){ lv_obj_set_height((lv_obj_t*)var, v); } static void status_bar_anim_create(lv_obj_t* contBatt) { lv_anim_t a; lv_anim_init(&a); lv_anim_set_var(&a, contBatt); lv_anim_set_exec_cb(&a, status_bar_anim); lv_anim_set_values(&a, 0, BATT_USAGE_HEIGHT); lv_anim_set_time(&a, 1000); lv_anim_set_ready_cb(&a, status_bar_on_anim_height_finish); lv_anim_start(&a); } static void status_bar_update(lv_timer_t* timer) { /* satellite */ lv_label_set_text_fmt(ui.satellite.label, "%d", 7); lv_obj_clear_flag(ui.imgSD, LV_OBJ_FLAG_HIDDEN); // lv_obj_add_flag(ui.imgSD, LV_OBJ_FLAG_HIDDEN); /* clock */ lv_label_set_text_fmt(ui.labelClock, "%02d:%02d", test_data->attr1, test_data->attr2); /* battery */ lv_label_set_text_fmt(ui.battery.label, "%d", 66); bool is_batt_charging = true; lv_obj_t* contBatt = ui.battery.objUsage; static bool is_batt_charging_anim_active = false; if(is_batt_charging) { if(!is_batt_charging_anim_active) { status_bar_anim_create(contBatt); is_batt_charging_anim_active = true; } } else { if(is_batt_charging_anim_active) { lv_anim_del(contBatt, NULL); status_bar_con_batt_set_opa(contBatt, LV_OPA_COVER); is_batt_charging_anim_active = false; } lv_coord_t height = lv_map(34, 0, 100, 0, BATT_USAGE_HEIGHT); lv_obj_set_height(contBatt, height); } } static lv_obj_t* status_bar_create(lv_obj_t* par) { lv_obj_t* cont = lv_obj_create(par); lv_obj_remove_style_all(cont); lv_obj_set_size(cont, LV_HOR_RES, STATUS_BAR_HEIGHT); lv_obj_set_y(cont, -STATUS_BAR_HEIGHT); /* style1 */ lv_obj_set_style_bg_opa(cont, LV_OPA_TRANSP, LV_STATE_DEFAULT); lv_obj_set_style_bg_color(cont, lv_color_hex(0x333333), LV_STATE_DEFAULT); /* style2 */ lv_obj_set_style_bg_opa(cont, LV_OPA_60, LV_STATE_USER_1); lv_obj_set_style_bg_color(cont, lv_color_black(), LV_STATE_USER_1); lv_obj_set_style_shadow_color(cont, lv_color_black(), LV_STATE_USER_1); lv_obj_set_style_shadow_width(cont, 10, LV_STATE_USER_1); static lv_style_transition_dsc_t tran; static const lv_style_prop_t prop[] = { LV_STYLE_BG_COLOR, LV_STYLE_OPA, LV_STYLE_PROP_INV }; lv_style_transition_dsc_init( &tran, prop, lv_anim_path_ease_out, 200, 0, NULL ); lv_obj_set_style_transition(cont, &tran, LV_STATE_USER_1); ui.cont = cont; static lv_style_t style; lv_style_init(&style); lv_style_set_text_color(&style, lv_color_white()); lv_style_set_text_font(&style, resource_pool_get_font("bahnschrift_13")); /* satellite */ lv_obj_t* img = lv_img_create(cont); lv_img_set_src(img, resource_pool_get_image("satellite")); lv_obj_align(img, LV_ALIGN_LEFT_MID, 14, 0); ui.satellite.img = img; lv_obj_t* label = lv_label_create(cont); lv_obj_add_style(label, &style, 0); lv_obj_align_to(label, ui.satellite.img, LV_ALIGN_OUT_RIGHT_MID, 5, 0); lv_label_set_text(label, "0"); ui.satellite.label = label; /* sd card */ img = lv_img_create(cont); lv_img_set_src(img, resource_pool_get_image("sd_card")); lv_obj_align(img, LV_ALIGN_LEFT_MID, 50, -1); lv_obj_add_flag(img, LV_OBJ_FLAG_HIDDEN); ui.imgSD = img; /* clock */ label = lv_label_create(cont); lv_obj_add_style(label, &style, 0); lv_label_set_text(label, "00:00"); lv_obj_center(label); ui.labelClock = label; /* recorder */ label = lv_label_create(cont); lv_obj_add_style(label, &style, 0); lv_obj_align(label, LV_ALIGN_RIGHT_MID, -50, 0); lv_label_set_text(label, ""); lv_obj_add_flag(label, LV_OBJ_FLAG_HIDDEN); ui.labelRec = label; /* battery */ img = lv_img_create(cont); lv_img_set_src(img, resource_pool_get_image("battery")); lv_obj_align(img, LV_ALIGN_RIGHT_MID, -30, 0); lv_img_t* img_ext = (lv_img_t*)img; lv_obj_set_size(img, img_ext->w, img_ext->h); ui.battery.img = img; lv_obj_t* obj = lv_obj_create(img); lv_obj_remove_style_all(obj); lv_obj_set_style_bg_color(obj, lv_color_white(), 0); lv_obj_set_style_bg_opa(obj, LV_OPA_COVER, 0); lv_obj_set_style_opa(obj, LV_OPA_COVER, 0); lv_obj_set_size(obj, BATT_USAGE_WIDTH, BATT_USAGE_HEIGHT); lv_obj_align(obj, LV_ALIGN_BOTTOM_MID, 0, -2); ui.battery.objUsage = obj; label = lv_label_create(cont); lv_obj_add_style(label, &style, 0); lv_obj_align_to(label, ui.battery.img, LV_ALIGN_OUT_RIGHT_MID, 5, 0); lv_label_set_text(label, "100%"); ui.battery.label = label; status_bar_set_style(STATUS_BAR_STYLE_TRANSP); lv_timer_t* timer = lv_timer_create(status_bar_update, 1000, NULL); lv_timer_ready(timer); return ui.cont; } void status_bar_set_style(status_bar_style_t style) { lv_obj_t* cont = ui.cont; if (style == STATUS_BAR_STYLE_TRANSP) { lv_obj_add_state(cont, LV_STATE_DEFAULT); lv_obj_clear_state(cont, LV_STATE_USER_1); } else if (style == STATUS_BAR_STYLE_BLACK) { lv_obj_add_state(cont, LV_STATE_USER_1); } else { return; } } static void on_data_event(dc_data_msg_t *d){ if(strcmp(d->topic,"test_topic") == 0){ if(d->msg_type == TEST_MSG_TEST_DATA){ test_data_t *ptr = (test_data_t *) d->data; *test_data = *ptr; } } } void status_bar_init(lv_obj_t* par) { test_data = calloc(1, sizeof (test_data_t)); status_bar_create(par); dc_subscribe("test_topic", on_data_event); } void status_bar_appear(bool en) { int32_t start = -STATUS_BAR_HEIGHT; int32_t end = 0; if (!en) { int32_t temp = start; start = end; end = temp; } lv_anim_t a; lv_anim_init(&a); lv_anim_set_var(&a, ui.cont); lv_anim_set_values(&a, start, end); lv_anim_set_time(&a, 500); lv_anim_set_delay(&a, 1000); lv_anim_set_exec_cb(&a, LV_ANIM_EXEC(y)); lv_anim_set_path_cb(&a, lv_anim_path_ease_out); lv_anim_set_early_apply(&a, true); lv_anim_start(&a); }
lzx8589561/X-UI
main/ui/ui_page_manager.c
<reponame>lzx8589561/X-UI #include <stdio.h> #include "ui_page_manager.h" #include <stdlib.h> /** 是否开启日志 */ #define PAGE_MANAGER_USE_LOG 1 /** --- LOG --- */ #if PAGE_MANAGER_USE_LOG # define _PM_LOG(format, ...) printf("[PM]"format"\r\n", ##__VA_ARGS__) # define PM_LOG_INFO(format, ...) _PM_LOG("[Info] "format, ##__VA_ARGS__) # define PM_LOG_WARN(format, ...) _PM_LOG("[Warn] "format, ##__VA_ARGS__) # define PM_LOG_ERROR(format, ...) _PM_LOG("[Error] "format, ##__VA_ARGS__) #else # define PM_LOG_INFO(...) # define PM_LOG_WARN(...) # define PM_LOG_ERROR(...) #endif /** --- LOG --- */ /** --- PageManager private --- */ /* Page animation status */ struct { bool is_switch_req; // Whether to switch request bool is_busy; // Is switching bool is_pushing; // Whether it is in push state pm_page_anim_attr_t current; // Current animation properties pm_page_anim_attr_t global; // Global animation properties } anim_state; /** 私有变量定义 */ /* Page pool<page_base_handler> */ static pm_array_list_t *page_pool = NULL; /* Page stack<PageBase> */ static pm_stack_t *page_stack = NULL; /* Previous page */ static page_base_handler page_prev = NULL; /* The current page */ static page_base_handler page_current = NULL; /* Page Pool */ page_base_handler find_page_in_pool(const char *name); /* Page Stack */ page_base_handler find_page_in_stack(const char *name); page_base_handler get_stack_top(); page_base_handler get_stack_top_after(); void set_stack_clear(bool keep_bottom); bool fource_unload(page_base_handler base); /* Anim */ bool get_load_anim_attr(uint8_t anim, load_anim_attr_t *attr); bool get_is_over_anim(uint8_t anim) { return (anim >= LOAD_ANIM_OVER_LEFT && anim <= LOAD_ANIM_OVER_BOTTOM); } bool get_is_move_anim(uint8_t anim) { return (anim >= LOAD_ANIM_MOVE_LEFT && anim <= LOAD_ANIM_MOVE_BOTTOM); } void anim_default_init(lv_anim_t *a); load_anim_t get_current_load_anim_type() { return (load_anim_t) anim_state.current.type; } bool get_current_load_anim_attr(load_anim_attr_t *attr) { return get_load_anim_attr(get_current_load_anim_type(), attr); } /* Root */ static void on_root_drag_event(lv_event_t *event); static void on_root_anim_finish(lv_anim_t *a); static void on_root_async_leave(void *data); void root_enable_drag(lv_obj_t *root); static void root_get_drag_predict(lv_coord_t *x, lv_coord_t *y); /* Switch */ void switch_to(page_base_handler new_node, bool is_push_act, const pm_page_stash_t *stash); static void on_switch_anim_finish(lv_anim_t *a); void switch_anim_create(page_base_handler base); void switch_anim_type_update(page_base_handler base); bool switch_req_check(); bool switch_anim_state_check(); /* State */ pm_page_state_t state_load_execute(page_base_handler base); pm_page_state_t state_will_appear_execute(page_base_handler base); pm_page_state_t state_did_appear_execute(page_base_handler base); pm_page_state_t state_will_disappear_execute(page_base_handler base); pm_page_state_t state_did_disappear_execute(page_base_handler base); pm_page_state_t state_unload_execute(page_base_handler base); void state_update(page_base_handler base); pm_page_state_t state_get_state() { return page_current->priv.state; } /** --- PageManager private --- */ /** --- PageBase ---*/ /* Set whether to enable automatic cache */ void set_custom_auto_cache_enable(page_base_handler pb, bool en) { pb->priv.req_disable_auto_cache = !en; } /* Set whether to manually manage the cache */ void set_custom_cache_enable(page_base_handler pb, bool en) { set_custom_auto_cache_enable(pb, false); pb->priv.req_enable_cache = en; } /* Set custom animation properties */ void set_custom_load_anim_type(page_base_handler pb, uint8_t anim_type, uint16_t time, lv_anim_path_cb_t path ) { pb->priv.anim.attr.type = anim_type; pb->priv.anim.attr.time = time; pb->priv.anim.attr.path = path; } /* Get the data in the stash area */ bool pm_get_stash(page_base_handler pb, void *ptr, uint32_t size) { bool retval = false; if (pb->priv.stash.ptr != NULL && pb->priv.stash.size == size) { memcpy(ptr, pb->priv.stash.ptr, pb->priv.stash.size); //lv_mem_free(pb->priv.Stash.ptr); //pb->priv.Stash.ptr = NULL; retval = true; } return retval; } /** --- PageBase ---*/ /** --- PM_Base --- */ #define PM_EMPTY_PAGE_NAME "EMPTY_PAGE" /** * @brief Search pages in the page pool * @param name: Page name * @retval A pointer to the base class of the page, or NULL if not found */ page_base_handler find_page_in_pool(const char *name) { for (int i = 0; i < page_pool->length; i++) { page_base_handler iter = pm_array_list_get(page_pool, i); if (strcmp(name, iter->name) == 0) { return iter; } } return NULL; } /** * @brief Search pages in the page stack * @param name: Page name * @retval A pointer to the base class of the page, or NULL if not found */ page_base_handler find_page_in_stack(const char *name) { for (int i = 0; i < page_stack->length; ++i) { page_base_handler base = stack_get(page_stack, i); if (strcmp(name, base->name) == 0) { return base; } } return NULL; } /** * @brief Install the page, and register the page to the page pool * @param class_name: The class name of the page * @param app_name: Page application name, no duplicates allowed * @retval A pointer to the base class of the page, or NULL if wrong */ page_base_handler pm_install(const char *class_name, const char *app_name) { page_base_handler base = pm_create_page(class_name); if (base == NULL) { PM_LOG_ERROR("Factory has not %s", class_name); return NULL; } base->root = NULL; base->id = 0; base->user_data = NULL; memset(&base->priv, 0, sizeof(base->priv)); base->on_custom_attr_config(base); if (app_name == NULL) { PM_LOG_WARN("appName has not set"); app_name = class_name; } PM_LOG_INFO("Install Page[class = %s, name = %s]", class_name, app_name); pm_register(base, app_name); return base; } /** * @brief Uninstall page * @param app_name: Page application name, no duplicates allowed * @retval Return true if the uninstallation is successful */ bool pm_uninstall(const char *app_name) { PM_LOG_INFO("Page(%s) uninstall...", app_name); page_base_handler base = find_page_in_pool(app_name); if (base == NULL) { PM_LOG_ERROR("Page(%s) was not found", app_name); return false; } if (!pm_unregister(app_name)) { PM_LOG_ERROR("Page(%s) unregister failed", app_name); return false; } if (base->priv.is_cached) { PM_LOG_WARN("Page(%s) has cached, unloading...", app_name); base->priv.state = PAGE_STATE_UNLOAD; state_update(base); } else { PM_LOG_INFO("Page(%s) has not cache", app_name); } free(base); base = NULL; PM_LOG_INFO("Uninstall OK"); return true; } /** * @brief Register the page to the page pool * @param name: Page application name, duplicate registration is not allowed * @retval Return true if the registration is successful */ bool pm_register(page_base_handler base, const char *name) { if (find_page_in_pool(name) != NULL) { PM_LOG_ERROR("Page(%s) was multi registered", name); return false; } base->name = name; pm_array_list_insert(page_pool, base, -1); return true; } /** * @brief Log out the page from the page pool * @param name: Page application name * @retval Return true if the logout is successful */ bool pm_unregister(const char *name) { PM_LOG_INFO("Page(%s) unregister...", name); page_base_handler base = find_page_in_stack(name); if (base != NULL) { PM_LOG_ERROR("Page(%s) was in stack", name); return false; } base = find_page_in_pool(name); if (base == NULL) { PM_LOG_ERROR("Page(%s) was not found", name); return false; } page_base_handler iter = NULL; for (int i = 0; i < page_pool->length; ++i) { page_base_handler item = pm_array_list_get(page_pool, i); if (item == base) { iter = item; break; } } if (iter == NULL) { PM_LOG_ERROR("Page(%s) was not found in PagePool", name); return false; } pm_array_list_remove_p(page_pool, iter); PM_LOG_INFO("Unregister OK"); return true; } /** * @brief Get the top page of the page stack * @param None * @retval A pointer to the base class of the page */ page_base_handler get_stack_top() { return stack_empty(page_stack) ? NULL : stack_top(page_stack); } /** * @brief Get the page below the top of the page stack * @param None * @retval A pointer to the base class of the page */ page_base_handler get_stack_top_after() { page_base_handler top = get_stack_top(); if (top == NULL) { return NULL; } stack_pop(page_stack); page_base_handler top_after = get_stack_top(); stack_push(page_stack, top); return top_after; } /** * @brief Clear the page stack and end the life cycle of all pages in the page stack * @param keep_bottom: Whether to keep the bottom page of the stack * @retval None */ void set_stack_clear(bool keep_bottom) { while (1) { page_base_handler top = get_stack_top(); if (top == NULL) { PM_LOG_INFO("Page stack is empty, breaking..."); break; } page_base_handler top_after = get_stack_top_after(); if (top_after == NULL) { if (keep_bottom) { page_prev = top; PM_LOG_INFO("Keep page stack bottom(%s), breaking...", top->name); break; } else { page_prev = NULL; } } fource_unload(top); stack_pop(page_stack); } PM_LOG_INFO("Stack clear done"); } /** * @brief Get the name of the previous page * @param None * @retval The name of the previous page, if it does not exist, return PM_EMPTY_PAGE_NAME */ const char *pm_get_page_prev_name() { return page_prev ? page_prev->name : PM_EMPTY_PAGE_NAME; } /** --- PM_Base --- */ /** --- PM_Anim --- */ void dir_hor_anim_setter(void *obj, int32_t v) { lv_obj_set_x((lv_obj_t *) obj, v); } int32_t dir_hor_anim_getter(void *obj) { return (int32_t) lv_obj_get_x((lv_obj_t *) obj); } void dir_ver_anim_setter(void *obj, int32_t v) { lv_obj_set_y((lv_obj_t *) obj, v); } int32_t dir_ver_anim_getter(void *obj) { return (int32_t) lv_obj_get_y((lv_obj_t *) obj); } void opa_anim_setter(void *obj, int32_t v) { lv_obj_set_style_bg_opa((lv_obj_t *) obj, (lv_opa_t) v, LV_PART_MAIN); } int32_t opa_anim_getter(void *obj) { return (int32_t) lv_obj_get_style_bg_opa((lv_obj_t *) obj, LV_PART_MAIN); } /** * @brief Get page loading animation properties * @param anim: Animation type * @param attr: Pointer to attribute * @retval Whether the acquisition is successful */ bool get_load_anim_attr(uint8_t anim, load_anim_attr_t *attr) { lv_coord_t hor = LV_HOR_RES; lv_coord_t ver = LV_VER_RES; switch (anim) { case LOAD_ANIM_OVER_LEFT: attr->drag_dir = ROOT_DRAG_DIR_HOR; attr->push.enter.start = hor; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = 0; attr->pop.enter.start = 0; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = hor; break; case LOAD_ANIM_OVER_RIGHT: attr->drag_dir = ROOT_DRAG_DIR_HOR; attr->push.enter.start = -hor; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = 0; attr->pop.enter.start = 0; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = -hor; break; case LOAD_ANIM_OVER_TOP: attr->drag_dir = ROOT_DRAG_DIR_VER; attr->push.enter.start = ver; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = 0; attr->pop.enter.start = 0; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = ver; break; case LOAD_ANIM_OVER_BOTTOM: attr->drag_dir = ROOT_DRAG_DIR_VER; attr->push.enter.start = -ver; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = 0; attr->pop.enter.start = 0; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = -ver; break; case LOAD_ANIM_MOVE_LEFT: attr->drag_dir = ROOT_DRAG_DIR_HOR; attr->push.enter.start = hor; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = -hor; attr->pop.enter.start = -hor; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = hor; break; case LOAD_ANIM_MOVE_RIGHT: attr->drag_dir = ROOT_DRAG_DIR_HOR; attr->push.enter.start = -hor; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = hor; attr->pop.enter.start = hor; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = -hor; break; case LOAD_ANIM_MOVE_TOP: attr->drag_dir = ROOT_DRAG_DIR_VER; attr->push.enter.start = ver; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = -ver; attr->pop.enter.start = -ver; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = ver; break; case LOAD_ANIM_MOVE_BOTTOM: attr->drag_dir = ROOT_DRAG_DIR_VER; attr->push.enter.start = -ver; attr->push.enter.end = 0; attr->push.exit.start = 0; attr->push.exit.end = ver; attr->pop.enter.start = ver; attr->pop.enter.end = 0; attr->pop.exit.start = 0; attr->pop.exit.end = -ver; break; case LOAD_ANIM_FADE_ON: attr->drag_dir = ROOT_DRAG_DIR_NONE; attr->push.enter.start = LV_OPA_TRANSP; attr->push.enter.end = LV_OPA_COVER; attr->push.exit.start = LV_OPA_COVER; attr->push.exit.end = LV_OPA_COVER; attr->pop.enter.start = LV_OPA_COVER; attr->pop.enter.end = LV_OPA_COVER; attr->pop.exit.start = LV_OPA_COVER; attr->pop.exit.end = LV_OPA_TRANSP; break; case LOAD_ANIM_NONE: memset(attr, 0, sizeof(load_anim_attr_t)); return true; default: PM_LOG_ERROR("Load anim type error: %d", anim); return false; } /* Determine the setter and getter of the animation */ if (attr->drag_dir == ROOT_DRAG_DIR_HOR) { attr->setter = dir_hor_anim_setter; attr->getter = dir_hor_anim_getter; } else if (attr->drag_dir == ROOT_DRAG_DIR_VER) { attr->setter = dir_ver_anim_setter; attr->getter = dir_ver_anim_getter; } else { attr->setter = opa_anim_setter; attr->getter = opa_anim_getter; } return true; } /** --- PM_Anim --- */ /** --- PM_Drag --- */ #define CONSTRAIN(amt, low, high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) /* The distance threshold to trigger the drag */ #define PM_INDEV_DEF_DRAG_THROW 20 /** * @brief Page drag event callback * @param event: Pointer to event structure * @retval None */ static void on_root_drag_event(lv_event_t *event) { lv_obj_t *root = lv_event_get_target(event); page_base_handler base = (page_base_handler) lv_obj_get_user_data(root); if (base == NULL) { PM_LOG_ERROR("Page base is NULL"); return; } lv_event_code_t event_code = lv_event_get_code(event); load_anim_attr_t anim_attr; if (!get_current_load_anim_attr(&anim_attr)) { PM_LOG_ERROR("Can't get current anim attr"); return; } if (event_code == LV_EVENT_PRESSED) { if (anim_state.is_switch_req) return; if (!anim_state.is_busy) return; PM_LOG_INFO("Root anim interrupted"); lv_anim_del(root, anim_attr.setter); anim_state.is_busy = false; } else if (event_code == LV_EVENT_PRESSING) { lv_coord_t cur = anim_attr.getter(root); lv_coord_t max = anim_attr.pop.exit.start > anim_attr.pop.exit.end ? anim_attr.pop.exit.start : anim_attr.pop.exit.end; lv_coord_t min = anim_attr.pop.exit.start < anim_attr.pop.exit.end ? anim_attr.pop.exit.start : anim_attr.pop.exit.end; lv_point_t offset; lv_indev_get_vect(lv_indev_get_act(), &offset); if (anim_attr.drag_dir == ROOT_DRAG_DIR_HOR) { cur += offset.x; } else if (anim_attr.drag_dir == ROOT_DRAG_DIR_VER) { cur += offset.y; } anim_attr.setter(root, CONSTRAIN(cur, min, max)); } else if (event_code == LV_EVENT_RELEASED) { if (anim_state.is_switch_req) { return; } lv_coord_t offset_sum = anim_attr.push.enter.end - anim_attr.push.enter.start; lv_coord_t x_predict = 0; lv_coord_t y_predict = 0; root_get_drag_predict(&x_predict, &y_predict); lv_coord_t start = anim_attr.getter(root); lv_coord_t end = start; if (anim_attr.drag_dir == ROOT_DRAG_DIR_HOR) { end += x_predict; PM_LOG_INFO("Root drag x_predict = %d", end); } else if (anim_attr.drag_dir == ROOT_DRAG_DIR_VER) { end += y_predict; PM_LOG_INFO("Root drag y_predict = %d", end); } if (abs(end) > abs((int) offset_sum) / 2) { lv_async_call(on_root_async_leave, base); } else if (end != anim_attr.push.enter.end) { anim_state.is_busy = true; lv_anim_t a; anim_default_init(&a); lv_anim_set_var(&a, root); lv_anim_set_values(&a, start, anim_attr.push.enter.end); lv_anim_set_exec_cb(&a, anim_attr.setter); lv_anim_set_ready_cb(&a, on_root_anim_finish); lv_anim_start(&a); PM_LOG_INFO("Root anim start"); } } } /** * @brief Drag animation end event callback * @param a: Pointer to animation * @retval None */ static void on_root_anim_finish(lv_anim_t *a) { PM_LOG_INFO("Root anim finish"); anim_state.is_busy = false; } /** * @brief Enable root's drag function * @param root: Pointer to the root object * @retval None */ void root_enable_drag(lv_obj_t *root) { lv_obj_add_event_cb( root, on_root_drag_event, LV_EVENT_PRESSED, NULL ); lv_obj_add_event_cb( root, on_root_drag_event, LV_EVENT_PRESSING, NULL ); lv_obj_add_event_cb( root, on_root_drag_event, LV_EVENT_RELEASED, NULL ); PM_LOG_INFO("Root drag enabled"); } /** * @brief Asynchronous callback when dragging ends * @param data: Pointer to the base class of the page * @retval None */ static void on_root_async_leave(void *data) { page_base_handler base = (page_base_handler) data; PM_LOG_INFO("Page(%s) send event: LV_EVENT_LEAVE, need to handle...", base->name); lv_event_send(base->root, LV_EVENT_LEAVE, NULL); } /** * @brief Get drag inertia prediction stop point * @param x: x stop point * @param y: y stop point * @retval None */ static void root_get_drag_predict(lv_coord_t *x, lv_coord_t *y) { lv_indev_t *indev = lv_indev_get_act(); lv_point_t vect; lv_indev_get_vect(indev, &vect); lv_coord_t y_predict = 0; lv_coord_t x_predict = 0; while (vect.y != 0) { y_predict += vect.y; vect.y = vect.y * (100 - PM_INDEV_DEF_DRAG_THROW) / 100; } while (vect.x != 0) { x_predict += vect.x; vect.x = vect.x * (100 - PM_INDEV_DEF_DRAG_THROW) / 100; } *x = x_predict; *y = y_predict; } /** --- PM_Drag --- */ /** --- PM_Router --- */ /** * @brief Enter a new page, the old page is pushed onto the stack * @param name: The name of the page to enter * @param stash: Parameters passed to the new page * @retval Pointer to the page pushed onto the stack */ page_base_handler pm_push(const char *name, const pm_page_stash_t *stash) { /* Check whether the animation of switching pages is being executed */ if (!switch_anim_state_check()) { return NULL; } /* Check whether the stack is repeatedly pushed */ if (find_page_in_stack(name) != NULL) { PM_LOG_ERROR("Page(%s) was multi push", name); return NULL; } /* Check if the page is registered in the page pool */ page_base_handler base = find_page_in_pool(name); if (base == NULL) { PM_LOG_ERROR("Page(%s) was not install", name); return NULL; } /* Synchronous automatic cache configuration */ base->priv.is_disable_auto_cache = base->priv.req_disable_auto_cache; /* Push into the stack */ stack_push(page_stack, base); PM_LOG_INFO("Page(%s) push >> [Screen] (stash = 0x%p)", name, stash); /* Page switching execution */ switch_to(base, true, stash); return base; } /** * @brief Pop the current page * @param None * @retval Pointer to the next page */ page_base_handler pm_pop() { /* Check whether the animation of switching pages is being executed */ if (!switch_anim_state_check()) { return NULL; } /* Get the top page of the stack */ page_base_handler top = get_stack_top(); if (top == NULL) { PM_LOG_WARN("Page stack is empty, cat't pop"); return NULL; } /* Whether to turn off automatic cache */ if (!top->priv.is_disable_auto_cache) { PM_LOG_INFO("Page(%s) has auto cache, cache disabled", top->name); top->priv.is_cached = false; } PM_LOG_INFO("Page(%s) pop << [Screen]", top->name); /* Page popup */ stack_pop(page_stack); /* Get the next page */ top = get_stack_top(); if (top != NULL) { /* Page switching execution */ switch_to(top, false, NULL); } return top; } /** * @brief Page switching * @param new_node: Pointer to new page * @param is_push_act: Whether it is a push action * @param stash: Parameters passed to the new page * @retval None */ void switch_to(page_base_handler new_node, bool is_push_act, const pm_page_stash_t *stash) { if (new_node == NULL) { PM_LOG_ERROR("newNode is NULL"); return; } /* Whether page switching has been requested */ if (anim_state.is_switch_req) { PM_LOG_WARN("Page switch busy, reqire(%s) is ignore", new_node->name); return; } anim_state.is_switch_req = true; /* Is there a parameter to pass */ if (stash != NULL) { PM_LOG_INFO("stash is detect, %s >> stash(0x%p) >> %s", pm_get_page_prev_name(), stash, new_node->name); void *buffer = NULL; if (new_node->priv.stash.ptr == NULL) { buffer = lv_mem_alloc(stash->size); if (buffer == NULL) { PM_LOG_ERROR("stash malloc failed"); } else { PM_LOG_INFO("stash(0x%p) malloc[%d]", buffer, stash->size); } } else if (new_node->priv.stash.size == stash->size) { buffer = new_node->priv.stash.ptr; PM_LOG_INFO("stash(0x%p) is exist", buffer); } if (buffer != NULL) { memcpy(buffer, stash->ptr, stash->size); PM_LOG_INFO("stash memcpy[%d] 0x%p >> 0x%p", stash->size, stash->ptr, buffer); new_node->priv.stash.ptr = buffer; new_node->priv.stash.size = stash->size; } } /* Record current page */ page_current = new_node; /* If the current page has a cache */ if (page_current->priv.is_cached) { /* Direct display, no need to load */ PM_LOG_INFO("Page(%s) has cached, appear driectly", page_current->name); page_current->priv.state = PAGE_STATE_WILL_APPEAR; } else { /* Load page */ page_current->priv.state = PAGE_STATE_LOAD; } if (page_prev != NULL) { page_prev->priv.anim.is_enter = false; } page_current->priv.anim.is_enter = true; anim_state.is_pushing = is_push_act; if (anim_state.is_pushing) { /* Update the animation configuration according to the current page */ switch_anim_type_update(page_current); } /* Update the state machine of the previous page */ state_update(page_prev); /* Update the state machine of the current page */ state_update(page_current); /* Move the layer, move the new page to the front */ if (anim_state.is_pushing) { PM_LOG_INFO("Page PUSH is detect, move Page(%s) to foreground", page_current->name); if (page_prev)lv_obj_move_foreground(page_prev->root); lv_obj_move_foreground(page_current->root); } else { PM_LOG_INFO("Page POP is detect, move Page(%s) to foreground", pm_get_page_prev_name()); lv_obj_move_foreground(page_current->root); if (page_prev)lv_obj_move_foreground(page_prev->root); } } /** * @brief Force the end of the life cycle of the page without animation * @param base: Pointer to the page being executed * @retval Return true if successful */ bool fource_unload(page_base_handler base) { if (base == NULL) { PM_LOG_ERROR("Page is NULL, Unload failed"); return false; } PM_LOG_INFO("Page(%s) Fource unloading...", base->name); if (base->priv.state == PAGE_STATE_ACTIVITY) { PM_LOG_INFO("Page state is ACTIVITY, Disappearing..."); base->on_view_will_disappear(base); base->on_view_did_disappear(base); } base->priv.state = state_unload_execute(base); return true; } /** * @brief Back to the main page (the page at the bottom of the stack) * @param None * @retval Return true if successful */ bool pm_back_home() { /* Check whether the animation of switching pages is being executed */ if (!switch_anim_state_check()) { return false; } set_stack_clear(true); page_prev = NULL; page_base_handler home = get_stack_top(); switch_to(home, false, NULL); return true; } /** * @brief Check if the page switching animation is being executed * @param None * @retval Return true if it is executing */ bool switch_anim_state_check() { if (anim_state.is_switch_req || anim_state.is_busy) { PM_LOG_WARN( "Page switch busy[AnimState.IsSwitchReq = %d," "AnimState.IsBusy = %d]," "request ignored", anim_state.is_switch_req, anim_state.is_busy ); return false; } return true; } /** * @brief Page switching request check * @param None * @retval Return true if all pages are executed */ bool switch_req_check() { bool ret = false; bool last_node_busy = page_prev && page_prev->priv.anim.is_busy; if (!page_current->priv.anim.is_busy && !last_node_busy) { PM_LOG_INFO("----Page switch was all finished----"); anim_state.is_switch_req = false; ret = true; page_prev = page_current; } else { if (page_current->priv.anim.is_busy) { PM_LOG_WARN("Page PageCurrent(%s) is busy", page_current->name); } else { PM_LOG_WARN("Page PagePrev(%s) is busy", pm_get_page_prev_name()); } } return ret; } /** * @brief PPage switching animation execution end callback * @param a: Pointer to animation * @retval None */ static void on_switch_anim_finish(lv_anim_t *a) { page_base_handler base = (page_base_handler) a->user_data; PM_LOG_INFO("Page(%s) Anim finish", base->name); state_update(base); base->priv.anim.is_busy = false; bool is_finished = switch_req_check(); if (!anim_state.is_pushing && is_finished) { switch_anim_type_update(page_current); } } /** * @brief Create page switching animation * @param a: Point to the animated page * @retval None */ void switch_anim_create(page_base_handler base) { load_anim_attr_t anim_attr; if (!get_current_load_anim_attr(&anim_attr)) { return; } lv_anim_t a; anim_default_init(&a); a.user_data = base; lv_anim_set_var(&a, base->root); lv_anim_set_ready_cb(&a, on_switch_anim_finish); lv_anim_set_exec_cb(&a, anim_attr.setter); int32_t start = 0; if (anim_attr.getter) { start = anim_attr.getter(base->root); } if (anim_state.is_pushing) { if (base->priv.anim.is_enter) { lv_anim_set_values( &a, anim_attr.push.enter.start, anim_attr.push.enter.end ); } else /* Exit */ { lv_anim_set_values( &a, start, anim_attr.push.exit.end ); } } else /* Pop */ { if (base->priv.anim.is_enter) { lv_anim_set_values( &a, anim_attr.pop.enter.start, anim_attr.pop.enter.end ); } else /* Exit */ { lv_anim_set_values( &a, start, anim_attr.pop.exit.end ); } } lv_anim_start(&a); base->priv.anim.is_busy = true; } /** * @brief Set global animation properties * @param anim: Animation type * @param time: Animation duration * @param path: Animation curve * @retval None */ void pm_set_global_load_anim_type(load_anim_t anim, uint16_t time, lv_anim_path_cb_t path) { if (anim > _LOAD_ANIM_LAST) { anim = LOAD_ANIM_NONE; } anim_state.global.type = anim; anim_state.global.time = time; anim_state.global.path = path; PM_LOG_INFO("Set global load anim type = %d", anim); } /** * @brief Update current animation properties, apply page custom animation * @param base: Pointer to page * @retval None */ void switch_anim_type_update(page_base_handler base) { if (base->priv.anim.attr.type == LOAD_ANIM_GLOBAL) { PM_LOG_INFO( "Page(%s) Anim.type was not set, use AnimState.global.type = %d", base->name, anim_state.global.type ); anim_state.current = anim_state.global; } else { if (base->priv.anim.attr.type > _LOAD_ANIM_LAST) { PM_LOG_ERROR( "Page(%s) ERROR custom Anim.type = %d, use AnimState.global.type = %d", base->name, base->priv.anim.attr.type, anim_state.global.type ); base->priv.anim.attr = anim_state.global; } else { PM_LOG_INFO( "Page(%s) custom Anim.type set = %d", base->name, base->priv.anim.attr.type ); } anim_state.current = base->priv.anim.attr; } } /** * @brief Set animation default parameters * @param a: Pointer to animation * @retval None */ void anim_default_init(lv_anim_t *a) { lv_anim_init(a); uint32_t time = (get_current_load_anim_type() == LOAD_ANIM_NONE) ? 0 : anim_state.current.time; lv_anim_set_time(a, time); lv_anim_set_path_cb(a, anim_state.current.path); } /** --- PM_Router --- */ /** --- PM_State --- */ /** * @brief Update page state machine * @param base: Pointer to the updated page * @retval None */ void state_update(page_base_handler base) { if (base == NULL) return; switch (base->priv.state) { case PAGE_STATE_IDLE: PM_LOG_INFO("Page(%s) state idle", base->name); break; case PAGE_STATE_LOAD: base->priv.state = state_load_execute(base); state_update(base); break; case PAGE_STATE_WILL_APPEAR: base->priv.state = state_will_appear_execute(base); break; case PAGE_STATE_DID_APPEAR: base->priv.state = state_did_appear_execute(base); PM_LOG_INFO("Page(%s) state active", base->name); break; case PAGE_STATE_ACTIVITY: PM_LOG_INFO("Page(%s) state active break", base->name); base->priv.state = PAGE_STATE_WILL_DISAPPEAR; state_update(base); break; case PAGE_STATE_WILL_DISAPPEAR: base->priv.state = state_will_disappear_execute(base); break; case PAGE_STATE_DID_DISAPPEAR: base->priv.state = state_did_disappear_execute(base); if (base->priv.state == PAGE_STATE_UNLOAD) { state_update(base); } break; case PAGE_STATE_UNLOAD: base->priv.state = state_unload_execute(base); break; default: PM_LOG_ERROR("Page(%s) state[%d] was NOT FOUND!", base->name, base->priv.state); break; } } /** * @brief Page loading status * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_load_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state load", base->name); if (base->root != NULL) { PM_LOG_ERROR("Page(%s) root must be NULL", base->name); } lv_obj_t *root_obj = lv_obj_create(lv_scr_act()); lv_obj_set_size(root_obj, LV_HOR_RES, LV_VER_RES); lv_obj_clear_flag(root_obj, LV_OBJ_FLAG_SCROLLABLE); root_obj->user_data = base; base->root = root_obj; base->on_view_load(base); if (get_is_over_anim(get_current_load_anim_type())) { page_base_handler bottom_page = get_stack_top_after(); if (bottom_page != NULL && bottom_page->priv.is_cached) { load_anim_attr_t anim_attr; if (get_current_load_anim_attr(&anim_attr)) { if (anim_attr.drag_dir != ROOT_DRAG_DIR_NONE) { root_enable_drag(base->root); } } } } base->on_view_did_load(base); if (base->priv.is_disable_auto_cache) { PM_LOG_INFO("Page(%s) disable auto cache, ReqEnableCache = %d", base->name, base->priv.req_enable_cache); base->priv.is_cached = base->priv.req_enable_cache; } else { PM_LOG_INFO("Page(%s) AUTO cached", base->name); base->priv.is_cached = true; } return PAGE_STATE_WILL_APPEAR; } /** * @brief The page is about to show the status * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_will_appear_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state will appear", base->name); base->on_view_will_appear(base); lv_obj_clear_flag(base->root, LV_OBJ_FLAG_HIDDEN); switch_anim_create(base); return PAGE_STATE_DID_APPEAR; } /** * @brief The status of the page display * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_did_appear_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state did appear", base->name); base->on_view_did_appear(base); return PAGE_STATE_ACTIVITY; } /** * @brief The page is about to disappear * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_will_disappear_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state will disappear", base->name); base->on_view_will_disappear(base); switch_anim_create(base); return PAGE_STATE_DID_DISAPPEAR; } /** * @brief Page disappeared end state * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_did_disappear_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state did disappear", base->name); if (get_current_load_anim_type() == LOAD_ANIM_FADE_ON) { PM_LOG_INFO("AnimState.typeCurrent == LOAD_ANIM_FADE_ON, Page(%s) hidden", base->name); lv_obj_add_flag(base->root, LV_OBJ_FLAG_HIDDEN); } base->on_view_did_disappear(base); if (base->priv.is_cached) { PM_LOG_INFO("Page(%s) has cached", base->name); return PAGE_STATE_WILL_APPEAR; } else { return PAGE_STATE_UNLOAD; } } /** * @brief Page unload complete * @param base: Pointer to the updated page * @retval Next state */ pm_page_state_t state_unload_execute(page_base_handler base) { PM_LOG_INFO("Page(%s) state unload", base->name); if (base->root == NULL) { PM_LOG_WARN("Page is loaded!"); goto exit; } if (base->priv.stash.ptr != NULL && base->priv.stash.size != 0) { PM_LOG_INFO("Page(%s) free stash(0x%p)[%d]", base->name, base->priv.stash.ptr, base->priv.stash.size); lv_mem_free(base->priv.stash.ptr); base->priv.stash.ptr = NULL; base->priv.stash.size = 0; } lv_obj_del_async(base->root); base->root = NULL; base->priv.is_cached = false; base->on_view_did_unload(base); exit: return PAGE_STATE_IDLE; } /** --- PM_State --- */ /** --- ResourceManager ---*/ typedef struct resource_node_t { const char *name; void *ptr; } resource_node_t; bool search_node(resource_manager_handler rm, const char *name, resource_node_t *node) { for (int i = 0; i < rm->node_pool->length; i++) { resource_node_t *item = pm_array_list_get(rm->node_pool, i); if (strcmp(name, item->name) == 0) { *node = *item; return true; } } return false; } /** * @brief Add resources to the resource pool * @param name: Resource Name * @param ptr: Pointer to the resource * @retval Return true if the addition is successful */ bool rm_add_resource(resource_manager_handler rm, const char *name, void *ptr) { resource_node_t *node = calloc(1, sizeof(struct resource_node_t)); if (search_node(rm, name, node)) { PM_LOG_WARN("Resource: %s was register", name); return false; } node->name = name; node->ptr = ptr; pm_array_list_insert(rm->node_pool, node, -1); PM_LOG_INFO("Resource: %s[0x%p] add success", node->name, node->ptr); return true; } /** * @brief Remove resources from the resource pool * @param name: Resource Name * @retval Return true if the removal is successful */ bool rm_remove_resource(resource_manager_handler rm, const char *name) { resource_node_t node; if (!search_node(rm, name, &node)) { PM_LOG_ERROR("Resource: %s was not found", name); return false; } resource_node_t *find = NULL; for (int i = 0; i < rm->node_pool->length; ++i) { resource_node_t *item = pm_array_list_get(rm->node_pool, i); if (strcmp(item->name, name) == 0) { find = item; break; } } if (find == NULL) { PM_LOG_ERROR("Resource: %s was not found", name); return false; } pm_array_list_remove_p(rm->node_pool, find); PM_LOG_INFO("Resource: %s remove success", name); return true; } /** * @brief Get resource address * @param name: Resource Name * @retval If the acquisition is successful, return the address of the resource, otherwise return the default resource */ void *rm_get_resource(resource_manager_handler rm, const char *name) { resource_node_t node; if (!search_node(rm, name, &node)) { PM_LOG_WARN("Resource: %s was not found, return default[0x%p]", name, rm->default_ptr); return rm->default_ptr; } PM_LOG_INFO("Resource: %s[0x%p] was found", name, node.ptr); return node.ptr; } /** * @brief Set default resources * @param ptr: Pointer to the default resource * @retval None */ void rm_set_default(resource_manager_handler rm, void *ptr) { rm->default_ptr = ptr; PM_LOG_INFO("Resource: set [0x%p] to default", rm->default_ptr); } resource_manager_handler resource_manager_init() { resource_manager_handler rm = calloc(1, sizeof(struct resource_manager_t)); rm->default_ptr = NULL; rm->node_pool = pm_array_list_init(); return rm; } /** --- ResourceManager ---*/ /** --- lv_obj_ext_func ---*/ void lv_obj_set_opa_scale(lv_obj_t *obj, int16_t opa) { lv_obj_set_style_bg_opa(obj, (lv_opa_t) opa, LV_PART_MAIN); } int16_t lv_obj_get_opa_scale(lv_obj_t *obj) { return lv_obj_get_style_bg_opa(obj, LV_PART_MAIN); } /** * @brief 在label后追加字符串 * @param label:被追加的对象 * @param text:追加的字符串 * @retval 无 */ void lv_label_set_text_add(lv_obj_t *label, const char *text) { if (!label) return; lv_label_ins_text(label, strlen(lv_label_get_text(label)), text); } /** * @brief 为对象添加动画 * @param obj:对象地址 * @param a:动画控制器地址 * @param exec_cb:控制对象属性的函数地址 * @param start:动画的开始值 * @param end:动画的结束值 * @param time:动画的执行时间 * @param delay:动画开始前的延时时间 * @param ready_cb:动画结束事件回调 * @param path_cb:动画曲线 * @retval 无 */ void lv_obj_add_anim( lv_obj_t *obj, lv_anim_t *a, lv_anim_exec_xcb_t exec_cb, int32_t start, int32_t end, uint16_t time, uint32_t delay, lv_anim_ready_cb_t ready_cb, lv_anim_path_cb_t path_cb ) { lv_anim_t anim_temp; if (a == NULL) { a = &anim_temp; /* INITIALIZE AN ANIMATION *-----------------------*/ lv_anim_init(a); } /* MANDATORY SETTINGS *------------------*/ /*Set the "animator" function*/ lv_anim_set_exec_cb(a, exec_cb); /*Set the "animator" function*/ lv_anim_set_var(a, obj); /*Length of the animation [ms]*/ lv_anim_set_time(a, time); /*Set start and end values. E.g. 0, 150*/ lv_anim_set_values(a, start, end); /* OPTIONAL SETTINGS *------------------*/ /*Time to wait before starting the animation [ms]*/ lv_anim_set_delay(a, delay); /*Set the path in an animation*/ lv_anim_set_path_cb(a, path_cb); /*Set a callback to call when animation is ready.*/ lv_anim_set_ready_cb(a, ready_cb); /*Set a callback to call when animation is started (after delay).*/ lv_anim_set_start_cb(a, ready_cb); /* START THE ANIMATION *------------------*/ lv_anim_start(a); /*Start the animation*/ } void lv_obj_add_anim_def( lv_obj_t *obj, lv_anim_t *a, lv_anim_exec_xcb_t exec_cb, int32_t start, int32_t end ) { lv_obj_add_anim(obj, a, exec_cb, start, end, LV_ANIM_TIME_DEFAULT, 0, NULL, lv_anim_path_ease_out); } lv_indev_t *lv_get_indev(lv_indev_type_t type) { lv_indev_t *cur_indev = NULL; for (;;) { cur_indev = lv_indev_get_next(cur_indev); if (!cur_indev) { break; } if (cur_indev->driver->type == type) { return cur_indev; } } return NULL; } /** --- lv_obj_ext_func ---*/ /** --- lv_anim_timeline_wrapper ---*/ void lv_anim_timeline_add_wrapper(lv_anim_timeline_t *at, const lv_anim_timeline_wrapper_t *wrapper) { for (uint32_t i = 0; wrapper[i].obj != NULL; i++) { const lv_anim_timeline_wrapper_t *atw = &wrapper[i]; lv_anim_t a; lv_anim_init(&a); lv_anim_set_var(&a, atw->obj); lv_anim_set_values(&a, atw->start, atw->end); lv_anim_set_exec_cb(&a, atw->exec_cb); lv_anim_set_time(&a, atw->duration); lv_anim_set_path_cb(&a, atw->path_cb); lv_anim_set_early_apply(&a, atw->early_apply); lv_anim_timeline_add(at, atw->start_time, &a); } } /** --- lv_anim_timeline_wrapper ---*/ /** --- lv_label_anim_effect ---*/ void lv_label_anim_effect_init( lv_label_anim_effect_t *effect, lv_obj_t *cont, lv_obj_t *label_copy, uint16_t anim_time ) { lv_obj_t *label = lv_label_create(cont); effect->y_offset = (lv_obj_get_height(cont) - lv_obj_get_height(label_copy)) / 2 + 1; lv_obj_align_to(label, label_copy, LV_ALIGN_OUT_BOTTOM_MID, 0, effect->y_offset); effect->label_1 = label_copy; effect->label_2 = label; effect->value_last = 0; lv_anim_t a; lv_anim_init(&a); lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t) lv_obj_set_y); lv_anim_set_time(&a, anim_time); lv_anim_set_delay(&a, 0); lv_anim_set_path_cb(&a, lv_anim_path_ease_in_out); effect->anim_now = a; effect->anim_next = a; } void lv_label_anim_effect_check_value(lv_label_anim_effect_t *effect, uint8_t value, lv_anim_enable_t anim_enable) { /*如果值相等则不切换*/ if (value == effect->value_last) return; if (anim_enable == LV_ANIM_ON) { /*标签对象*/ lv_obj_t *next_label; lv_obj_t *now_label; /*判断两个标签的相对位置,确定谁是下一个标签*/ if (lv_obj_get_y(effect->label_2) > lv_obj_get_y(effect->label_1)) { now_label = effect->label_1; next_label = effect->label_2; } else { now_label = effect->label_2; next_label = effect->label_1; } lv_label_set_text_fmt(now_label, "%d", effect->value_last); lv_label_set_text_fmt(next_label, "%d", value); effect->value_last = value; /*对齐*/ lv_obj_align_to(next_label, now_label, LV_ALIGN_OUT_TOP_MID, 0, -effect->y_offset); /*计算需要的Y偏移量*/ lv_coord_t y_offset = abs(lv_obj_get_y(now_label) - lv_obj_get_y(next_label)); /*滑动动画*/ lv_anim_t *a; a = &(effect->anim_now); lv_anim_set_var(a, now_label); lv_anim_set_values(a, lv_obj_get_y(now_label), lv_obj_get_y(now_label) + y_offset); lv_anim_start(a); a = &(effect->anim_next); lv_anim_set_var(a, next_label); lv_anim_set_values(a, lv_obj_get_y(next_label), lv_obj_get_y(next_label) + y_offset); lv_anim_start(a); } else { lv_label_set_text_fmt(effect->label_1, "%d", value); lv_label_set_text_fmt(effect->label_2, "%d", value); effect->value_last = value; } } /** --- lv_label_anim_effect ---*/ /** --- stack ---*/ pm_stack_t *stack_init() { pm_stack_t *pStack = (pm_stack_t *) malloc(sizeof(pm_stack_t)); if (pStack == NULL) { return NULL; } pStack->node = (pm_stack_node_t *) malloc(STACK_INIT_SIZE * sizeof(pm_stack_node_t)); if (pStack->node == NULL) { free(pStack); return NULL; } for (int i = 0; i < STACK_INIT_SIZE; i++) { pStack->node[i].data = NULL; } pStack->length = 0; pStack->size = STACK_INIT_SIZE; return pStack; } void *stack_pop(pm_stack_t *stack) { if (stack == NULL || stack->length == 0) return NULL; void *data = stack->node[stack->length - 1].data; stack->node[stack->length - 1].data = NULL; stack->length--; return data; } void *stack_get(pm_stack_t *stack, int index) { if (stack == NULL || stack->length == 0 || index > (stack->length - 1)) return NULL; return stack->node[index].data; } void *stack_top(pm_stack_t *stack) { if (stack == NULL || stack->length == 0) return NULL; return stack->node[stack->length - 1].data; } int stack_empty(pm_stack_t *stack) { if (stack == NULL) return 1; return stack->length == 0; } int stack_push(pm_stack_t *stack, void *data) { if (stack == NULL) return 0; if (stack->length == stack->size - 1) { unsigned long realloc_size = stack->size + STACK_INCREASE_SIZE; stack->node = (pm_stack_node_t *) realloc(stack->node, realloc_size * sizeof(pm_stack_node_t)); if (stack->node == NULL) { return 0; } for (unsigned long i = stack->length; i < realloc_size; i++) { stack->node[i].data = NULL; } stack->size = realloc_size; } stack->node[stack->length].data = data; stack->length++; return 1; } /** --- stack ---*/ /** --- array_list ---*/ pm_array_list_t *pm_array_list_init() { pm_array_list_t *p_list = (pm_array_list_t *) malloc(sizeof(pm_array_list_t)); if (p_list == NULL) { return NULL; } p_list->node = (pm_array_node_t *) malloc(PM_ARRAY_LIST_INIT_SIZE * sizeof(pm_array_node_t)); if (p_list->node == NULL) { free(p_list); return NULL; } for (int i = 0; i < PM_ARRAY_LIST_INIT_SIZE; i++) { p_list->node[i].data = NULL; } p_list->length = 0; p_list->size = PM_ARRAY_LIST_INIT_SIZE; return p_list; } int pm_array_list_insert(pm_array_list_t *p_list, void *p_data, long index) { if (p_list == NULL) return -1; if (index < -1 || (index > p_list->length && index != -1)) { return -1; } if (p_list->length == p_list->size - 1) { unsigned long realloc_size = p_list->size + PM_ARRAY_LIST_INCREASE_SIZE; p_list->node = (pm_array_node_t *) realloc(p_list->node, realloc_size * sizeof(pm_array_node_t)); if (p_list->node == NULL) { return -1; } for (int i = p_list->length; i < realloc_size; i++) { p_list->node[i].data = NULL; } p_list->size = realloc_size; } if (index == -1) { p_list->node[p_list->length].data = p_data; p_list->length++; return 0; } else if (index == 0) { for (int i = p_list->length; i > 0; i--) { p_list->node[i] = p_list->node[i - 1]; } p_list->node[0].data = p_data; p_list->length++; return 0; } else { int i; for (i = p_list->length; i > index; i--) { p_list->node[i] = p_list->node[i - 1]; } p_list->node[i].data = p_data; p_list->length++; return 0; } return 0; } void pm_array_list_remove(pm_array_list_t *p_list, unsigned long index) { if (p_list == NULL) return; if (index < 0 || index >= p_list->length) return; for (int i = index; i < p_list->length; i++) { p_list->node[i] = p_list->node[i + 1]; } p_list->node[p_list->length - 1].data = NULL; p_list->length--; } void pm_array_list_remove_p(pm_array_list_t *p_list, void *p_data) { if (p_list == NULL) return; for (int i = 0; i < p_list->length; ++i) { if (p_list->node[i].data == p_data) { pm_array_list_remove(p_list, i); break; } } } void *pm_array_list_get(pm_array_list_t *p_list, unsigned long index) { void *p_data = NULL; if (p_list == NULL) { return NULL; } if (index < 0 || index >= p_list->length) { return NULL; } p_data = p_list->node[index].data; return p_data; } void pm_array_list_clear(pm_array_list_t *p_list) { int i = 0; if (p_list == NULL) { return; } for (i = 0; i < p_list->length; i++) { if (p_list->node[i].data != NULL) { p_list->node[i].data = NULL; } } p_list->length = 0; } void pm_array_list_free(pm_array_list_t *p_list) { if (p_list == NULL) return; if (p_list->node != NULL) { free(p_list->node); p_list->node = NULL; } free(p_list); p_list = NULL; } /** --- array_list ---*/ /** --- data_center --- */ /** <dc_topic_subscribe_t> */ static pm_array_list_t *dc_topic_list = NULL; /** <dc_page_data_msg_t> */ static pm_array_list_t *dc_msg_list = NULL; static pm_array_list_t *dc_temp_del_list = NULL; static dc_topic_subscribe_t *find_topic(const char *topic){ dc_topic_subscribe_t *topic_subscribe = NULL; for (int i = 0; i < dc_topic_list->length; ++i) { dc_topic_subscribe_t *item = pm_array_list_get(dc_topic_list, i); if(strcmp(item->topic,topic) == 0){ topic_subscribe = item; break; } } return topic_subscribe; } void dc_subscribe(const char *topic,dc_callback c){ dc_topic_subscribe_t *topic_subscribe = find_topic(topic); if(!topic_subscribe){ topic_subscribe = calloc(1, sizeof (dc_topic_subscribe_t)); topic_subscribe->topic = topic; topic_subscribe->subscribe_list = pm_array_list_init(); pm_array_list_insert(dc_topic_list, topic_subscribe, -1); } bool find_c = false; for (int i = 0; i < topic_subscribe->subscribe_list->length; ++i) { dc_callback c_item = pm_array_list_get(topic_subscribe->subscribe_list, i); if(c == c_item){ find_c = true; break; } } if(!find_c){ pm_array_list_insert(topic_subscribe->subscribe_list, c, -1); } } void dc_unsubscribe(const char *topic,dc_callback c){ dc_topic_subscribe_t *topic_subscribe = find_topic(topic); if(topic_subscribe){ pm_array_list_remove_p(topic_subscribe->subscribe_list, c); } } void dc_publish(dc_data_msg_t *data_msg){ if(data_msg){ data_msg->sync = false; pm_array_list_insert(dc_msg_list, data_msg, -1); } } void dc_sync_req(dc_data_msg_t *data_msg){ data_msg->sync = true; dc_topic_subscribe_t *topic_subscribe = find_topic(data_msg->topic); if(topic_subscribe){ if(topic_subscribe->subscribe_list->length > 0){ for (int j = 0; j < topic_subscribe->subscribe_list->length; ++j) { dc_callback c = pm_array_list_get(topic_subscribe->subscribe_list, j); if(c){ c(data_msg); } } } } } dc_data_msg_t * dc_create_msg(const char *topic){ dc_data_msg_t *msg = calloc(1, sizeof (dc_data_msg_t)); msg->topic = topic; return msg; } void data_center(){ if(dc_msg_list->length > 0){ for (int i = 0; i < dc_msg_list->length; ++i) { dc_data_msg_t *data_msg = pm_array_list_get(dc_msg_list, i); dc_topic_subscribe_t *topic_subscribe = find_topic(data_msg->topic); if(topic_subscribe){ for (int j = 0; j < topic_subscribe->subscribe_list->length; ++j) { dc_callback c = pm_array_list_get(topic_subscribe->subscribe_list, j); if(c){ c(data_msg); } } } pm_array_list_insert(dc_temp_del_list, data_msg, -1); } } if(dc_temp_del_list->length > 0){ for (int i = 0; i < dc_temp_del_list->length; ++i) { dc_data_msg_t *data_msg = pm_array_list_get(dc_temp_del_list, i); pm_array_list_remove_p(dc_msg_list, data_msg); if(data_msg->data){ free(data_msg->data); } free(data_msg); } pm_array_list_clear(dc_temp_del_list); } } /** --- data_center --- */ /** * @brief Page manager constructor * @param factory: Pointer to the page factory * @retval None */ void ui_page_manager_init() { page_prev = NULL; page_current = NULL; memset(&anim_state, 0, sizeof(anim_state)); page_stack = stack_init(); page_pool = pm_array_list_init(); // data center init dc_topic_list = pm_array_list_init(); dc_msg_list = pm_array_list_init(); dc_temp_del_list = pm_array_list_init(); pm_set_global_load_anim_type(LOAD_ANIM_OVER_LEFT, 500, lv_anim_path_ease_out); }