repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Akshat69/SFML-RPG
SFML-RPG/TileMap.h
<gh_stars>0 #pragma once #include "Tile.h" #include "stdafx.h" class TileMap { unsigned gridSizeU, gridSizeF, layers; sf::Vector2u maxSize; std::vector<std::vector<std::vector<Tile>>> tilemap; public: TileMap(); ~TileMap(); void Update(const float& DeltaTime); void Render(sf::RenderTarget* target); };
Akshat69/SFML-RPG
SFML-RPG/MovementComponent.h
<gh_stars>0 #pragma once #include "stdafx.h" class MovementComponent { private: sf::Sprite& sprite; float maxVelocity; float acceleration; float deceleration; sf::Vector2f initialVelocity = sf::Vector2f(0.0f, 0.0f); sf::Vector2f Velocity; //Initializer Functions public: bool isEnabled = true; MovementComponent(sf::Sprite& sprite, float maxVelocity, float acceleration, float deceleration); ~MovementComponent(); //Getters const sf::Vector2f& getVelocity() const { return this->Velocity; } void move(const float dirX, const float dirY, const float& DeltaTime); void Update(const float& DeltaTime); };
Akshat69/SFML-RPG
SFML-RPG/AudioComponent.h
#pragma once #include "stdafx.h" class AudioComponent { private: sf::Music music; std::map<std::string, std::string> audios; public: void Play(bool looping = false); void Stop(); void initVariables(); AudioComponent(const std::string& audioFile); ~AudioComponent(); };
Akshat69/SFML-RPG
SFML-RPG/stdafx.h
<reponame>Akshat69/SFML-RPG<filename>SFML-RPG/stdafx.h<gh_stars>0 //Core #include <algorithm> #include <deque> #include <iostream> #include <map> #include <memory> #include <set> #include <thread> #include <utility> #include <vector> #include <list> #include <stack> #include <string> #include <sstream> #include <fstream> #include <cmath> //SFML #include <SFML\System.hpp> #include <SFML\Window.hpp> #include <SFML\Graphics.hpp> #include <SFML\Audio.hpp> #include <SFML\Network.hpp>
Akshat69/SFML-RPG
SFML-RPG/Entity.h
<gh_stars>0 #pragma once #include "HitboxComponent.h" #include "MovementComponent.h" #include "AnimationComponent.h" class Entity { private: protected: sf::Sprite sprite; MovementComponent* movementComponent; AnimationComponent* animationComponent; HitboxComponent* hitboxComponent; float movementSpeed = 100.0f; void initVariables(); public: sf::RenderWindow* window; Entity(sf::RenderWindow* window); virtual ~Entity(); //Component Functions void setTexture(sf::Texture* texture); void createMovementComponent(float maxVelocity, float acceleration, float deceleration); void createAnimationComponent(sf::Texture& texture_sheet); void createHitboxComponent(sf::Vector2f offset, sf::Vector2f size); //Functions virtual void setPosition(const float posX, const float posY); virtual void move(const float& DeltaTime, const float dirX, const float dirY); virtual void moveTo(const float& DeltaTime, const float posX, const float posY); virtual void Update(const float& DeltaTime); virtual void Render(sf::RenderTarget* target = nullptr); };
github188/catlib
test/testshell.c
<filename>test/testshell.c<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <cat/shell.h> #include <cat/stduse.h> #include <cat/str.h> int func(struct shell_env *env, int nargs, char *args[], struct shell_value *r); struct shell_cmd_entry cmds[] = { {"ival", func}, {"uval", func}, {"dval", func}, {"sval", func}, {"pval", func}, {"help", func}, }; DECLARE_SHELL_ENV(env, cmds); int func(struct shell_env *env, int nargs, char *args[], struct shell_value *rv) { int nrequired = 1; printf("function f (int) -- %d\n", *(int*)env->se_ctx); if ( strcmp(args[0], "help") == 0 ) nrequired = 0; if ( nargs != nrequired+1 ) { printf("need %d argument got %d\n", nrequired, nargs-1); return -1; } if ( strcmp(args[0], "ival") == 0 ) { int ival; printf("arg = /%s/\n", args[1]); if ( shell_arg2int(env, args[1], &ival) < 0 ) goto err; printf("Integer val: %d\n", ival); rv->sval_type = SVT_INT; rv->sval_int = ival; rv->sval_free = NULL; } else if ( strcmp(args[0], "uval") == 0 ) { unsigned int uval; if ( shell_arg2uint(env, args[1], &uval) < 0 ) goto err; printf("Unsigned Integer val: %u\n", uval); rv->sval_type = SVT_UINT; rv->sval_uint = uval; rv->sval_free = NULL; } else if ( strcmp(args[0], "dval") == 0 ) { double dval; if ( shell_arg2dbl(env, args[1], &dval) < 0 ) goto err; printf("Double val: %f\n", dval); rv->sval_type = SVT_DOUBLE; rv->sval_dbl = dval; rv->sval_free = NULL; } else if ( strcmp(args[0], "sval") == 0 ) { char *sval; if ( shell_arg2str(env, args[1], &sval) < 0 ) goto err; printf("String val: %s\n", sval); rv->sval_type = SVT_STRING; rv->sval_str = str_copy_a(sval); rv->sval_mm = &estdmm; rv->sval_free = mem_free; } else if ( strcmp(args[0], "pval") == 0 ) { void *pval; if ( shell_arg2ptr(env, args[1], &pval) < 0 ) goto err; printf("Pointer val: %p\n", pval); rv->sval_type = SVT_PTR; rv->sval_ptr = pval; rv->sval_free = NULL; } else { printf("Commands: ival, uval, dval, sval, pval\n"); printf("Syntax: [VAR=] <cmd> <value>\n"); printf("Ctrl-D (on UNIX) ends the program.\n\n"); } return 0; err: return -1; } int main(int argc, char *argv[]) { char line[256]; unsigned int ctx = 0; env.se_ctx = &ctx; while ( fgets(line, sizeof(line), stdin) ) { ++ctx; if ( line[0] != '\0' && line[strlen(line)-1] != '\n' ) { fprintf(stderr, "line too long!\n"); break; } if ( shell_run(&env, line) < 0 ) fprintf(stderr, "Error running line\n"); } return 0; }
github188/catlib
attic/mcache.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/mcache.h> void mc_init(struct mcache *mc, int pglen, memctl_f mctl) { Assert(mc); Assert(slabsize > sizeof(union mc_pool_u) || (!slabsize && !mctl)); l_init(&mc->types); l_init(&mc->pages); mc->pglen = pglen; mc->mctl = mctl; } void mc_inittype(struct mc_type *type, struct mc_tdesc *tdesc, int maxalloc, int maxcache); { /* lots of sanity checks */ Assert(type); Assert(tdesc); Assert(maxalloc >= 0); Assert(tdesc->pgsiz >= sizeof(union mc_page_u)); Assert(tdesc->init); Assert(tdesc->alloc); Assert(tdesc->free); l_init(&type->entry); l_init(&type->avail); l_init(&type->empty); l_init(&type->cache); type->tdesc = *tdesc; type->maxalloc = maxalloc; type->maxcache = maxcache; type->clen = 0; } void mc_addtype(struct mcache *mc, struct mc_type *type) { Assert(mc); Assert(type); l_ins(&mc->types, &type->entry); type->mcache = mc; } void mc_freetype(struct mc_type *type) { struct mcache *mc; struct mc_page *mcp; struct list *lp; Assert(type); mc = type->mcache; for ( lp = l_head(&type->avail) ; lp != l_end(&type->avail) ; ) { mcp = base(lp, struct mc_page, te); lp = lp->next; l_rem(&mcp->ce); l_rem(&mcp->te); if ( mcp->isdyn ) mc->mctl(mcp, 0); } for ( lp = l_head(&type->empty) ; lp != l_end(&type->empty) ; ) { mcp = base(lp, struct mc_page, te); lp = lp->next; l_rem(&mcp->ce); l_rem(&mcp->te); if ( mcp->isdyn ) mc->mctl(mcp, 0); } for ( lp = l_head(&type->cache) ; lp != l_end(&type->cache) ; ) { mcp = base(lp, struct mc_page, te); lp = lp->next; l_rem(&mcp->ce); l_rem(&mcp->te); if ( mcp->isdyn ) mc->mctl(mcp, 0); } l_rem(&type->entry); } void mc_addpage(struct mcache *mc, void *page, int plen) { struct mc_page *mcp; Assert(mc); Assert(page); Assert(plen >= sizeof(union mc_page_u)); mcp = page; l_init(&mcp->te); l_init(&mcp->ce); mcp->type = NULL; mcp->siz = plen; mcp->avail = mcp->total = 0; l_ins(&mc->pages, &mcp->ce); } void mc_rempage(struct mc_page *mcp) { l_rem(&mcp->te); l_rem(&mcp->ce); mcp->type = NULL; } void * mc_alloc(struct mc_type *type, int len) { struct mcache *mc; struct mc_page *mcp; void *item; struct list *lp; Assert(type); Assert(len > 0); mc = type->mcache; if ( !l_isempty(&type->avail) ) { mcp = base(l_head(&type->avail), struct mc_page, te); } else if ( !l_isempty(&type->cache) ) { mcp = base(l_head(&type->avail), struct mc_page, te); l_rem(&mcp->te); l_rem(&mcp->ce); l_ins(&type->avail, &mcp->te); type->clen -= 1; } else if ( !l_isempty(&mc->pages) ) { for ( lp = l_head(&mc->pages ; lp != l_end(&mc->pages) ; lp = lp->next ) { mcp = base(lp, struct mc_page, ce); if ( mcp->siz <= type->tdesc.pgsiz + len + MC_MAXOHEAD ) break; if ( lp == l_end(&mc->pages) ) { mcp = NULL; } else { if ( mcp->type ) mcp->type->clen -= 1; l_rem(&mcp->te); l_rem(&mcp->ce); mcp->type = type; type->tdesc.init(mcp, mcp->siz); l_ins(&type->avail, &mcp->te); } } } if ( mcp == NULL ) { if ( ! mc->mctl ) return NULL; /* TODO: adjust mc->pglen? */ mcp = mc->mctl(NULL, mc->pglen); mcp->siz = mc->pglen; mcp->type = type; type->tdesc.init(mcp, mc->pglen); mcp->isdyn = 1; l_ins(&type->avail, &mcp->te); } /* by here we have a page with the available space */ item = type->tdesc.alloc(mcp, len); if ( mcp->avail == 0 ) { l_rem(&mcp->te); l_ins(&type->empty, &mcp->te); } return item; } void mc_free(void *item) { struct mc_page *mcp; struct mc_type *type; struct mcache *mc; int wasempty; Assert(item); /* ASSUMPTION: the cat_pitem_t bytes before item contain a pointer */ /* which points to memory immediately AFTER the memory page the item */ /* was allocated from */ mcp = (struct mc_page *) *(char **)((char *)item-sizeof(cat_pitem_t)) - sizeof(union mc_page_u); wasempty = mcp->avail == 0; type = mcp->type; type->tdesc.free(mcp, item); if ( wasempty ) { l_rem(&mcp->te); l_ins(&type->avail, &mcp->te); } if ( mcp->total == mcp->avail ) { l_rem(&mcp->te); mc = type->mcache; /* if the cache is full then: if the page was dynamically allocated free it otherwise put it on the page list with NO type */ if ( type->clen == type->maxcache ) { if ( mcp->isdyn ) { mc->mctl(mcp, 0); } else { mcp->type = NULL; l_ins(&mc->pages, &mcp->ce); } /* if the cache isn't full, put the page on the cache and */ /* in the total list of pages */ } else { type->clen += 1; l_ins(&type->cache, &mcp->te); l_ins(mc->pages.prev, &mcp->ce); } } } struct mc_tdesc mc_pooldesc = { sizeof(union mc_pool_u); mc_pl_initpg, mc_pl_alloc, mc_pl_free } ; void mc_pl_initpg(void *pagep, int siz) { char *page; struct mc_page *mcp; struct mc_pool *pl; Assert(pagep); Assert(siz >= sizeof(union mc_pool_u)); page = pagep; mcp = pagep; Assert(mcp->type->asiz > 0); pl = (struct mc_pool *)mcp; page += sizeof(union mc_pool_u); siz -= sizeof(union mc_pool_u); pl2_init(&pl->pool, mcp->type->asiz, page, siz, &mcp->total); pl->isiz = pl2_isiz(siz); mcp->total *= pl->isiz; mcp->avail = mcp->total; } void * mc_pl_alloc(struct mc_page *mcp, int len) { struct mc_pool *pl; void *item; Assert(mcp); Assert(mcp->type); Assert(len <= mcp->type->asiz); pl = (struct mc_pool *)mcp; item = pl2_alloc(&pl->pool); Assert(item); mcp->avail -= pl->isiz; } void mc_pl_free(struct mc_page *mcp, void *item) { struct mc_pool *pl; Assert(mcp); Assert(item); pl2_free(item); pl = (struct mc_pool *)mcp; mcp->avail += pl->isiz; }
github188/catlib
include/cat/dbgmem.h
<gh_stars>1-10 /* * dbgmem.h -- Memory management API instrumented for debugging. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __dbgmem_h #define __dbgmem_h #include <cat/cat.h> #include <cat/mem.h> void *dbg_mem_get(struct memmgr *mm, size_t amt); void *dbg_mem_resize(struct memmgr *mm, void *p, size_t newsize); void dbg_mem_free(struct memmgr *mm, void *p); ulong dbg_get_num_alloc(void); ulong dbg_get_alloc_amt(void); int dbg_is_dyn_mem(void *ptr); void dbg_mem_reset(void); extern struct memmgr dbgmem; #endif /* __dbgmem_h */
github188/catlib
src/heap.c
/* * heap.c -- Array-based heap implementation * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_HEAP_DO_DECL #define CAT_USE_INLINE 0 #define CAT_HEAP_DO_DECL 1 #include <cat/heap.h>
github188/catlib
utils/vernam.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <ctype.h> #include <cat/stduse.h> #define MAXLINE 256 void decode(char *c1, char *c2, int add, int off) { char out[MAXLINE], *op = out; int i, v1, v2, outc; while ( *c1 != '\0' && *c2 != '\0' ) { while ( *c1 != '\0' && !isalpha(*c1) ) c1++; while ( *c2 != '\0' && !isalpha(*c2) ) c2++; if ( *c1 == '\0' || *c2 == '\0' ) break; v1 = toupper(*c1) - 'A'; v2 = toupper(*c2) - 'A' + off; if (!add) { outc = v1 - v2; while ( outc < 0 ) outc += 26; outc += 'A'; } else { outc = (v1 + v2) % 26 + 'A'; } /* printf("%c (%2d), %c (%2d) -> %c (%2d)\n", toupper(*c1), v1, toupper(*c2), v2, outc, outc - 'A' + 1); */ *op++ = outc; c1++; c2++; } *op = '\0'; printf("Output: add = %d, off = %d\n%s\n\n", add, off, out); } int main(int argc, char *argv[]) { char line1[MAXLINE]; char line2[MAXLINE]; int off; if ( fgets(line1, sizeof(line1), stdin) == NULL ) err("no first line!\n"); if ( fgets(line2, sizeof(line2), stdin) == NULL ) err("no first line!\n"); for ( off = 0 ; off < 26 ; ++off ) decode(line1, line2, 1, off); for ( off = 0 ; off < 26 ; ++off ) decode(line1, line2, 0, off); return 0; }
github188/catlib
test/testcrypto.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <cat/crypto.h> #include <cat/time.h> #define NITER 100000 #define DLEN 256 uchar rand_data[DLEN]; byte_t sipkey[16]; void init_data() { const char seed[] = "Hi world!"; struct arc4ctx arc4; arc4_init(&arc4, seed, sizeof(seed)); arc4_gen(&arc4, rand_data, sizeof(rand_data)); arc4_gen(&arc4, sipkey, sizeof(sipkey)); } void test_arc4() { struct arc4ctx arc4; int i, j, match; ulong len; unsigned char test_vectors[3][3][32] = { {"Key", "Plaintext", <KEY>"}, {"Wiki", "pedia", "\x10\x21\xBF\x04\x20"}, {"Secret", "Attack at dawn", "\x45\xA0\x1F\x64\x5F\xC3\x5B\x38\x35\x52\x54\x4B\x9B\xF5"} }; unsigned char out[32]; match = 1; for ( i = 0; i < 3; ++i ) { arc4_init(&arc4, test_vectors[i][0], strlen(test_vectors[i][0])); len = strlen(test_vectors[i][1]); arc4_encrypt(&arc4, test_vectors[i][1], out, len); printf("RC4| Plaintext:'%s', Key:'%s', Ciphertext:'", test_vectors[i][0], test_vectors[i][1]); for ( j = 0; j < len; ++j ) { printf("%02x", out[j]); match = match && (out[j] == test_vectors[i][2][j]); } printf("' (%s)\n", match ? "match" : "no match"); } } void perf_arc4() { int i; cat_time_t start, diff; const char key[] = "hey there RC4!"; struct arc4ctx arc4; arc4_init(&arc4, key, sizeof(key)); start = tm_uget(); for ( i = 0; i < NITER; ++i ) arc4_encrypt(&arc4, rand_data, rand_data, sizeof(rand_data)); diff = tm_sub(tm_uget(), start); printf("%lf seconds to run %d ARC4 encryptions on %d-byte data\n", tm_2dbl(diff), NITER, DLEN); printf("%lf ns per byte\n", (tm_2dbl(diff) * 1e9 / (DLEN * NITER))); fflush(stdout); } void test_sha256() { struct sha256ctx s256; char str1[] = "abc"; char str2[] = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; byte_t out[32]; byte_t res1[32] = "\xBA\x78\x16\xBF\x8F\x01\xCF\xEA\x41\x41\x40\xDE" "\x5D\xAE\x22\x23\xB0\x03\x61\xA3\x96\x17\x7A\x9C" "\xB4\x10\xFF\x61\xF2\x00\x15\xAD"; byte_t res2[32] = "\x24\x8D\x6A\x61\xD2\x06\x38\xB8\xE5\xC0\x26\x93" "\x0C\x3E\x60\x39\xA3\x3C\xE4\x59\x64\xFF\x21\x67" "\xF6\xEC\xED\xD4\x19\xDB\x06\xC1"; int i; sha256(str1, sizeof(str1)-1, out); printf("sha256 hash of \"%s\" is:\n\t", str1); for ( i = 0 ; i < 32; ++i ) printf("%02x", out[i]); printf("\n"); printf("Expected value is:\n\t"); for ( i = 0 ; i < 32; ++i ) printf("%02x", res1[i]); printf("\n"); if (memcmp(out, res1, 32)) printf("FAILURE!\n"); else printf("SUCCESS\n"); printf("\n"); sha256(str2, sizeof(str2)-1, out); printf("sha256 hash of \"%s\" is: \n\t", str2); for ( i = 0 ; i < 32; ++i ) printf("%02x", out[i]); printf("\n"); printf("Expected value is:\n\t"); for ( i = 0 ; i < 32; ++i ) printf("%02x", res2[i]); printf("\n"); if (memcmp(out, res2, 32)) printf("FAILURE!\n"); else printf("SUCCESS\n"); } void perf_sha256() { int i; cat_time_t start, diff; start = tm_uget(); for ( i = 0; i < NITER; ++i ) sha256(rand_data, sizeof(rand_data), rand_data); diff = tm_sub(tm_uget(), start); printf("%lf seconds to run %d SHA256 hashes on %d-byte data\n", tm_2dbl(diff), NITER, DLEN); printf("%lf ns per byte\n", (tm_2dbl(diff) * 1e9 / (DLEN * NITER))); fflush(stdout); } /* * SipHash-2-4 output with * k = 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f * and * input = (empty string) * input = 00 (1 byte) * input = 00 01 (2 bytes) * input = 00 01 02 (3 bytes) * ... * input = 00 01 02 ... 3e (63 bytes) */ byte_t siphash24_test_vectors[64][8] = { { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, }, { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, }, { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, }, { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, }, { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, }, { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, }, { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, }, { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, }, { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, }, { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, }, { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, }, { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, }, { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, }, { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, }, { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, }, { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, }, { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, }, { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, }, { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, }, { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, }, { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, }, { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, }, { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, }, { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, }, { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, }, { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, }, { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, }, { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, }, { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, }, { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, }, { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, }, { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, }, { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, }, { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, }, { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, }, { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, }, { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, }, { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, }, { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, }, { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, }, { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, }, { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, }, { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, }, { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, }, { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, }, { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, }, { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, }, { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, }, { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, }, { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, }, { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, }, { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, }, { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, }, { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, }, { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, }, { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, }, { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, }, { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, }, { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, }, { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, }, { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } }; char *out2hex(byte_t out[8], char *s) { sprintf(s, "%02x%02x%02x%02x%02x%02x%02x%02x", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); return s; } void test_siphash24() { byte_t key[16] = { 0 }; byte_t input[64] = { 0 }; byte_t out[8]; char ostr[64], eostr[64]; int i; int fail = 0; printf("Testing siphash24 using 64 vectors\n"); for ( i = 0; i < sizeof(key); ++i ) { key[i] = i; } for ( i = 0; i < sizeof(input); ++i ) { input[i] = i; } for ( i = 0; i < 64; ++i ) { siphash24(key, input, i, out); if ( memcmp(out, siphash24_test_vectors[i], sizeof(out)) ) { printf("siphash for input %d produces output %s: expected %s\n", i, out2hex(out, ostr), out2hex(siphash24_test_vectors[i], eostr)); fail = 1; } } if ( !fail ) { printf("All siphash24 test passed\n"); } } void perf_siphash24() { int i; cat_time_t start, diff; start = tm_uget(); for ( i = 0; i < NITER; ++i ) siphash24(sipkey, rand_data, sizeof(rand_data), rand_data); diff = tm_sub(tm_uget(), start); printf("%lf seconds to run %d SipHash-2-4 hashes on %d-byte data\n", tm_2dbl(diff), NITER, DLEN); printf("%lf ns per byte\n", (tm_2dbl(diff) * 1e9 / (DLEN * NITER))); fflush(stdout); } int main(int argc, char *argv[]) { init_data(); test_arc4(); perf_arc4(); test_sha256(); perf_sha256(); test_siphash24(); perf_siphash24(); return 0; }
github188/catlib
test/testavl.c
<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cat/avl.h> #include <cat/stduse.h> #include <cat/emalloc.h> #include <sys/time.h> #define NUMSTR 4 #define NA 200 /* in case strdup() doesn't exist */ int vrfy(struct anode *an) { int l, r; if ( ! an ) return 0; l = vrfy(an->avl_left); r = vrfy(an->avl_right); if ( l < 0 || r < 0 ) return -1; if ( r-l != an->b ) { printf("Error! Node %s has balance of %d, but left = %d and right = %d\n", (char *)an->key, an->b, l, r); return -1; } return (l < r) ? r + 1 : l + 1; } void printan(struct anode *an, int d) { int i; struct canode *can = container(an, struct canode, node); if ( an->avl_right ) printan(an->avl_right, d+1); for ( i = 0 ; i < d ; ++i ) printf(" "); printf("[%s:%s->%d]\n", (char *)an->key, (char *)can->data, an->b); if ( an->avl_left ) printan(an->avl_left, d+1); } void printavl(struct cavltree *t) { if ( t->tree.avl_root == NULL ) printf("tree is empty\n"); else printan(t->tree.avl_root, 0); } void ourfree(void *data, void *ctx) { free(data); } #define NOPS 65536 #define NITER (NOPS * 128) void timeit() { struct anode nodes[NOPS], *finder; struct timeval start, end; int i, j, dir; struct avltree t; double dbl; for (i = 0; i < NOPS; i++) avl_ninit(&nodes[i], str_fmt_a("node%d", i)); avl_init(&t, cmp_str); gettimeofday(&start, NULL); for (j = 0; j < NITER / NOPS; j++) { for (i = 0; i < NOPS; i++) { finder = avl_lkup(&t, nodes[i].key, &dir); if (dir == CA_N) err("Found duplicate key for %s", nodes[i].key); avl_ins(&t, &nodes[i], finder, dir); } for (i = 0; i < NOPS; i++) avl_rem(&nodes[i]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem w/ %d entries max\n", dbl / (double)NITER, NOPS); gettimeofday(&start, NULL); for (i = 0; i < NITER; i++) { finder = avl_lkup(&t, nodes[0].key, &dir); if (dir == CA_N) err("Found duplicate key for %s", nodes[0].key); avl_ins(&t, &nodes[0], finder, dir); avl_rem(&nodes[0]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem (1 item deep max)\n", dbl / (double)NITER); for (i = 0; i < NOPS; i++) free(nodes[i].key); } int main() { int i, idx, tmp; int arr[NA]; char nstr[80], vstr[80]; void free(void *); char *strs[NUMSTR][2] = { {"key 1", "Hi there!" }, {"key2", "String 2!"}, {"Key 3!", "By now! this is over."}, {"key 1", "Overwrite."} }; struct cavltree *avl; char *s; avl = cavl_new(&cavl_std_attr_skey, 1); for (i = 0; i < NUMSTR; i++) { cavl_put(avl, strs[i][0], strs[i][1]); s = cavl_get(avl, strs[i][0]); printf("Put (%s) at key (%s): %p\n", s, strs[i][0], s); fflush(stdout); } if (cavl_get(avl, "bye")) printf("found something I shouldn't have!\n"); fflush(stdout); s = cavl_get(avl, strs[1][0]); printf("Under key %s is the string %s\n", strs[1][0], s); printf("address is %p\n\n", s); fflush(stdout); s = cavl_get(avl, strs[2][0]); printf("Under key %s is the string %s\n", strs[2][0], s); printf("address is %p\n\n", s); fflush(stdout); s = cavl_get(avl, strs[0][0]); printf("Under key %s is the string %s\n", strs[0][0], s); printf("address is %p\n\n", s); fflush(stdout); printavl(avl); fflush(stdout); s = cavl_get(avl, strs[1][0]); cavl_del(avl, strs[1][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); s = cavl_del(avl, strs[2][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); if (cavl_get(avl, strs[1][0])) printf("Error! Thing not deleted! : %s\n", (char*)cavl_get(avl, strs[1][0])); fflush(stdout); printavl(avl); printf("\n"); cavl_free(avl); /* get rid of "Overwrite!" */ avl = cavl_new(&cavl_std_attr_skey, 1); for ( i = 0 ; i < NA ; ++i ) arr[i] = i; for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); sprintf(nstr, "k%03d", arr[i]); sprintf(vstr, "v%03d", arr[i]); cavl_put(avl, nstr, estrdup(vstr)); } printf("\n\n"); printavl(avl); printf("\n\n"); fflush(stdout); for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); /* printf("%d\n", arr[i]); printavl(avl); printf("\n\n"); */ sprintf(nstr, "k%03d", arr[i]); s = cavl_del(avl, nstr); free(s); if ( vrfy(avl->tree.avl_root) < 0 ) { printavl(avl); exit(-1); } } printf("\n\n"); fflush(stdout); printavl(avl); fflush(stdout); cavl_apply(avl, ourfree, NULL); cavl_free(avl); printf("Freed\n"); timeit(); printf("Ok!\n"); return 0; }
github188/catlib
test/testrb.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cat/rbtree.h> #include <cat/stduse.h> #include <cat/emalloc.h> #include <sys/time.h> #define NUMSTR 4 #define NA 200 int vrfy(struct rbnode *n) { int l, r; if ( ! n ) return 0; l = vrfy(n->rb_left); r = vrfy(n->rb_right); if ( l < 0 || r < 0 ) return -1; if ( r != l ) { printf("Error! Node %s has black heights of %d (left) and %d (right)\n", (char *)n->key, l, r); return -1; } return (n->col == CRB_BLACK) ? l + 1 : l; } void printrb(struct rbnode *n, int d) { int i; struct crbnode *crn = container(n, struct crbnode, node); if ( n->rb_right ) printrb(n->rb_right, d+1); for ( i = 0 ; i < d ; ++i ) printf(" "); printf("[%s:%s->%s]\n", (char *)n->key, (char *)crn->data, n->col == CRB_BLACK ? "black" : "red"); if ( n->rb_left ) printrb(n->rb_left, d+1); } void printrbt(struct crbtree *t) { if ( t->tree.rb_root == NULL ) printf("tree is empty\n"); else printrb(t->tree.rb_root, 0); } void ourfree(void *data, void *ctx) { free(data); } #define NOPS 65536 #define NITER (NOPS * 128) void timeit() { struct rbnode nodes[NOPS], *finder; struct timeval start, end; int i, j, dir; struct rbtree t; double dbl; for (i = 0; i < NOPS; i++) rb_ninit(&nodes[i], str_fmt_a("node%d", i)); rb_init(&t, cmp_str); gettimeofday(&start, NULL); for (j = 0; j < NITER / NOPS; ++j) { for (i = 0; i < NOPS; i++) { finder = rb_lkup(&t, nodes[i].key, &dir); if (dir == CRB_N) err("Found duplicate key for %s", nodes[i].key); rb_ins(&t, &nodes[i], finder, dir); } for (i = 0; i < NOPS; i++) rb_rem(&nodes[i]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem w/ %d entries max\n", dbl / (double)NITER, NOPS); gettimeofday(&start, NULL); for (i = 0; i < NITER; i++) { finder = rb_lkup(&t, nodes[0].key, &dir); if (dir == CRB_N) err("Found duplicate key for %s", nodes[0].key); rb_ins(&t, &nodes[0], finder, dir); rb_rem(&nodes[0]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem (1 item deep max)\n", dbl / (double)NITER); for (i = 0; i < NOPS; i++) free(nodes[i].key); } int main() { int i, idx, tmp; int arr[NA]; char nstr[80], vstr[80]; void free(void *); char *strs[NUMSTR][2] = { {"key 1", "Hi there!" }, {"key2", "String 2!"}, {"Key 3!", "By now! this is over."}, {"key 1", "Overwrite."} }; struct crbtree *t; char *s; struct rbnode *np; t = crb_new(&crb_std_attr_skey, 1); for (i = 0; i < NUMSTR; i++) { crb_put(t, strs[i][0], strs[i][1]); s = crb_get(t, strs[i][0]); printf("Put (%s) at key (%s): %p\n", s, strs[i][0], s); fflush(stdout); } if (crb_get(t, "bye")) printf("found something I shouldn't have!\n"); fflush(stdout); s = crb_get(t, strs[1][0]); printf("Under key %s is the string %s\n", strs[1][0], s); printf("address is %p\n\n", s); fflush(stdout); s = crb_get(t, strs[2][0]); printf("Under key %s is the string %s\n", strs[2][0], s); printf("address is %p\n\n", s); fflush(stdout); s = crb_get(t, strs[0][0]); printf("Under key %s is the string %s\n", strs[0][0], s); printf("address is %p\n\n", s); fflush(stdout); printrbt(t); fflush(stdout); s = crb_del(t, strs[1][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); s = crb_del(t, strs[2][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); if (crb_get(t, strs[1][0])) printf("Error! Thing not deleted! : %s\n", (char *)crb_get(t, strs[1][0])); fflush(stdout); printrbt(t); printf("\n"); crb_free(t); /* get rid of "Overwrite!" */ t = crb_new(&crb_std_attr_skey, 1); for ( i = 0 ; i < NA ; ++i ) arr[i] = i; for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); /* printf("\n"); printrbt(t); printf("\n"); fflush(stdout); */ sprintf(nstr, "k%03d", arr[i]); sprintf(vstr, "v%03d", arr[i]); crb_put(t, nstr, estrdup(vstr)); if ( vrfy(t->tree.rb_root) < 0 ) { printrbt(t); exit(-1); } } printf("\n\n"); printrbt(t); printf("\n\n"); fflush(stdout); for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); /* printf("\n"); printrbt(t); printf("\n\n"); fflush(stdout); */ sprintf(nstr, "k%03d", arr[i]); s = crb_del(t, nstr); free(s); if ( vrfy(t->tree.rb_root) < 0 ) { printrbt(t); exit(-1); } } printf("\n\n"); fflush(stdout); printrbt(t); fflush(stdout); crb_apply(t, ourfree, NULL); crb_free(t); printf("Freed\n"); timeit(); printf("Ok!\n"); return 0; }
github188/catlib
test/testheap.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <cat/aux.h> #include <cat/heap.h> #include <cat/err.h> #include <cat/stduse.h> int my_cmp_int(const void *a, const void *b) { return ptr2int(a) - ptr2int(b); } int main(int argc, char *argv[]) { int num, i, hold, si, *arr, pos; struct heap *hp; if ( argc < 2 ) err("need a size of the array\n"); num = atoi(argv[1]); arr = emalloc(sizeof(int) * num); /* generate the array */ for ( i = 0 ; i < num ; ++i ) arr[i] = i+1; for ( i = 0 ; i < num - 1 ; ++i ) { si = rand(); if ( si < 0 ) si = -si; si = (si % (num-i-1))+i+1; hold = arr[si]; arr[si] = arr[i]; arr[i] = hold; } printf("initial array: "); for ( i = 0 ; i < num ; ++i ) printf("%d ", arr[i]); printf("\n"); /* generate the heap */ hp = hp_new(0, &my_cmp_int); for ( i = 0 ; i < num ; ++i ) { if (hp_add(hp, int2ptr(arr[i]), NULL) < 0) { fprintf(stderr, "out of memory\n"); exit(-1); } } printf("current heap: "); for ( i = 0 ; i < num ; ++i ) printf("%d ", (int)ptr2int(hp->elem[i])); printf("\n"); /* do some border test cases for find */ if ( (pos = hp_find(hp, int2ptr(1))) < 0 ) err("Couldn't find 1\n"); else printf("1 was at %u\n", pos); if ( (pos = hp_find(hp, int2ptr(num / 2))) < 0 ) err("Couldn't find %d\n", num / 2); else printf("%d was at %u\n", num / 2, pos); if ( (pos = hp_find(hp, int2ptr(num+1))) >= 0 ) err("Couldn't found %d at %u when I shouldn't have\n", num+1, pos); /* now print out all the numbers */ while ( (i = ptr2int(hp_rem(hp, 0))) ) printf("%d ", i); printf("\n"); /* free the heap */ hp_free(hp); return 0; }
github188/catlib
attic/ex.h
/* * cat/ex.h -- Exceptions via longjmp * * by <NAME> * * Copyright 2003, See accompanying license * */ #ifndef __CAT_EX_H #define __CAT_EX_H #include <cat/cat.h> #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <setjmp.h> #ifndef MAXEXSTK #define MAXEXSTK 64 #endif /* MAXEXSTK */ struct ex_ent { jmp_buf env; void * data; }; struct ex_stack { int top; void (*uncaught)(void *); struct ex_ent stack[MAXEXSTK]; }; int ex_try(void); void ex_throw(void *data); void * ex_get(void); void ex_end(void); void ex_setu(void (*uncaught)(void *)); #endif /* CAT_USE_STDLIB */ #endif /* __CAT_EX_H */
github188/catlib
src/list.c
<reponame>github188/catlib<gh_stars>1-10 /* * list.c -- circular doubly linked list implementation * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_LIST_DO_DECL #define CAT_USE_INLINE 0 #define CAT_LIST_DO_DECL 1 #include <cat/list.h>
github188/catlib
include/cc/stddef.h
/* * stddef.h -- C stddef.h header file * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __catstddef_h #define __catstddef_h /* * These are best guesses that you can substitute on your own machine if * need be. */ typedef ulong size_t; typedef long ptrdiff_t; typedef ushort wchar_t; #define offsetof(type, field) ((ulong)&((type *)0)->field) #define NULL ((void *)0) #endif /* __catstddef_h */
github188/catlib
test/pegs/peg-calc.c
#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> int stack[256]; int tos = 0; void push(int val) { if ( tos >= array_length(stack) ) err("Stack overflow\n"); stack[tos++] = val; } int pop(void) { if ( tos <= 0 ) err("Stack underflow\n"); return stack[--tos]; } 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 push_num(int n, struct raw *r, void *aux) { struct cpg_state *cs = aux; char buf[64]; if ( r->len >= sizeof(buf) ) err("number is too long"); memcpy(buf, r->data, r->len); buf[r->len] = '\0'; push(atoi(buf)); return 0; } int do_negate(int n, struct raw *r, void *aux) { push(-pop()); } int do_divide(int n, struct raw *r, void *aux) { int b = pop(); push(pop() / b); } int do_multiply(int n, struct raw *r, void *aux) { push(pop() * pop()); } int do_minus(int n, struct raw *r, void *aux) { int b = pop(); push(pop() - b); } int do_plus(int n, struct raw *r, void *aux) { push(pop() + pop()); } int output(int n, struct raw *r, void *aux) { printf("result = %d\n", pop()); fflush(stdout); } 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 < 2 ) err("usage: %s calc-file [expression-file]\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]); abort_unless(peg_action_set(&peg, "push_num", &push_num) == 1); abort_unless(peg_action_set(&peg, "do_negate", &do_negate) == 1); abort_unless(peg_action_set(&peg, "do_divide", &do_divide) == 1); abort_unless(peg_action_set(&peg, "do_multiply", &do_multiply) == 1); abort_unless(peg_action_set(&peg, "do_minus", &do_minus) == 1); abort_unless(peg_action_set(&peg, "do_plus", &do_plus) == 1); abort_unless(peg_action_set(&peg, "output", &output) == 1); cpg_init(&cs, &peg, lgetc); if ( argc < 3 ) { pfile = stdin; } else { 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
src/cat.c
/* * cat.c -- generic universal catlib functions * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cat.h> #include <stdio.h> #include <stdlib.h> void cat_abort(const char *fn, unsigned ln, const char *expr) { fprintf(stderr, "%s:%u -- check failed: %s\n", fn, ln, expr); abort(); exit(255); /* in case the signal is caught */ }
github188/catlib
include/cat/splay.h
/* * cat/splay.h -- Splay tree implementation * * by <NAME> * * Copyright 2006-2017 -- See accompanying license * */ #ifndef __cat_splay_h #define __cat_splay_h #include <cat/cat.h> #include <cat/aux.h> /* Structure for a splay tree node: to be embedded in other structures */ struct stnode { struct stnode * p[3]; char pdir; struct sptree * tree; void * key; }; #define CST_L 0 /* left node */ #define CST_R 2 /* right node */ #define CST_P 1 /* parent node */ #define CST_N 3 /* Used to denote an exact node when given a (p,dir) pair */ /* Splay tree and root node */ struct sptree { cmp_f cmp; struct stnode root; }; #define st_left p[CST_L] #define st_right p[CST_R] #define st_par p[CST_P] #define st_root root.p[CST_P] #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define PTRDECL static #define CAT_SP_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #define PTRDECL #endif /* CAT_USE_INLINE */ /* ----- Main Functions ----- */ /* Initialize a splay tree. 'cmp' is the function to compare nodes with. */ DECL void st_init(struct sptree *t, cmp_f cmp); /* Initialize a node of an AVL tree. 'k' is the node's key. */ DECL void st_ninit(struct stnode *n, void *k); /* * Find a node with key 'key' in 't'. Returns the node on success or NULL * on failure. */ DECL struct stnode * st_lkup(struct sptree *t, const void *key); /* Insert 'node' into 't'. */ DECL struct stnode * st_ins(struct sptree *t, struct stnode *node); /* Remove 'node' from its tree. */ DECL void st_rem(struct stnode *node); /* Apply 'func' to every node in 't' passing 'ctx' as state to 'func' */ DECL void st_apply(struct sptree *t, apply_f func, void * ctx); /* Return non-zero if 't' is empty or 0 otherwise */ DECL int st_isempty(struct sptree *t); /* Return the root node of the 't' or NULL if the tree is empty. */ DECL struct stnode * st_getroot(struct sptree *t); /* Return a pointer to the minimum node in 't' or NULL if the tree is empty */ DECL struct stnode * st_getmin(struct sptree *t); /* Return a pointer to the maximum node in 't' or NULL if the tree is empty */ DECL struct stnode * st_getmax(struct sptree *t); /* ----- Auxiliary (helper) functions (don't use) outside the module ----- */ DECL void st_findloc(struct sptree *t, const void *key, struct stnode **pn, int *pd); DECL void st_fix(struct stnode *par, struct stnode *cld, int dir); DECL void st_rl(struct stnode *n); DECL void st_rr(struct stnode *n); DECL void st_zll(struct stnode *n); DECL void st_zlr(struct stnode *n); DECL void st_zrl(struct stnode *n); DECL void st_zrr(struct stnode *n); DECL void st_splay(struct stnode *n); /* ----- Implementation ----- */ #if defined(CAT_SP_DO_DECL) && CAT_SP_DO_DECL DECL void st_init(struct sptree *t, cmp_f cmp) { abort_unless(t); abort_unless(cmp); t->cmp = cmp; st_ninit(&t->root, NULL); t->root.pdir = CST_P; } DECL void st_ninit(struct stnode *n, void *k) { abort_unless(n); n->p[CST_L] = n->p[CST_R] = n->p[CST_P] = NULL; n->pdir = CST_N; n->key = k; } DECL struct stnode * st_lkup(struct sptree *t, const void *key) { struct stnode *n; int dir; abort_unless(t); st_findloc(t, key, &n, &dir); if ( n == &t->root ) return NULL; st_splay(n); if ( dir == CST_N ) return n; else return NULL; } DECL struct stnode * st_ins(struct sptree *t, struct stnode *node) { struct stnode *n; int dir; abort_unless(t); node->tree = t; st_findloc(t, node->key, &n, &dir); if ( n == &t->root ) { st_fix(&t->root, node, CST_P); n = NULL; } else if ( dir == CST_N ) { /* approach: splay the original to the top of the tree and */ /* then replace it with the new one */ st_splay(n); st_fix(node, n->st_left, CST_L); st_fix(node, n->st_right, CST_R); st_fix(n->st_par, node, n->pdir); n->st_left = n->st_right = n->st_par = NULL; n->pdir = CST_N; } else { st_fix(n, node, dir); st_splay(node); n = NULL; } return n; } DECL void st_rem(struct stnode *node) { struct stnode *root, *rep; struct sptree *t; abort_unless(node); if ( !node || !node->tree ) return; t = node->tree; root = &t->root; st_splay(node); if ( ! node->st_left && ! node->st_right ) { st_fix(root, NULL, CST_P); } else if ( ! node->st_right ) { st_fix(root, node->st_left, CST_P); } else if ( ! node->st_left ) { st_fix(root, node->st_right, CST_P); } else { rep = node->st_left; while ( rep->st_right ) rep = rep->st_right; st_fix(root, node->st_left, CST_P); st_splay(rep); abort_unless(rep->st_right == NULL); st_fix(rep, node->st_right, CST_R); } node->st_left = node->st_right = node->st_par = NULL; node->pdir = CST_N; } DECL void st_apply(struct sptree *t, apply_f func, void * ctx) { struct stnode *trav; int dir = CST_P; abort_unless(t); abort_unless(func); trav = t->root.p[CST_P]; if ( ! trav ) return; do { switch (dir) { case CST_P: if ( trav->st_left ) trav = trav->st_left; else if ( trav->st_right ) trav = trav->st_right; else { (*func)(trav, ctx); dir = trav->pdir; trav = trav->st_par; } break; case CST_L: if ( trav->st_right ) { dir = CST_P; trav = trav->st_right; } else { (*func)(trav, ctx); dir = trav->pdir; trav = trav->st_par; } break; case CST_R: (*func)(trav, ctx); dir = trav->pdir; trav = trav->st_par; break; } } while ( trav != &t->root ); } DECL int st_isempty(struct sptree *t) { abort_unless(t); return t->st_root == NULL; } DECL struct stnode * st_getroot(struct sptree *t) { abort_unless(t); return t->st_root; } DECL struct stnode * st_getmin(struct sptree *t) { struct stnode *trav; abort_unless(t); trav = t->st_root; if ( trav != NULL ) { while ( trav->p[CST_L] != NULL ) trav = trav->p[CST_L]; } return trav; } DECL struct stnode * st_getmax(struct sptree *t) { struct stnode *trav; abort_unless(t); trav = t->st_root; if ( trav != NULL ) { while ( trav->p[CST_R] != NULL ) trav = trav->p[CST_R]; } return trav; } DECL void st_findloc(struct sptree *t, const void *key, struct stnode **pn, int *pd) { struct stnode *tmp, *par; int dir = CST_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 = CST_L; else if ( dir > 0 ) dir = CST_R; else { *pn = tmp; *pd = CST_N; return; } } *pn = par; *pd = dir; } DECL void st_fix(struct stnode *par, struct stnode *cld, int dir) { abort_unless(par); abort_unless(dir >= CST_L && dir <= CST_R); par->p[dir] = cld; if ( cld ) { cld->pdir = dir; cld->p[CST_P] = par; } } DECL void st_rl(struct stnode *n) { struct stnode *c; abort_unless(n); c = n->st_right; abort_unless(c); st_fix(n, c->st_left, CST_R); st_fix(n->st_par, c, n->pdir); st_fix(c, n, CST_L); } DECL void st_rr(struct stnode *n) { struct stnode *c; abort_unless(n); c = n->st_left; abort_unless(c); st_fix(n, c->st_right, CST_L); st_fix(n->st_par, c, n->pdir); st_fix(c, n, CST_R); } DECL void st_zll(struct stnode *n) { struct stnode *p, *gp; p = n->st_par; abort_unless(p); gp = p->st_par; abort_unless(gp); st_fix(gp, p->st_left, CST_R); st_fix(p, n->st_left, CST_R); st_fix(gp->st_par, n, gp->pdir); st_fix(n, p, CST_L); st_fix(p, gp, CST_L); } DECL void st_zlr(struct stnode *n) { struct stnode *p, *gp; p = n->st_par; abort_unless(p); gp = p->st_par; abort_unless(gp); st_fix(gp, n->st_right, CST_L); st_fix(p, n->st_left, CST_R); st_fix(gp->st_par, n, gp->pdir); st_fix(n, p, CST_L); st_fix(n, gp, CST_R); } DECL void st_zrl(struct stnode *n) { struct stnode *p, *gp; p = n->st_par; abort_unless(p); gp = p->st_par; abort_unless(gp); st_fix(gp, n->st_left, CST_R); st_fix(p, n->st_right, CST_L); st_fix(gp->st_par, n, gp->pdir); st_fix(n, p, CST_R); st_fix(n, gp, CST_L); } DECL void st_zrr(struct stnode *n) { struct stnode *p, *gp; p = n->st_par; abort_unless(p); gp = p->st_par; abort_unless(gp); st_fix(gp, p->st_right, CST_L); st_fix(p, n->st_right, CST_L); st_fix(gp->st_par, n, gp->pdir); st_fix(n, p, CST_R); st_fix(p, gp, CST_R); } DECL void st_splay(struct stnode *n) { struct stnode *p; abort_unless(n); while ( n->pdir != CST_P ) { p = n->st_par; abort_unless(p); if ( p->pdir == CST_P ) { if ( n->pdir == CST_L ) st_rr(p); else st_rl(p); } else if ( p->pdir == CST_L ) { if ( n->pdir == CST_L ) st_zrr(n); else st_zlr(n); } else { abort_unless(p->pdir == CST_R); if ( n->pdir == CST_L ) st_zrl(n); else st_zll(n); } } } #endif /* defined(CAT_SP_DO_DECL) && CAT_SP_DO_DECL */ #undef PTRDECL #undef DECL #undef CAT_SP_DO_DECL #endif /* __cat_splay_h */
github188/catlib
include/cat/optparse.h
/* * cat/optparse.h -- Command-line option parsing * * by <NAME> * * Copyright 2009-2012 -- See accompanying license * */ #ifndef __cat_optparse_h #define __cat_optparse_h #include <cat/cat.h> #define CLOPT_NOARG 0 #define CLOPT_STRING 1 #define CLOPT_INT 2 #define CLOPT_UINT 3 #define CLOPT_DOUBLE 4 #define CLORET_OPTION 0 #define CLORET_UNKOPT -1 #define CLORET_NOPARAM -2 #define CLORET_BADPARAM -3 #define CLORET_RESET -4 struct clopt { int type; char ch; const char * str; const char * argnam; const char * desc; attrib_t val; }; #define CLOPT_INIT(type, ch, str, desc) { type, ch, str, NULL, desc, {0} } #define CLOPT_I_NOARG(ch, str, desc) \ { CLOPT_NOARG, (ch), (str), NULL, (desc), {0} } #define CLOPT_I_STRING(ch, str, name, desc) \ { CLOPT_STRING, (ch), (str), (name), (desc), {0} } #define CLOPT_I_INT(ch, str, name, desc) \ { CLOPT_INT, (ch), (str), (name), (desc), {0} } #define CLOPT_I_UINT(ch, str, name, desc) \ { CLOPT_UINT, (ch), (str), (name), (desc), {0} } #define CLOPT_I_DOUBLE(ch, str, name, desc) \ { CLOPT_DOUBLE, (ch), (str), (name), (desc), {0} } struct clopt_parser { struct clopt * options; size_t num; int argc; char ** argv; int vidx; int non_opt; const char * chptr; char errbuf[128]; }; #define CLOPTPARSER_INIT(_optarr, _arrlen) \ { (_optarr), (_arrlen), 0, NULL, 0, 0, NULL, { 0 } } #define CLOPTPARSER_INIT_ARR(_optarr) \ CLOPTPARSER_INIT((_optarr), array_length(_optarr)) /* returns 0 if the parser, argc, and argv are well formatted */ int optparse_reset(struct clopt_parser *clp, int argc, char *argv[]); /* returns 0 on an option, < 0 on err, (CLORET_*), > 0 on index after options */ int optparse_next(struct clopt_parser *clp, struct clopt **p); /* prints up to slen -1 characters: always null terminates */ void optparse_print(struct clopt_parser *clp, char *str, size_t slen); /* format the option name into a string */ char *clopt_name(struct clopt *opt, char *buf, size_t buflen); #endif /* __cat_optparse_h */
github188/catlib
include/cat/raw.h
/* * cat/raw.h -- raw blob manipulation functions * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #ifndef __CAT_RAW_H #define __CAT_RAW_H #include <cat/cat.h> int raw_cmp(void *r1, void *r2); struct raw * str_to_raw(struct raw *r, char *s, int terminate); #endif /* __CAT_RAW_H */
github188/catlib
attic/regex.c
<gh_stars>1-10 /* * regex.c -- simplified UNIX regular expressions * * by <NAME> * * Copyright 2003, See accompanying license * */ #include <cat/cat.h> #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <cat/raw.h> #include <cat/regex.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int re_find(const char *s, const char *p, regmatch_t *m, int nm) { regex_t regex; int rv; Assert(s); Assert(p); Assert(nm >= 0); if ( nm ) { int i; Assert(m); for ( i = 0 ; i < nm ; ++i ) Assert((m[i].rm_so < 0) || (m[i].rm_eo >= m[i].rm_so)); } if ( regcomp(&regex, p, REG_EXTENDED) ) return -1; if ( m ) rv = regexec(&regex, s, nm, m, 0); else rv = regexec(&regex, s, 0, NULL, REG_NOSUB); regfree(&regex); if ( !rv ) return 1; else if ( rv == REG_NOMATCH ) return 0; else return -1; } int re_lastrep(const char *r) { int val, n = 0; char *p; Assert(r); /* find out the maximum replacement value */ for ( ; *r ; ++r ) if ( ( *r == '\\' ) && (*(r+1) >= '0') && (*(r+1) <= '9')) { ++r; val = (int) strtoul(r, &p, 10); if ( val < 0 ) return -1; r = p; n = (n < val) ? val : n; } return n; } int re_replen(const char *s, const char *r, regmatch_t *m) { unsigned int newlen, val; char *p; Assert(s); Assert(r); Assert(m); /* now find out how long the replacement string will be */ /* matches[0] should contain offsets for the entire pattern */ newlen = strlen(s) + 1 - (m[0].rm_eo - m[0].rm_so) + strlen(r); /* now find each replacement string */ for ( ; *r ; ++r ) if ( ( *r == '\\' ) && (*(r+1) >= '0') && (*(r+1) <= '9') ) { ++r; val = (int)strtoul(r, &p, 10); /* subtract out the \ and all the digits */ newlen -= 1 + (p - r); /* advance r */ r = p; /* add in the length of the replacement (cast do int because of */ /* stupidity! Bad OpenBSD implementation. No cookie!) */ if ( (int)(m[val].rm_so) >= 0 ) newlen += m[val].rm_eo - m[val].rm_so; } return newlen; } /* you'd better use re_replen to make sure t is long enough! */ int re_replace(const char *s, const char *r, const regmatch_t *m, char *d) { int val, off; char *p; Assert(s); Assert(r); Assert(m); Assert(d); /* copy in to the beginning of the match */ memmove(d, s, m[0].rm_so); d += m[0].rm_so; while ( *r ) if ( ( *r == '\\' ) && (*(r+1) >= '0') && (*(r+1) <= '9') ) { ++r; val = (int)strtoul(r, &p, 10); r = p; /* If there was no sub match just go on */ if ( m[val].rm_so < 0 ) continue; off = m[val].rm_eo - m[val].rm_so; memmove(d, s + m[val].rm_so, off); d += off; } else { *d = *r; ++d; ++r; } /* copy last bit of info and null terminate */ off = strlen(s) - m[0].rm_eo; memmove(d, s + m[0].rm_eo, off); d += off; *d = '\0'; return 0; } #include <cat/err.h> static void *Malloc(size_t s) { void *m; if ( !(m = malloc(s)) ) errsys("re_sr: "); return m; } char * re_sr(const char *s, const char *p, const char *r) { regmatch_t match[CAT_RE_MAXSUB+1]; int nm, rv; char *newstr; Assert(s); Assert(p); Assert(r); nm = re_lastrep(r); if ( ( nm < 0 ) || ( nm > CAT_RE_MAXSUB ) ) return NULL; rv = re_find(s, p, match, nm+1); if ( rv < 0 ) return NULL; if ( rv == 0 ) return strcpy(Malloc(strlen(s)+1), s); else { newstr = Malloc(re_replen(s, r, match)); re_replace(s, r, match, newstr); return newstr; } } #endif /* CAT_USE_STDLIB */
github188/catlib
attic/time.c
/* * time.c -- timing functions * * by <NAME> * * Copyright 2003, See accompanying license * */ #include <cat/time.h> #include <time.h> static void tm_fixup(struct cat_time *t) { Assert(t); if ( t->sec > 0 ) { if ( t->nsec < 0 ) { t->nsec += 1000000000L; t->sec--; } } else if ( t->sec < 0 ) { if ( t->nsec > 0 ) { t->nsec -= 1000000000L; t->sec++; } } } struct cat_time *tm_add(struct cat_time *t1, struct cat_time *t2) { Assert(t1); Assert(t2); t1->sec += t2->sec; t1->nsec += t2->nsec; tm_fixup(t1); return t1; } struct cat_time *tm_sub(struct cat_time *t1, struct cat_time *t2) { Assert(t1); Assert(t2); t1->sec -= t2->sec; t1->nsec -= t2->nsec; tm_fixup(t1); return t1; } struct cat_time *tm_clr(struct cat_time *t) { Assert(t); t->sec = -1; t->nsec = -1; return t; } int tm_isset(struct cat_time *t) { Assert(t); return t->sec >= 0 && t->nsec >= 0; } int tm_cmp(void *t1p, void *t2p) { struct cat_time *t1 = t1p, *t2 = t2p; long rv; Assert(t1); Assert(t2); if ( !(rv = t1->sec - t2->sec) ) rv = t1->nsec - t2->nsec; if ( rv < 0 ) return -1; else if ( rv ) return 1; else return 0; } double tm_2dbl(struct cat_time *t) { Assert(t); return t->sec + (double)t->nsec / (double)1000000000; } struct cat_time *tm_setd(struct cat_time *t, double d) { Assert(t); t->sec = (long)d; t->nsec = (long)((d - t->sec) * 1000000000L); return t; } struct cat_time *tm_setl(struct cat_time *t, long sec, long nsec) { Assert(t); Assert(sec >= 0); Assert(nsec >= 0 && nsec < 1000000000l); t->sec = sec; t->nsec = nsec; return t; } struct cat_time *tm_mark(struct cat_time *old, struct cat_time *new) { struct cat_time hold; Assert(new); Assert(old); hold = *new; tm_sub(new, old); *old = hold; return new; } struct cat_time *tm_cget(struct cat_time *t) { clock_t cur; Assert(t); cur = clock(); t->sec = cur / CLOCKS_PER_SEC; t->nsec = (long)((double)(cur - t->sec)/(double)CLOCKS_PER_SEC * 1000000000L); return t; } #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <sys/time.h> struct cat_time *tm_uget(struct cat_time *t) { struct timeval cur; Assert(t); gettimeofday(&cur, NULL); t->sec = cur.tv_sec; t->nsec = cur.tv_usec * 1000; return t; } #endif /* CAT_USE_STDLIB */
github188/catlib
attic/dlist.c
/* * dlist.c -- delta list implementation * * by <NAME> * * Copyright 2003, See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_DLIST_DO_DECL #define CAT_USE_INLINE 0 #define CAT_DLIST_DO_DECL 1 #include <cat/dlist.h>
github188/catlib
src/csv.c
<filename>src/csv.c<gh_stars>1-10 /* * csv.c -- functions to manipulated comma-separated value files. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cat.h> #include <cat/csv.h> #include <cat/grow.h> #include <string.h> void csv_init(struct csv_state *csv, getchar_f gc, void *gcctx) { abort_unless(csv && gc); memset(csv, 0, sizeof(*csv)); csv->csv_getc = gc; csv->csv_gcctx = gcctx; csv->csv_last = -1; } int csv_next(struct csv_state *csv, char *p, size_t len, size_t *rlen) { size_t i = 0; getchar_f getc = csv->csv_getc; void *gcctx = csv->csv_gcctx; int c, code = CSV_OK, prquote; if ( !csv || !p || len-- < 2 ) return CSV_ERR; if ( csv->csv_done > 0 ) return CSV_EOF; else if ( csv->csv_done < 0 ) return CSV_ERR; do { if ( csv->csv_last < 0 ) { c = (*getc)(gcctx); } else { c = csv->csv_last; csv->csv_last = -1; } if ( c < 0 ) { if ( c == CSV_GETC_EOF ) { csv->csv_done = 1; code = CSV_REC; } else { abort_unless(c == CSV_GETC_ERR); csv->csv_done = -1; code = CSV_ERR; } break; } else if ( c == '"' ) { csv->csv_inquote = !csv->csv_inquote; prquote = !csv->csv_inquote && csv->csv_sawquote; csv->csv_sawquote = 1; if ( !prquote ) continue; } else { csv->csv_sawquote = 0; } if ( c == ',' && !csv->csv_inquote ) { code = CSV_FLD; } else if ( c == '\n' && !csv->csv_inquote ) { code = CSV_REC; } else { if ( i == len ) { csv->csv_last = c; if ( c == '"' ) csv->csv_inquote = !csv->csv_inquote; code = CSV_CNT; } else { *p++ = c; ++i; } } } while ( code == CSV_OK ); if ( i == 0 && csv->csv_done > 0 ) code = CSV_EOF; if ( code != CSV_EOF ) { *p = '\0'; if ( code != CSV_CNT ) { csv->csv_inquote = 0; csv->csv_sawquote = 0; } if ( rlen ) *rlen = i; } return code; } int csv_clear_field(struct csv_state *csv) { char buf[256]; int code; while ( (code = csv_next(csv, buf, sizeof(buf), 0)) == CSV_CNT ) ; return code; }
github188/catlib
include/cat/err.h
/* * cat/err.h -- error reporting and debugging * * <NAME> * * Copyright 1999-2012 -- See accompanying license * */ #ifndef __CAT_ERR_H #define __CAT_ERR_H #include <cat/cat.h> #include <cat/emit.h> #include <stdio.h> typedef void (*log_close_f)(struct emitter *); void err(char *fmt, ...); void errsys(char *fmt, ...); void logrec(int level, char *fmt, ...); void logsys(int level, char *fmt, ...); void set_logger(struct emitter *em, log_close_f log_close_func); void setlogthresh(int thresh); #define ERRCK(x) \ do { \ if ( (x) < 0 ) \ err("Error at %s:%d:\n\t%s\n", __FILE__, __LINE__, #x); \ } while (0); #if CAT_DEBUG_LEVEL >= 1 #define CDBG \ logrec(1, "DEBUG %s:%d\n", __FILE__, __LINE__); #define CDBG1(f,v1) \ logrec(1, "DEBUG %s:%d: " f "\n", __FILE__, __LINE__, v1); #define CDBG2(f,v1,v2) \ logrec(1, , "DEBUG %s:%d: " f "\n", __FILE__, __LINE__, v1, v2); #define CDBG3(f,v1,v2,v3) \ logrec(1, "DEBUG %s:%d: " f "\n", __FILE__, __LINE__, v1, v2, v3); #define CDBG4(f,v1,v2,v3,v4) \ logrec(1, "DEBUG %s:%d: " f "\n", __FILE__, __LINE__, v1, v2, v3, v4); #define CDBG5(f,v1,v2,v3,v4,v5) \ logrec(1, "DEBUG %s:%d: " f "\n", __FILE__, __LINE__, \ v1, v2, v3, v4, v5); #define CDBGE(f,e) \ logrec(1, "DEBUG %s:%d: %s = " f " \n", __FILE__, __LINE__, #e , (e)); #else #define CDBG #define CDBG1(f,v1) #define CDBG2(f,v1,v2) #define CDBG3(f,v1,v2,v3) #define CDBG4(f,v1,v2,v3,v4) #define CDBG5(f,v1,v2,v3,v4,v5) #define CDBGE(f,e) #endif #endif /* __CAT_ERR_H */
github188/catlib
include/cat/emalloc.h
<reponame>github188/catlib /* * emalloc.h -- error aborting memory management operations. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_emalloc_h #define __cat_emalloc_h #include <cat/cat.h> typedef void (*emalloc_abort_f)(char *s, void *omem, size_t size, size_t nmem, int syserr); void * emalloc(size_t size); void * ecalloc(size_t nmemb, size_t size); void * erealloc(void *old, size_t size); char * estrdup(const char *s); /* The abort function must NOT return! (longjmp is ok) */ void emalloc_set_abort(emalloc_abort_f newfunc); #endif /* __cat_emalloc_h */
github188/catlib
test/testpool.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <cat/aux.h> #include <cat/mem.h> #include <cat/pool.h> #include <cat/stduse.h> #define NCONS 100000 struct pool Pool; int main(int argc, char *argv[]) { int i, j, na, psiz; void **allocs; struct timeval tv, tv2; double usec; if ( argc < 4 ) err("usage: %s <alloc size> <pool size> <number of allocs>\n", argv[0]); psiz = atoi(argv[2]); na = atoi(argv[3]); pl_init(&Pool, atoi(argv[1]), -1, emalloc(psiz), psiz); if ( na > Pool.max ) err("Allocating more items than pool size (%d > %d)\n", na, Pool.max); allocs = emalloc(sizeof(void *) * na); printf("number of rounds: %d\n", NCONS); printf("number of allocations/deallocations per round: %d\n", na); fflush(stdout); gettimeofday(&tv, 0); for ( i = 0 ; i < NCONS; ++i ) { for ( j = 0 ; j < na ; ++j ) allocs[j] = pl_alloc(&Pool); for ( j = 0 ; j < na ; ++j ) pl_free(&Pool, allocs[j]); } gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NCONS * na; printf("Roughly %f nanoseconds for the two operations\n", usec * 1000); fflush(stdout); return 0; }
github188/catlib
test/testregex.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <cat/raw.h> #include <cat/stduse.h> #include <cat/match.h> #include <cat/mem.h> struct rex_match_loc locs[16]; void tmatch(char *pat, char *str) { struct rex_pat rp; struct raw r; int rv, e, i; if ( rex_init(&rp, str_to_raw(&r, pat, 0), &estdmm, &e) < 0 ) { printf("Error parsing pattern '%s' at position %d\n", pat, e+1); return; } memset(locs, 0, sizeof(locs)); rv = rex_match(&rp, str_to_raw(&r, str, 0), locs, 16); if ( rv == REX_MATCH ) { printf("MATCH: /%s/ (@ %u:%u) -- \"%s\"\n", pat, (uint)locs[0].start, (uint)locs[0].len, str); for ( i = 1; i < 16; i++ ) if ( locs[i].valid ) printf("Sub-group %d match: @%u:%u\n", i, (uint)locs[i].start, (uint)locs[i].len); } else if ( rv == REX_NOMATCH ) { printf("NO MATCH: /%s/ -- \"%s\"\n", pat, str); } else if ( rv == REX_ERROR ) { printf("ERROR: /%s/ -- \"%s\"\n", pat, str); } else { printf("Unknown return code! (%d)\n", rv); } rex_free(&rp); } void tfail(char *pat) { struct rex_pat rp; struct raw r; int e; if ( rex_init(&rp, str_to_raw(&r, pat, 0), &estdmm, &e) < 0 ) printf("Pattern /%s/ correctly failed at position %d.\n", pat, e+1); else printf("ERROR: /%s/ -- should have failed to compile.\n", pat); } int main(int argc, char *argv[]) { tmatch("a", "bad"); tmatch("a", "good"); tmatch("z?", "bad"); tmatch("a?", "bad"); tmatch("a+", "bad"); tmatch("a+", "baaaad"); tmatch("a+", "bonk"); tmatch("a*", "bonk"); tmatch(".", "bonk"); tmatch(".*", "bonk"); tmatch(".+", "bonk"); tmatch("[abc]", "c"); tmatch("[abc]", "9"); tmatch("[a-z]", "b"); tmatch("[a-z]", "9"); tmatch("[a-zA-Z]", "K"); tmatch("[a-zA-Z]", ","); tmatch("[^a-zA-Z]", ","); tmatch("[^a-zA-Z]", "q"); tmatch("9[a-z]?", "9q"); tmatch("9[a-z]?", "99"); tmatch("[]]", "a]b"); tmatch("[^]]", "]b"); tmatch("[a-z]*", " hello "); tmatch("[a-z]+", " hello "); tmatch("(ab)", " caby"); tmatch("(a(b)*)", " cabbby"); tmatch("(a(b)?)", " cabbby"); tmatch("(a(b)?)", " cacbbby"); tmatch("(a(b)+)", " cay"); tmatch("(a(b)+)", " caby"); tmatch("(a(b)+)", " cabbby"); tmatch("a|b", "a"); tmatch("a|b", "b"); tmatch("a|b", "cad"); tmatch("a|b", "cbd"); tmatch("(a|b)", "cbd"); tmatch("(a|b)+", "cbabbd"); tmatch("(a|bb)+", "cbabbbd"); tmatch("^abc", "abcd"); tmatch("^abc", "aaabcd"); tmatch("abc$", "abcd"); tmatch("bcd$", "aaabcd"); tmatch("^", ""); tmatch("$", ""); tmatch("^$", ""); tmatch("a?", ""); tmatch("a*", ""); tmatch("a+", ""); tmatch("a{0,3}", ""); tmatch("a{1,3}", ""); tmatch("a{1,3}", "aa"); tmatch("a{1,3}", "baaaa"); tmatch("a{2,2}", "baaaa"); tmatch("a{5}", "aaaa"); tmatch("a{5}", "baaaa"); tmatch("a{5}", "aaaaa"); tmatch("a{5}", "bababaaaaabbbb"); tmatch("a{5}", "bababaaaabbbb"); tmatch("(abc){1,2}", "bababcabb"); tmatch("(abc){1,2}", "bababcabc"); tmatch("(abc){2}", "bababcabc"); tmatch("(abc){2}", "bababcabb"); tmatch("(abc|cba){2}", "bababccbaxx"); tmatch("(abc|cba){2}", "bababcccaxx"); tmatch("[a-zA-Z_0-9]{1,10}", "bababcccaxx"); tmatch("[^a-zA-Z_0-9]{1,10}", "bababcccaxx"); tmatch("[a-zA-Z_0-9]{1,10}", "bab9abcccaxx"); tmatch("[^a-zA-Z_0-9]{1,10}", "bab9abcccaxx"); tmatch("[a-zA-Z_0-9]{1,}", "999"); tmatch("[a-zA-Z_0-9]{1,}", "bababcccaxx"); tmatch("[a-zA-Z_0-9]{,5}", "999"); tmatch("[a-zA-Z_0-9]{,5}", "999a"); tfail("(abc"); tfail("abc)"); tfail("(abc)(*"); tfail("(a(bc)"); tfail("(a(b*c)"); tfail("(a(bc)))"); tfail("(a(bc*)))"); tfail("[abc"); tfail("abc]"); tfail("*"); tfail("*abc"); tfail("?abc"); tfail("+abc"); tfail("abc??"); tfail("abc**"); tfail("abc++"); tfail("[a-zA-Z_0-9]{1,0}"); tfail("[a-zA-Z_0-9]{5,2}"); tfail("a{1000}"); tfail("a{1000,1000}"); tfail("a{,1000}"); return 0; }
github188/catlib
src/lex.c
<gh_stars>1-10 /* * lex.c -- Dumb lexical analysis. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/lex.h> #include <cat/raw.h> #include <string.h> #include <stdlib.h> #define node_to_lexent(node) container((node), struct lexer_entry, entry) struct lexer *lex_new(struct memmgr *mm) { struct lexer *lex = mem_get(mm, sizeof(*lex)); if ( lex == NULL ) return NULL; l_init(&lex->entries); lex->input.data = NULL; lex->input.len = 0; lex->next_char = NULL; lex->mm = mm; return lex; } int lex_add_entry(struct lexer *lex, const char *pattern, int token) { struct lexer_entry *ent; struct raw r; int rv; if ( token < 0 ) return -1; if ( (ent = mem_get(lex->mm, sizeof(*ent))) == NULL ) return -1; l_init(&ent->entry); ent->token = token; r.len = strlen(pattern) + 1; if ( (r.data = mem_get(lex->mm, r.len + 1)) == NULL ) { mem_free(lex->mm, ent); return -1; } *(char *)r.data = '^'; memcpy((char *)r.data + 1, pattern, r.len); rv = rex_init(&ent->pattern, &r, lex->mm, NULL); mem_free(lex->mm, r.data); if ( rv < 0 ) { mem_free(lex->mm, ent); return -1; } l_enq(&lex->entries, &ent->entry); return 0; } void lex_reset(struct lexer *lex, const char *string) { abort_unless(string); str_to_raw(&lex->input, (char *)string, 0); lex->next_char = lex->input.data; } int lex_next_token(struct lexer *lex, const char **string, int *len) { int rv; struct list *node; struct lexer_entry *ent; struct raw r; struct rex_match_loc match; if ( lex->next_char == (char *)lex->input.data + lex->input.len ) return LEX_END; r.data = (byte_t*)lex->next_char; r.len = lex->input.len - (lex->next_char - (char *)r.data); l_for_each(node, &lex->entries) { ent = node_to_lexent(node); rv = rex_match(&ent->pattern, &r, &match, 1); if ( rv == REX_ERROR ) return LEX_ERROR; if ( rv != REX_MATCH ) continue; abort_unless(match.valid); abort_unless(match.start == 0); if ( string != NULL ) *string = lex->next_char; if ( len != NULL ) *len = match.len; lex->next_char += match.len; return ent->token; } return LEX_NOMATCH; } void lex_destroy(struct lexer *lex) { struct list *node; struct memmgr *mm = lex->mm; while ( (node = l_deq(&lex->entries)) != NULL ) { struct lexer_entry *ent = node_to_lexent(node); rex_free(&ent->pattern); mem_free(mm, ent); } mem_free(mm, lex); }
github188/catlib
src/err.c
/* * err.c -- Error handling and debugging * * <NAME> * * Copyright 2005-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/err.h> #include <cat/emit.h> #include <cat/stdclio.h> #include <cat/str.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #if CAT_HAS_POSIX #include <syslog.h> #include <signal.h> #include <errno.h> #else /* CAT_HAS_POSIX */ #define LOG_ERR 3 #define LOG_INFO 6 #endif /* CAT_HAS_POSIX */ static int def_log_emit_func(struct emitter *em, const void *buf, size_t len); static void def_log_close_func(struct emitter *em); static void eout(int, int, char *, va_list); static struct file_emitter def_log_emitter = { { EMIT_OK, def_log_emit_func }, NULL, }; static log_close_f log_close_func = def_log_close_func; static struct emitter *log_emitter = (struct emitter *)&def_log_emitter; static int log_threshold = 0; /* The mode for debugging */ static int def_log_emit_func(struct emitter *em, const void *buf, size_t len) { static int initialized = 0; if ( !initialized ) { def_log_emitter.fe_file = stderr; initialized = 1; } return file_emit_func(em, buf, len); } static void def_log_close_func(struct emitter *em) { struct file_emitter *fe = (struct file_emitter *)em; fclose(fe->fe_file); } /* This is for fatal errors. Assume we quit */ void err(char *fmt, ...) { va_list ap; va_start(ap, fmt); eout(LOG_ERR, 0, fmt, ap); va_end(ap); #if defined(CAT_DIE_DUMP) && CAT_DIE_DUMP abort(); #else /* CAT_DIE_DUMP */ exit(1); #endif /* CAT_DIE_DUMP */ } void errsys(char *fmt, ...) { va_list ap; va_start(ap, fmt); eout(LOG_ERR, 1, fmt, ap); va_end(ap); #if defined(CAT_DIE_DUMP) && CAT_DIE_DUMP abort(); #else /* CAT_DIE_DUMP */ exit(1); #endif /* CAT_DIE_DUMP */ } void logrec(int level, char *fmt, ...) { va_list ap; va_start(ap, fmt); if ( level >= log_threshold ) eout(LOG_INFO, 0, fmt, ap); va_end(ap); } void logsys(int level, char *fmt, ...) { va_list ap; va_start(ap, fmt); if ( level >= log_threshold ) eout(LOG_INFO, 1, fmt, ap); va_end(ap); } void set_logger(struct emitter *em, log_close_f new_close_func) { abort_unless(em); if ( log_close_func != NULL ) (*log_close_func)(log_emitter); log_emitter = em; log_close_func = new_close_func; } void setlogthresh(int thresh) { log_threshold = thresh; } static void eout(int level, int sys, char *fmt, va_list ap) { char buf[256]; int len; #if CAT_HAS_POSIX int savee = 0; if ( sys ) savee = errno; #endif /* CAT_HAS_POSIX */ len = str_vfmt(buf, sizeof(buf)-1, fmt, ap); #if CAT_HAS_POSIX if ( sys && len >= 0 && len < sizeof(buf) ) len = str_fmt(buf + len, sizeof(buf) - len, "%s\n", strerror(savee)); #endif /* CAT_HAS_POSIX */ if ( len < 0 ) str_copy(buf, "eout() -> error with string formatting\n", sizeof(buf)); emit_string(log_emitter, buf); #if CAT_HAS_POSIX if ( sys ) errno = savee; #endif /* CAT_HAS_POSIX */ }
github188/catlib
include/cat/match.h
/* * match.h -- fast string matching algorithms. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __match_h #define __match_h #include <cat/cat.h> #include <cat/mem.h> #include <cat/hash.h> /* Knuth-Morris-Pratt String matching */ struct kmppat { ulong * skips; struct raw pat; }; void kmp_pinit(struct kmppat *p, struct raw *pat, ulong *skips); int kmp_match(const struct raw *str, struct kmppat *pat, ulong *loc); /* Boyer-Moore String matching */ struct bmpat { ulong last[256]; struct raw pat; ulong * skips; }; void bm_pinit(struct bmpat *bmp, struct raw *pat, ulong *skips, ulong *scratch); /* This function initializes a Boyer-Moore pattern, but does not perform */ /* skip-ahead calculation. (i.e. the algorithm will only skip forward */ /* based on the last time the mismatched character was seen. This is */ /* quicker to initialize and lower memory, but can be less efficient */ /* especially for longer patterns. */ void bm_pinit_lite(struct bmpat *bmp, struct raw *pat); int bm_match(struct raw *str, struct bmpat *pat, ulong *loc); /* Suffix Tree string matching */ #ifndef CAT_SFX_MAXLEN #define CAT_SFX_MAXLEN 0x7ffffffe #undef CAT_SFX_EXPLICIT #define CAT_SFX_EXPLICIT (CAT_SFX_MAXLEN + 1) #endif /* CAT_SFX_MAXLEN */ struct sfxnode { struct sfxnode * sptr; }; struct sfxedge { struct hnode hentry; struct sfxnode * node; long start; long end; }; struct suffix { struct sfxnode * node; long start; long end; }; struct sfxedgekey { struct sfxnode * node; ushort character; }; struct sfxtree { struct memmgr * mm; struct raw str; struct htab edges; struct sfxnode root; }; int sfx_init(struct sfxtree *sfx, struct raw *str, struct memmgr *mm); int sfx_match(struct sfxtree *sfx, struct raw *pat, ulong *off); void sfx_clear(struct sfxtree *sfx); struct sfxnode *sfx_next(struct sfxtree *t, struct sfxnode *cur, int ch); /* Regular expression string matching */ #define REX_T_STRING 0 #define REX_T_CLASS 1 #define REX_T_BANCHOR 2 /* no repitition */ #define REX_T_EANCHOR 3 /* no repitition */ #define REX_T_CHOICE 4 /* no repitition */ #define REX_T_GROUP_S 5 /* no repitition */ #define REX_T_GROUP_E 6 #define REX_WILDCARD 0 struct rex_node { uchar type; uchar repmin; uchar repmax; struct rex_node * next; }; struct rex_node_str { struct rex_node base; uchar str[32]; ulong len; }; struct rex_ascii_class { struct rex_node base; uchar set[32]; }; struct rex_group { struct rex_node base; unsigned num; struct rex_group * other; }; struct rex_choice { struct rex_node base; struct rex_node * opt1; struct rex_node * opt2; }; struct rex_pat { struct memmgr * mm; int start_anchor; struct rex_group start; struct rex_group end; }; struct rex_match_loc { int valid; size_t start; size_t len; }; #define REX_MATCH 0 #define REX_NOMATCH 1 #define REX_ERROR -1 int rex_init(struct rex_pat *rxp, struct raw *pat, struct memmgr *mm, int *error); int rex_match(struct rex_pat *rxp, struct raw *str, struct rex_match_loc *m, uint nm); void rex_free(struct rex_pat *rxp); #endif /* __match_h */
github188/catlib
test/testdynmem.c
<reponame>github188/catlib<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- 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 dynmem Dm; void printblock(void *obj, void *ctx) { struct dynmem_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 dynmempool *pool = obj; int *poolno = ctx; *poolno += 1; printf("Pool %d\n", *poolno); dynmem_each_block(pool, printblock, NULL); } void printmem(struct dynmem *dm, const char *title) { int poolno = 0; printf("-- %s --\n", title); dynmem_each_pool(dm, printpool, &poolno); printf("\n"); } void getmem(struct dynmem *dm, struct raw *r, size_t len) { if (r->data) dynmem_free(dm, r->data); r->data = dynmem_malloc(dm, len); if (r->data) r->len = len; } void freemem(struct dynmem *dm, struct raw *r) { dynmem_free(dm, r->data); r->data = NULL; r->len = 0; } void freeallmem(struct dynmem *dm, struct raw *rarr, size_t ralen) { size_t i; for ( i = 0; i < ralen; i++ ) freemem(dm, 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(&Dm, "Initial state"); getmem(&Dm, &allocs[0], 128); printmem(&Dm, "First alloc"); getmem(&Dm, &allocs[1], 7); getmem(&Dm, &allocs[2], 7); printmem(&Dm, "Some more allocs"); freemem(&Dm, &allocs[1]); printmem(&Dm, "First free"); getmem(&Dm, &allocs[3], 48); printmem(&Dm, "Another alloc"); freemem(&Dm, &allocs[2]); printmem(&Dm, "more free"); freeallmem(&Dm, allocs, array_length(allocs)); printmem(&Dm, "freed all"); } void doit2() { int i, nops, len, idx, op; struct raw allocs[MAXALLOCS] = { 0 }; printmem(&Dm, "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(&Dm, &allocs[idx], len); } else { len = 0; freemem(&Dm, &allocs[idx]); } printraw(allocs, array_length(allocs)); printmem(&Dm, str); } printmem(&Dm, "Final before clear"); freeallmem(&Dm, allocs, array_length(allocs)); printmem(&Dm, "Final"); } int main(int argc, char *argv[]) { srand(time(NULL)); dynmem_init(&Dm); dynmem_add_pool(&Dm, Memory, sizeof(Memory)); doit(); doit2(); return 0; }
github188/catlib
attic/teststr.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/str.h> #include <cat/aux.h> #include <cat/err.h> #include <cat/mem.h> #include <string.h> int main(int argc, char *argv[]) { struct cstring *s1, *s2, *s3, *s4, *s5, *s6, *s7; const char *foo = "howdy there folks"; const char *bar = "another random string"; const char *pat = " fo"; char *p; int r, start, end; s1 = str_new("Hello World", -1, &estdcmem); s2 = str_copy(s1); s3 = str_slice(s1, 3, 8, 1); s4 = str_new(NULL, 4, &estdcmem); if (str_grow(&s4, strlen(foo) + 1) < 0) errsys("Couldn't grow string to length %d", strlen(foo) + 1); else printf("s4's length is now %d\n", s4->buf.len); str_scopy(s4, foo); s5 = str_fnew(&estdcmem, "String 4 is (%s) len = %d", s4->buf.data, str_len(s4)); s6 = str_new(NULL, 900, &estdcmem); str_set(s6, bar, strlen(bar)+1); s7 = str_splice(s2, 3, 8, s6, 1); printf("String 1 = %s\n", str_data(s1)); printf("String 2 = %s\n", str_data(s2)); printf("String 3 = %s\n", str_data(s3)); printf("String 4 = %s\n", str_data(s4)); printf("String 5 = %s\n", str_data(s5)); printf("String 6 = %s\n", str_data(s6)); printf("String 7 = %s\n", str_data(s7)); if ( str_cmp(s1, s2) == 0 ) printf("String 1 == String 2\n"); else printf("String 1 != String 2\n"); r = str_cmp(s1, s3); if ( r == 0 ) printf("String 1 == String 3\n"); else if ( r < 0 ) printf("String 1 < String 3\n"); else printf("String 1 > String 3\n"); p = strstr(str_data(s2), "llo"); printf("\"llo\" is at %d,%d in String 2\n", p - str_data(s2), p - str_data(s2) + strlen("llo")); start = str_find(s4, pat, -1); end = strlen(pat) + start; if ( start > 0 ) printf("(%s) is at (%d,%d) in (%s) *len = -1*\n", pat, start, end, str_data(s4)); else printf("(%s) is not in (%s) *len = -1*\n", pat, str_data(s4)); start = str_find(s4, pat, strlen(pat)); end = strlen(pat) + start; if ( start > 0 ) printf("(%s) is at (%d,%d) in (%s) *len = %d*\n", pat, start, end, str_data(s4), strlen(pat)); else printf("(%s) is not in (%s) *len = %d*\n", pat, str_data(s4), strlen(pat)); start = str_find(s5, pat, strlen(pat)); end = strlen(pat) + start; if ( start > 0 ) printf("(%s) is at (%d,%d) in (%s)\n", pat, start, end, str_data(s5)); else printf("(%s) is not in (%s)\n", pat, str_data(s5)); printf("Freeing them all\n"); str_free(s1); str_free(s2); str_free(s3); str_free(s4); str_free(s5); str_free(s6); str_free(s7); return 0; }
github188/catlib
include/cat/dynmem.h
<reponame>github188/catlib /* * dynmem.h -- Dynamic memory managers. * * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #ifndef __cat_dynmem_h #define __cat_dynmem_h #include <cat/cat.h> #include <cat/list.h> /* core alignment type */ union align_u { void * p; long l; size_t sz; double d; #if CAT_HAS_LONGLONG long long ll; #endif /* CAT_HAS_LONGLONG */ }; #define UNITSIZE sizeof(union align_u) STATIC_BUG_ON(align_u_not_power_2_size, (UNITSIZE & (UNITSIZE - 1)) != 0); struct memblk { union align_u mb_len; struct list mb_entry; }; struct dynmem { int dm_init; struct list dm_pools; struct list dm_blocks; struct list * dm_current; void * (*add_mem_func)(size_t len); }; struct dynmempool { struct list dmp_entry; size_t dmp_total_len; size_t dmp_useable_len; void * dmp_start; }; struct dynmem_block_fake { int allocated; int prev_allocated; size_t size; void * ptr; }; void dynmem_init(struct dynmem *dm); void *dynmem_malloc(struct dynmem *dm, size_t amt); void dynmem_free(struct dynmem *dm, void *mem); void *dynmem_realloc(struct dynmem *dm, void *omem, size_t newamt); void dynmem_add_pool(struct dynmem *dm, void *mem, size_t len); /* allows walking each pool in a dynmem heap */ void dynmem_each_pool(struct dynmem *dm, apply_f f, void *ctx); void dynmem_each_block(struct dynmempool *pool, apply_f f, void *ctx); #if CAT_64BIT #ifndef TLSF_LG2_ALIM #define TLSF_LG2_ALIM 63 #endif /* TLSF_LG2_ALIM */ typedef uint64_t tlsf_sz_t; #define TLSF_SZ_BITS 64 #ifndef TLSF_L2_LEN #define TLSF_L2_LEN 6 #endif /* TLSF_L2_LEN */ #if TLSF_L2_LEN > 6 #error "Max supported L2 len is 6 in a 64-bit architecture" #endif /* TLSF_L2_LEN */ #define tlsf_nlz(x) nlz_64(x) #define tlsf_ntz(x) ntz_64(x) #else /* CAT_64BIT */ #ifndef TLSF_LG2_ALIM #define TLSF_LG2_ALIM 31 #endif /* TLSF_LG2_ALIM */ typedef uint32_t tlsf_sz_t; #define TLSF_SZ_BITS 32 #ifndef TLSF_L2_LEN #define TLSF_L2_LEN 5 #endif /* TLSF_L2_LEN */ #if TLSF_L2_LEN > 5 #error "Max supported L2 len is 5 in a 32-bit architecture" #endif /* TLSF_L2_LEN */ #define tlsf_nlz(x) nlz_32(x) #define tlsf_ntz(x) ntz_32(x) #endif /* CAT_64BIT */ enum { TLSF_LG2_UNITSIZE = FLOG2(UNITSIZE), TLSF_MINNU = ((sizeof(struct memblk)+2*UNITSIZE-1)/UNITSIZE), TLSF_MINSZ = (TLSF_MINNU * UNITSIZE), TLSF_MINPOOL = ((TLSF_MINNU + 2) * UNITSIZE), TLSF_NUML2 = (TLSF_LG2_ALIM - TLSF_LG2_UNITSIZE), TLSF_FULLBLLEN = (1 << TLSF_L2_LEN), TLSF_NUMSMALL = (TLSF_L2_LEN), TLSF_NUMFULL = (TLSF_NUML2 - TLSF_L2_LEN) }; /* Must be #defined since enums must be of type 'int' */ #define TLSF_ALIM ((tlsf_sz_t)1 << TLSF_LG2_ALIM) /* TLSF_SZ_BITS list heads for each list with a # of UNITSIZE slots >= to min size for the list head. Then consider the smaller lists. Number of slots there is 1 for slot 0, 2 for slot 1, 4 for slot 2... So there are 2^TLSF_NUMSMALL-1 blocks in all for small lists. */ #define TLSF_MINBINS TLSF_MINNU #define TLSF_NUMHEADS ((TLSF_NUMFULL * TLSF_FULLBLLEN) + ((1 << TLSF_NUMSMALL) - 1)) struct tlsf_l2 { tlsf_sz_t tl2_bm; int tl2_nblists; struct list * tl2_blists; }; struct tlsf { struct list tlsf_pools; tlsf_sz_t tlsf_l1bm; struct tlsf_l2 tlsf_l1[TLSF_NUML2]; struct list tlsf_lists[TLSF_NUMHEADS]; }; struct tlsfpool { struct list tpl_entry; size_t tpl_total_len; size_t tpl_useable_len; void * tpl_start; }; struct tlsf_block_fake { int allocated; int prev_allocated; size_t size; void * ptr; }; void tlsf_init(struct tlsf *tlsf); void tlsf_add_pool(struct tlsf *tlsf, void *mem, size_t len); void *tlsf_malloc(struct tlsf *tlsf, size_t amt); void tlsf_free(struct tlsf *tlsf, void *mem); void *tlsf_realloc(struct tlsf *tlsf, void *omem, size_t newamt); void tlsf_each_pool(struct tlsf *tlsf, apply_f f, void *ctx); void tlsf_each_block(struct tlsfpool *pool, apply_f f, void *ctx); #endif /* __cat_dynmem_h */
github188/catlib
attic/mcache.h
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __mcache_h #define __mcache_h #include <cat/pool2.h> #define MC_MAXOHEAD sizeof(struct list) struct mc_page { struct list te; /* type entry */ struct list ce; /* cache entry */ struct mc_type * type; /* pointer to curren type */ int isdyn; /* was dynamically created */ int siz; /* length of page */ int avail; /* available memory */ int total; /* total useable memory */ }; union mc_page_u { CAT_ALIGN align; struct mc_page page; }; #define MC_PGSIZ sizeof(union mc_page_u) typedef void (*mc_initpg_f)(void *mem, int siz); typedef void *(*mc_alloc_f)(struct mc_page *pg, int len); typedef void (*mc_free_f)(struct mc_page *pg, void *item); struct mc_tdesc { int pgsiz; mc_initpg_f init; mc_alloc_f alloc; mc_free_f free; }; struct mc_type { struct list entry; struct mcache * mcache; struct mc_tdesc tdesc; int asiz; int maxalloc; int maxcache; struct list avail; struct list empty; struct list cache; int clen; }; struct mcache { struct list types; struct list pages; int pglen; memctl_f mctl; }; void mc_init(struct mcache *mc, int pglen, memctl_f mctl); void mc_inittype(struct mc_type *type, struct mc_tdesc *tdesc, int asiz, int maxalloc, int maxcache); void mc_addtype(struct mcache *mc, struct mc_type *type); void mc_freetype(struct mc_type *type); void mc_addpage(struct mcache *mc, void *page, int plen); void mc_rempage(struct mc_page *mcp); void * mc_alloc(struct mc_type *type, int len); void mc_free(void *item); struct mc_pool { union mc_page_u pageu; struct pool pool; int isiz; }; union mc_pool_u { struct mc_pool mcp; CAT_ALIGN align; }; void mc_pl_initpg(void *page, int siz); void * mc_pl_alloc(struct mc_page *mcp, int len); void mc_pl_free(struct mc_page *mcp, void *item); extern struct mc_tdesc mc_pooldesc /* = { sizeof(union mc_pool_u); mc_pl_initpg, mc_pl_alloc, mc_pl_free } */ ; /* example usage: struct mcache Cache; struct mc_type MCT_hnode, MCT_htab, MCT_anode, MCT_avl; mc_init(&Cache, 65536, xmemctl); mc_inittype(&MCT_hnode, &mc_pooldesc, sizeof(struct hnode), 0, 6); mc_inittype(&MCT_htab, &mc_pooldesc, sizeof(struct htab), 0, 1); mc_inittype(&MCT_anode, &mc_pooldesc, sizeof(struct anode), 0, 6); mc_inittype(&MCT_avl, &mc_pooldesc, sizeof(struct avl), 0, 1); for ( i = 0 ; i < nitems ; ++i ) { struct hnode *hnp; hnp = mc_alloc(&MCT_hnode, 1); ... } for ( i = 0 ... ) mc_free(hnp); To create a hash table that gets nodes from a pool: struct hnode * mc_newhn(void *k, void *d, unsigned h, void *ctx) { struct hnode *hnp; struct mc_type *type; hnp = mc_alloc(type); }; struct hashsys cachesys = { strcmp, strhash, NULL, mc_newhn, &MCT_hnode }; */ #endif /* __mcache_h */
github188/catlib
attic/mem.h
<filename>attic/mem.h /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_mem_h #define __cat_mem_h #include <cat/cat.h> #include <cat/aux.h> struct memsys; typedef void *(*alloc_f)(struct memsys *msys, unsigned size); typedef void *(*resize_f)(struct memsys *msys, void *old, unsigned size); typedef void (*free_f)(struct memsys *msys, void * tofree); struct memsys { alloc_f ms_alloc; resize_f ms_resize; free_f ms_free; void * ms_ctx; }; void *mem_get(struct memsys *m, unsigned long len); void *mem_resize(struct memsys *m, void *mem, unsigned long len); void mem_free(struct memsys *m, void *mem); extern void applyfree(void *data, void *memsys); #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB extern struct memsys stdmem; /* uses fatal system error messages */ extern void *emalloc(size_t size); extern void *erealloc(void *old, size_t size); extern struct memsys estdmem; /* uses exceptions */ extern const char *XMemErr; extern void *xmalloc(size_t size); extern void *xrealloc(void *old, size_t size); extern struct memsys xstdmem; #endif /* CAT_USE_STDLIB */ #endif /* __cat_mem_h */
github188/catlib
attic/dlist.h
/* * cat/dlist.h -- Delta list header file for catlib2 * * by <NAME> * * Copyright 2003, See accompanying license * */ #ifndef __CAT_DLIST_H #define __CAT_DLIST_H #ifdef CAT_DLIST_DO_DECL #define SAVE_INLINE CAT_USE_INLINE #undef CAT_USE_INLINE #define CAT_USE_INLINE 1 #endif /* CAT_DLIST_DO_DECL */ #include <cat/cat.h> #include <cat/list.h> #ifdef SAVE_INLINE #undef CAT_USE_INLINE #define CAT_USE_INLINE SAVE_INLINE #undef SAVE_INLINE #endif /* SAVE_INLINE */ #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_DLIST_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #endif /* CAT_USE_INLINE */ #define CAT_DL_EMPTY 0xffffffff #define CAT_DL_DLIST CAT_DL_EMPTY struct dlist { struct list entry; unsigned long ttl; } ; DECL void dl_init(struct dlist *node, unsigned long ttl); DECL void dl_ins(struct dlist *list, struct dlist *node); DECL unsigned long dl_first(struct dlist *list); DECL struct dlist * dl_deq(struct dlist *list); DECL void dl_adv(struct dlist *list, unsigned long amt, struct list *out); DECL void dl_rem(struct dlist *elem); #define dl_head(list) ((list)->entry.next) #define dl_end(list) (&(list)->entry) #define dl_next(node) ((struct dlist *)(list)->entry.next) #if defined(CAT_DLIST_DO_DECL) && CAT_DLIST_DO_DECL DECL void dl_init(struct dlist *node, unsigned long ttl) { Assert(node); l_init(&node->entry); node->ttl = ttl; } DECL void dl_ins(struct dlist *dlist, struct dlist *node) { unsigned long ttl; struct list *t, *list; struct dlist *dl; Assert(dlist); Assert(node); list = &dlist->entry; ttl = node->ttl; for ( t = l_head(list) ; t != l_end(list) ; t = t->next ) { dl = base(t, struct dlist, entry); if ( ttl < dl->ttl ) break; else ttl -= dl->ttl; } if ( t != l_end(list) ) dl->ttl -= ttl; l_ins(t->prev, &node->entry); node->ttl = ttl; } DECL unsigned long dl_first(struct dlist *dlist) { Assert(dlist); if ( l_isempty(&dlist->entry) ) return CAT_DL_EMPTY; else return base(l_head(&dlist->entry), struct dlist, entry)->ttl; } DECL struct dlist * dl_deq(struct dlist *dlist) { struct list *list, *node; Assert(dlist); list = &dlist->entry; if ( l_isempty(list) ) return NULL; else { node = l_head(list); l_rem(node); return base(node, struct dlist, entry); } } DECL void dl_adv(struct dlist *dlist, unsigned long delta, struct list *out) { struct dlist *dl; struct list *t, *head, *list; Assert(dlist); Assert(out); list = &dlist->entry; if ( l_isempty(list) ) return; for ( t = l_head(list) ; t != l_end(list) ; t = t->next ) { dl = base(t, struct dlist, entry); if ( dl->ttl > delta ) break; else delta -= dl->ttl; } if ( t != l_end(list) ) dl->ttl -= delta; head = l_head(list); t = t->prev; if ( t->next == head ) return; list->next = t->next; t->next->prev = list; head->prev = out; out->next = head; t->next = out; out->prev = t; } DECL void dl_rem(struct dlist *elem) { struct dlist *next; next = base(elem->entry.next, struct dlist, entry); if ( next->ttl != CAT_DL_DLIST ) next->ttl += elem->ttl; l_rem(&elem->entry); } #endif /* CAT_DLIST_DO_DECL */ #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB struct dclist { struct dlist entry; void * data; }; DECL struct dlist * dcl_new(unsigned long ttl, void *data); DECL void * dcl_free(struct dlist *node); DECL void * dcl_data(struct dlist *node); DECL void dcl_setd(struct dlist *node, void *data); #if defined(CAT_DLIST_DO_DECL) && CAT_DLIST_DO_DECL #include <stdlib.h> #include <cat/err.h> DECL struct dlist * dcl_new(unsigned long ttl, void *data) { struct dclist *node; node = malloc(sizeof(*node)); if ( ! node ) errsys("dcl_new: "); dl_init(&node->entry, ttl); node->data = data; return &node->entry; } DECL void * dcl_free(struct dlist * nodep) { void *old = NULL; struct dclist *node; if ( nodep ) { node = base(nodep, struct dclist, entry); old = node->data; free(node); } return old; } DECL void * dcl_data(struct dlist *nodep) { Assert(nodep); return base(nodep, struct dclist, entry)->data; } DECL void dcl_setd(struct dlist *nodep, void *data) { Assert(nodep); base(nodep, struct dclist, entry)->data = data; } #endif /* CAT_DLIST_DO_DECL */ #endif /* CAT_USE_STDLIB */ #undef DECL #undef CAT_DLIST_DO_DECL #endif /* __CAT_DLIST_H */
github188/catlib
include/std/string.h
/* * string.h -- C standard string manipulation routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_string_h #define __cat_string_h #include <cat/cat.h> #include <stdarg.h> #if !CAT_USE_STDLIB /* string.h */ int memcmp(const void *b1p, const void *b2p, size_t len); void *memcpy(void *dst, const void *src, size_t len); void *memmove(void *dst, const void *src, size_t len); void *memset(void *dst, int c, size_t len); size_t strlen(const char *s); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t max); char *strstr(const char *str, const char *pat); char *strchr(const char *s, int ch); char *strrchr(const char *s, int ch); char *strcpy(char *dst, const char *src); size_t strspn(const char *s, const char *accept); size_t strcspn(const char *s, const char *reject); char *strdup(const char *s); #endif /* !CAT_USE_STDLIB */ #endif /* __cat_string_h */
github188/catlib
test/testmem.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <cat/mem.h> #include <cat/stduse.h> #define NREPS 50000 #define NMEM 100 unsigned nreps = NREPS; #define TEST(op) \ { \ struct timeval start, stop; \ double usec, nspo; \ int i; \ \ gettimeofday(&start, NULL); \ for ( i = 0 ; 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", "--"); int main(int argc, char *argv[]) { void *m; void *arr[NMEM]; int k; TEST(m=malloc(50); free(m)); TEST(m=mem_get(&estdmm,50); mem_free(&estdmm,m)); printf("\n"); TEST(m=malloc(256); free(m)); TEST(m=mem_get(&estdmm,256); mem_free(&estdmm,m)); printf("\n"); TEST(m=malloc(4096); free(m)); TEST(m=mem_get(&estdmm,4096); mem_free(&estdmm,m)); printf("\n"); TEST(m=malloc(65536); free(m)); TEST(m=mem_get(&estdmm,65536); mem_free(&estdmm,m)); printf("\n"); TEST(m=malloc(65538); free(m)); TEST(m=mem_get(&estdmm,65538); mem_free(&estdmm,m)); printf("\n"); TEST(for(k=0;k<NMEM;++k)arr[k]=malloc(256);while(k-->0)free(arr[k]);); TEST(for(k=0;k<NMEM;++k)arr[k]=mem_get(&estdmm,256);while(k-->0)mem_free(&estdmm,arr[k]);); return 0; }
github188/catlib
include/cat/heap.h
<filename>include/cat/heap.h /* * cat/heap.h -- Array-based heap implementation * * by <NAME> * * Copyright 2003-2017 -- See accompanying license * */ #ifndef __cat_heap_h #define __cat_heap_h #include <cat/cat.h> #include <cat/mem.h> #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define PTRDECL static #define LOCAL static inline #define CAT_HEAP_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #define PTRDECL #define LOCAL static #endif /* CAT_USE_INLINE */ /* Heap data structure */ struct heap { int size; /* current maximum number of elements */ int fill; /* Number of elements populated */ void ** elem; /* Pointer to array of elem pointers */ cmp_f cmp; /* Comparison function for the heap */ struct memmgr * mm; /* Memory manager for dynamic resize */ }; /* * Initialize a heap 'hp' so 'elem' points to an initial array of * 'size' element pointers. 'fill' points to the number of elements * that 'elem' currently has populated. 'cmp' is the comparison function. * If 'mm' is non-null, then it will be used to resize 'elem' as the heap * grows. Otherwise the heap is treated as having a fixed maximum size. * The initialization process "sorts" the initial elements in the heap. */ DECL void hp_init(struct heap *hp, void **elem, int size, int fill, cmp_f cmp, struct memmgr *mm); /* * Add 'elem' into 'hp'. Returns 0 on success or -1 if the heap is * full and can't be expanded. On success, if 'pos' is non-NULL, * then on return *pos will return the position of 'elem' hp->elem. */ DECL int hp_add(struct heap *hp, void *elem, int *pos); /* Return the index in 'hp->elem' of 'data' */ DECL int hp_find(struct heap *hp, void *data); /* * Extract (remove) the element at the top of the heap and return it. * Return NULL if the heap is empty. */ DECL void * hp_extract(struct heap *hp); /* Remove the element at position 'elem' from the heap. */ DECL void * hp_rem(struct heap *hp, int elem); /* ----- Implementation ----- */ #if defined(CAT_HEAP_DO_DECL) && CAT_HEAP_DO_DECL LOCAL int reheapup(struct heap *hp, int pos) { int ppos = (pos-1) >> 1; void *hold; abort_unless(hp); if ( pos >= hp->fill ) return 0; while ( (pos > 0) && (hp->cmp(hp->elem[ppos], hp->elem[pos]) > 0) ) { hold = hp->elem[pos]; hp->elem[pos] = hp->elem[ppos]; hp->elem[ppos] = hold; pos = ppos; ppos = (pos-1) >> 1; } return pos; } LOCAL void reheapdown(struct heap *hp, int pos) { int didswap; int cld; void *hold; abort_unless(hp); if ( pos >= hp->fill ) return; do { didswap = 0; if ( (cld = (pos << 1) + 1) >= hp->fill ) break; if ( ( cld + 1 < hp->fill ) && ( hp->cmp(hp->elem[cld], hp->elem[cld+1]) > 0 ) ) cld += 1; if ( hp->cmp(hp->elem[pos], hp->elem[cld]) > 0 ) { didswap = 1; hold = hp->elem[cld]; hp->elem[cld] = hp->elem[pos]; hp->elem[pos] = hold; pos = cld; } } while (didswap); } DECL void hp_init(struct heap *hp, void **elem, int size, int fill, cmp_f cmp, struct memmgr *mm) { int i; abort_unless(hp); abort_unless(size >= 0); abort_unless(fill >= 0); abort_unless(cmp); hp->size = size; hp->elem = elem; hp->cmp = cmp; hp->mm = mm; if ( (hp->fill = fill) ) { if ( fill > size ) /* sanity check */ hp->fill = size; for ( i = hp->fill >> 1 ; i >= 0 ; i-- ) reheapdown(hp, i); } } DECL int hp_add(struct heap *hp, void *elem, int *pos) { void * p; int n; abort_unless(hp); if ( hp->fill == hp->size ) { if ( ! hp->mm ) return -1; if ( ! hp->size ) n = 32; else n = hp->size << 1; if ( n < hp->size ) /* XXX check for overflow */ return -1; p = mem_resize(hp->mm, hp->elem, n * sizeof(void *)); if ( p == NULL ) return -1; hp->elem = p; hp->size = n; } hp->elem[n = hp->fill++] = elem; n = reheapup(hp, n); if ( pos ) *pos = n; return 0; } DECL int hp_find(struct heap *hp, void *data) { int i; abort_unless(hp); for ( i = 0 ; i < hp->fill ; ++i ) if ( ! hp->cmp(hp->elem[i], data) ) return i; return -1; } DECL void * hp_extract(struct heap *hp) { void *hold; int last; abort_unless(hp); last = hp->fill - 1; if ( hp->fill == 0 ) return NULL; hold = hp->elem[0]; hp->elem[0] = hp->elem[last]; hp->elem[last] = hold; hp->fill -= 1; reheapdown(hp, 0); return hold; } DECL void * hp_rem(struct heap *hp, int elem) { void *hold; int last = hp->fill-1; abort_unless(hp); abort_unless(elem >= 0); if ( elem >= hp->fill ) return NULL; hold = hp->elem[elem]; hp->elem[elem] = hp->elem[last]; hp->elem[last] = hold; hp->fill = last; if ( reheapup(hp, elem) == elem ) reheapdown(hp, elem); return hp->elem[last]; } #endif /* if defined(CAT_HEAP_DO_DECL) && CAT_HEAP_DO_DECL */ #undef PTRDECL #undef DECL #undef LOCAL #endif /* __cat_heap_h */
github188/catlib
src/crypto.c
<reponame>github188/catlib /* * crypto.c -- Cryptographic algorithm implementations * * by <NAME> * * Copyright 2009-2015 See accompanying license * */ #include <cat/crypto.h> #include <string.h> void arc4_init(struct arc4ctx *arc4, const void *key, ulong len) { int i, j; byte_t b; const byte_t *keyp = key; abort_unless(arc4 != NULL && (key != NULL || len == 0)); for ( i = 0; i < 256 ; ++i ) arc4->s[i] = i; j = 0; for ( i = 0; i < 256 ; ++i ) { j = (j + arc4->s[i] + keyp[i % len]) & 0xFF; b = arc4->s[i]; arc4->s[i] = arc4->s[j]; arc4->s[j] = b; } arc4->i = 0; arc4->j = 0; } void arc4_gen(struct arc4ctx *arc4, void *out, ulong len) { int i, j; byte_t b1, b2; byte_t *outp = out; abort_unless(arc4 != NULL && (out != NULL || len == 0)); i = arc4->i; j = arc4->j; while ( len-- > 0 ) { i = (i + 1) & 0xff; j = (j + arc4->s[i]) & 0xff; b1 = arc4->s[i]; b2 = arc4->s[i] = arc4->s[j]; arc4->s[j] = b1; *outp++ = arc4->s[(b1 + b2) & 0xff]; } arc4->i = i; arc4->j = j; } void arc4_encrypt(struct arc4ctx *arc4, const void *in, void *out, ulong len) { int i, j; byte_t b1, b2; const byte_t *inp = in; byte_t *outp = out; abort_unless(arc4 != NULL && ((in != NULL && out != NULL) || len == 0)); i = arc4->i; j = arc4->j; while ( len-- > 0 ) { i = (i + 1) & 0xff; j = (j + arc4->s[i]) & 0xff; b1 = arc4->s[i]; b2 = arc4->s[i] = arc4->s[j]; arc4->s[j] = b1; *outp++ = *inp++ ^ arc4->s[(b1 + b2) & 0xff]; } arc4->i = i; arc4->j = j; } static ulong sha256_k[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, }; static ulong ror(ulong x, uint amt) { return ((x >> amt) | (x << (32 - amt))) & 0xFFFFFFFF; } static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); } static ulong Maj(ulong x, ulong y, ulong z) { return (x & y) ^ (x & z) ^ (y & z); } static ulong Sigma0(ulong x) { return ror(x, 2) ^ ror(x, 13) ^ ror(x, 22); } static ulong Sigma1(ulong x) { return ror(x, 6) ^ ror(x, 11) ^ ror(x, 25); } static ulong sigma0(ulong x) { return ror(x, 7) ^ ror(x, 18) ^ ((x >> 3) & 0xFFFFFFFF); } static ulong sigma1(ulong x) { return ror(x, 17) ^ ror(x, 19) ^ ((x >> 10) & 0xFFFFFFFF); } static int sha256_add_bytes(struct sha256ctx *s, byte_t **pp, ulong *len) { int idx = s->llo & 63; int toadd = 64 - idx; int i; byte_t *p = *pp; ulong olo; if ( toadd > *len ) toadd = *len; for ( i = 0; i < toadd; ++i ) { switch ( idx & 3 ) { case 0: s->w[idx / 4] = ((ulong)*p++ << 24); break; case 1: s->w[idx / 4] |= ((ulong)*p++ << 16); break; case 2: s->w[idx / 4] |= ((ulong)*p++ << 8); break; case 3: s->w[idx / 4] |= (ulong)*p++; break; } ++idx; } *pp = p; *len -= toadd; olo = s->llo; s->llo = (olo + toadd) & 0xFFFFFFFF; if ( s->llo < olo ) s->lhi++; return (idx == 64); } void sha256_init(struct sha256ctx *s) { memset(s, 0, sizeof(*s)); s->llo = 0; s->lhi = 0; s->h[0] = 0x6a09e667; s->h[1] = 0xbb67ae85; s->h[2] = 0x3c6ef372; s->h[3] = 0xa54ff53a; s->h[4] = 0x510e527f; s->h[5] = 0x9b05688c; s->h[6] = 0x1f83d9ab; s->h[7] = 0x5be0cd19; } void sha256_hash_block(struct sha256ctx *s) { int i; ulong a, b, c, d, e, f, g, h, t1, t2; /* compute the schedule */ for ( i = 16; i < 64; ++i ) s->w[i] = (sigma1(s->w[i-2]) + s->w[i-7] + sigma0(s->w[i-15]) + s->w[i-16]) & 0xFFFFFFFF; /* set the working variables */ a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; e = s->h[4]; f = s->h[5]; g = s->h[6]; h = s->h[7]; /* hash rounds */ for ( i = 0; i < 64; ++i ) { t1 = (h + Sigma1(e) + Ch(e, f, g) + sha256_k[i] + s->w[i]) & 0xFFFFFFFF; t2 = (Sigma0(a) + Maj(a, b, c)) & 0xFFFFFFFF; h = g; g = f; f = e; e = (d + t1) & 0xFFFFFFFF; d = c; c = b; b = a; a = (t1 + t2) & 0xFFFFFFFF; } s->h[0] = (s->h[0] + a) & 0xFFFFFFFF; s->h[1] = (s->h[1] + b) & 0xFFFFFFFF; s->h[2] = (s->h[2] + c) & 0xFFFFFFFF; s->h[3] = (s->h[3] + d) & 0xFFFFFFFF; s->h[4] = (s->h[4] + e) & 0xFFFFFFFF; s->h[5] = (s->h[5] + f) & 0xFFFFFFFF; s->h[6] = (s->h[6] + g) & 0xFFFFFFFF; s->h[7] = (s->h[7] + h) & 0xFFFFFFFF; } void sha256_add(struct sha256ctx *s, void *vp, ulong len) { byte_t *p = vp; while ( len > 0 ) if ( sha256_add_bytes(s, &p, &len) ) sha256_hash_block(s); } void sha256_fini(struct sha256ctx *s, byte_t hash[32]) { byte_t pad[72]; byte_t *p; ulong plen; ulong llo, lhi; int i; /* initialize the pad bytes to add */ memset(pad, 0, sizeof(pad)); pad[0] = 0x80; plen = 64 - (s->llo % 63); if ( plen < 9 ) plen += 64; /* compute length into bits */ lhi = (s->lhi << 3) + (s->llo >> 29); llo = (s->llo << 3) & 0xFFFFFFFF; /* encode as a big-endian bytes */ p = &pad[plen - 8]; *p++ = (lhi >> 24) & 0xFF; *p++ = (lhi >> 16) & 0xFF; *p++ = (lhi >> 8) & 0xFF; *p++ = (lhi >> 0) & 0xFF; *p++ = (llo >> 24) & 0xFF; *p++ = (llo >> 16) & 0xFF; *p++ = (llo >> 8) & 0xFF; *p++ = (llo >> 0) & 0xFF; /* hash the last block(s) */ p = pad; while ( plen > 0 ) { sha256_add_bytes(s, &p, &plen); sha256_hash_block(s); } /* extract the hash value into hash bytes */ for ( i = 0; i < 32; ++i ) hash[i] = (s->h[i / 4] >> ((3 - (i % 4)) * 8)) & 0xFF; memset(s, 0, sizeof(*s)); } void sha256(void *in, ulong len, byte_t hash[32]) { struct sha256ctx s; sha256_init(&s); sha256_add(&s, in, len); sha256_fini(&s, hash); } #define U8TOU32LE(_p) \ ((ulong)((_p)[0]) | ((ulong)((_p)[1]) << 8) | \ ((ulong)((_p)[2]) << 16) | ((ulong)((_p)[3]) << 24)) void siphash_init(struct siphashctx *shc, byte_t key[16]) { shc->nbytes = 0; shc->state[0] = 0; shc->state[1] = 0; shc->v0[0] = 0x70736575ul ^ U8TOU32LE(key); shc->v0[1] = 0x736f6d65ul ^ U8TOU32LE(key + 4); shc->v1[0] = 0x6e646f6dul ^ U8TOU32LE(key + 8); shc->v1[1] = 0x646f7261ul ^ U8TOU32LE(key + 12); shc->v2[0] = 0x6e657261ul ^ U8TOU32LE(key); shc->v2[1] = 0x6c796765ul ^ U8TOU32LE(key + 4); shc->v3[0] = 0x79746573ul ^ U8TOU32LE(key + 8); shc->v3[1] = 0x74656462ul ^ U8TOU32LE(key + 12); } #undef U8TOU32LE #define ADD64(_v0, _v1) \ do { \ ulong _ov00 = (_v0)[0]; \ (_v0)[0] += (_v1)[0]; \ (_v0)[0] &= 0xFFFFFFFF; \ (_v0)[1] += (_v1)[1] + ((_v0)[0] < _ov00); \ (_v0)[1] &= 0xFFFFFFFF; \ } while (0) #define ROTL64(_v, _amt) \ do { \ ulong out0 = (_v)[0] >> (32 - (_amt)); \ ulong out1 = (_v)[1] >> (32 - (_amt)); \ (_v)[0] = (((_v)[0] << (_amt)) | out1) & 0xFFFFFFFF; \ (_v)[1] = (((_v)[1] << (_amt)) | out0) & 0xFFFFFFFF; \ } while (0) #define ROTL64_32(_v) \ do { \ ulong t = (_v)[0]; \ (_v)[0] = (_v)[1]; \ (_v)[1] = t; \ } while (0) #define XOR64(_v0, _v1) \ do { \ (_v0)[0] ^= (_v1)[0]; \ (_v0)[1] ^= (_v1)[1]; \ } while (0) static void siphash_round(struct siphashctx *shc) { ADD64(shc->v0, shc->v1); ADD64(shc->v2, shc->v3); ROTL64(shc->v1, 13); ROTL64(shc->v3, 16); XOR64(shc->v1, shc->v0); XOR64(shc->v3, shc->v2); ROTL64_32(shc->v0); ADD64(shc->v2, shc->v1); ADD64(shc->v0, shc->v3); ROTL64(shc->v1, 17); ROTL64(shc->v3, 21); XOR64(shc->v1, shc->v2); XOR64(shc->v3, shc->v0); ROTL64_32(shc->v2); } static int siphash_add_bytes(struct siphashctx *shc, const byte_t **bp, ulong *amt) { uint off = shc->nbytes % 8; uint toadd; uint i; if ( off == 0 && *amt >= 8 ) { /* fast path */ shc->state[0] = (*bp)[0] | (*bp)[1] << 8 | (*bp)[2] << 16 | (*bp)[3] << 24; shc->state[1] = (*bp)[4] | (*bp)[5] << 8 | (*bp)[6] << 16 | (*bp)[7] << 24; shc->nbytes += 8; *amt -= 8; *bp += 8; return 1; } else { /* slow path */ if ( off == 0 ) { shc->state[0] = 0; shc->state[1] = 0; } toadd = 8 - off; if ( toadd > *amt ) toadd = *amt; for ( i = 0; i < toadd; ++i, ++*bp, ++off ) { if ( off < 4 ) { shc->state[0] |= **bp << (8 * off); } else { shc->state[1] |= **bp << (8 * (off - 4)); } } shc->nbytes += toadd; *amt -= toadd; return shc->nbytes % 8 == 0; } } void siphash24_add(struct siphashctx *shc, const void *p, ulong len) { const byte_t *bp = p; while ( len > 0 ) { if ( siphash_add_bytes(shc, &bp, &len) ) { XOR64(shc->v3, shc->state); siphash_round(shc); siphash_round(shc); XOR64(shc->v0, shc->state); } } } void siphash24_fini(struct siphashctx *shc, byte_t hash[8]) { if ( shc->nbytes % 8 == 0 ) { shc->state[0] = 0; shc->state[1] = 0; } shc->state[1] |= (shc->nbytes % 256) << 24; XOR64(shc->v3, shc->state); siphash_round(shc); siphash_round(shc); XOR64(shc->v0, shc->state); /* finalize hash */ shc->v2[0] ^= 0xff; siphash_round(shc); siphash_round(shc); siphash_round(shc); siphash_round(shc); shc->state[0] = shc->v0[0] ^ shc->v1[0] ^ shc->v2[0] ^ shc->v3[0]; shc->state[1] = shc->v0[1] ^ shc->v1[1] ^ shc->v2[1] ^ shc->v3[1]; /* copy out result */ hash[0] = shc->state[0] & 0xff; hash[1] = (shc->state[0] >> 8) & 0xff; hash[2] = (shc->state[0] >> 16) & 0xff; hash[3] = (shc->state[0] >> 24) & 0xff; hash[4] = shc->state[1] & 0xff; hash[5] = (shc->state[1] >> 8) & 0xff; hash[6] = (shc->state[1] >> 16) & 0xff; hash[7] = (shc->state[1] >> 24) & 0xff; /* clean up state for safety */ memset(shc, 0, sizeof(*shc)); } #undef ADD64 #undef XOR64 #undef ROTL64 #undef ROTL64_32 void siphash24(byte_t key[16], const void *p, ulong len, byte_t hash[8]) { struct siphashctx shc; siphash_init(&shc, key); siphash24_add(&shc, p, len); siphash24_fini(&shc, hash); } void ht_sh24_init(struct ht_sh24_ctx *hsc, const void *k, ulong len) { const byte_t *p = k; ulong i; memset(hsc, 0, sizeof(*hsc)); for ( i = 0; i < len; ++i, ++p ) hsc->key[i % 4] ^= *p; } uint ht_sh24_shash(const void *sp, void *hscp) { const char *s = sp; struct ht_sh24_ctx *hsc = hscp; byte_t hash[8]; ulong len = 0; while ( *s++ != '\0' ) ++len; siphash24(hsc->key, sp, len, hash); return hash[0] | hash[1] << 8 | hash[2] << 16 | hash[3] << 24; } uint ht_sh24_rhash(const void *rp, void *hscp) { const struct raw *r = rp; struct ht_sh24_ctx *hsc = hscp; byte_t hash[8]; siphash24(hsc->key, r->data, r->len, hash); return hash[0] | hash[1] << 8 | hash[2] << 16 | hash[3] << 24; }
github188/catlib
test/testbitset.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <sys/time.h> #include <cat/stduse.h> #define S0LEN 1024 #define NT 100000000 int main(int argc, char *argv[]) { struct timeval tv, tv2; double usec; struct safebitset *set1, *set2; unsigned i, bit; DECLARE_BITSET(set0, S0LEN); bset_fill(set0, S0LEN); bset_clr(set0, 100); if ( bset_test(set0, 100) ) logrec(0, "Should not have found 100 in set0\n"); bset_clr(set0, 2); bset_clr(set0, 198); bset_set_to(set0, 100, 1); if ( !bset_test(set0, 3) ) logrec(0, "Should have found 3 in set0\n"); if ( bset_test(set0, 2) ) logrec(0, "Should not have found 2 in set0\n"); if ( !bset_test(set0, 190) ) logrec(0, "Should have found 190 in set0\n"); if ( bset_test(set0, 198) ) logrec(0, "Should not have found 198 in set0\n"); if ( !bset_test(set0, 100) ) logrec(0, "Should have found 100 in set0\n"); set1 = sbs_new(&estdmm, 5); set2 = sbs_new(&estdmm, 378); sbs_fill(set2); sbs_set(set1, 3); sbs_set(set1, 2); if ( sbs_test(set1, 4) ) logrec(0, "Should not have found 4 in set1\n"); if ( !sbs_test(set1, 3) ) logrec(0, "Should have found 3 in set1\n"); sbs_clr(set2, 3); printf("Copied %u bits (should be %u)\n", (uint)sbs_copy(set1, set2), (uint)set1->nbits); sbs_set_to(set1, 1, 0); sbs_set_to(set1, 0, 1); if ( bset_test(set1->set, 5) ) logrec(0, "Should not have found 5 in set1 after copy\n"); if ( sbs_test(set1, 3) ) logrec(0, "Should not have found 3 in set1 after copy\n"); if ( !sbs_test(set1, 4) ) logrec(0, "Should have found 4 in set1 after copy\n"); if ( sbs_test(set1, 1) ) logrec(0, "Should not have found 1 in set1 after copy\n"); if ( !sbs_test(set1, 0) ) logrec(0, "Should have found 0 in set1 after copy\n"); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) sbs_set(set2, i & 0xff); gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for sbs_set()\n", usec * 1000); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) sbs_clr(set2, i & 0xff); gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for sbs_clr()\n", usec * 1000); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) sbs_set_to(set2, i & 0xff, i & 1); gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for sbs_set_to()\n", usec * 1000); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) sbs_test(set2, i & 0xff); gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for sbs_test()\n", usec * 1000); sbs_free(set2); sbs_free(set1); gettimeofday(&tv, 0); for ( i = 0 ; i < NT ; ++i ) { bit = i & (S0LEN - 1); if ( bset_test(set0, bit) ) bset_clr(set0, bit); else bset_set(set0, bit); } gettimeofday(&tv2, 0); usec = (tv2.tv_sec - tv.tv_sec) * 1000000 + tv2.tv_usec - tv.tv_usec; usec /= NT; printf("Roughly %f nanoseconds for bset_*()-based toggle\n", usec * 1000); printf("Tests completed\n"); return 0; }
github188/catlib
test/testsplay.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <cat/splay.h> #include <cat/stduse.h> #include <cat/emalloc.h> #include <sys/time.h> #define NUMSTR 4 #define NA 200 void printst(struct stnode *n, int d) { int i; struct cstnode *csn = container(n, struct cstnode, node); if ( n->st_right ) printst(n->st_right, d+1); for ( i = 0 ; i < d ; ++i ) printf(" "); printf("[%s:%s]\n", (char *)n->key, (char *)csn->data); if ( n->st_left ) printst(n->st_left, d+1); } void print_splay(struct sptree *t) { struct stnode *top = t->root.p[CST_P]; if ( top == NULL ) printf("tree is empty\n"); else printst(top, 0); } void ourfree(void *data, void *ctx) { free(data); } #define NOPS 65536 #define NITER (NOPS * 128) void timeit() { struct stnode nodes[NOPS], *finder; struct timeval start, end; int i, j, dir; struct sptree t; double dbl; for (i = 0; i < NOPS; i++) st_ninit(&nodes[i], str_fmt_a("node%d", i)); st_init(&t, cmp_str); gettimeofday(&start, NULL); for (j = 0; j < NITER / NOPS; j++) { for (i = 0; i < NOPS; i++) { finder = st_lkup(&t, nodes[i].key); if (finder) err("Found duplicate key for %s", nodes[i].key); st_ins(&t, &nodes[i]); } for (i = 0; i < NOPS; i++) st_rem(&nodes[i]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem w/ %d entries max\n", dbl / (double)NITER, NOPS); gettimeofday(&start, NULL); for (i = 0; i < NITER; i++) { finder = st_lkup(&t, nodes[0].key); if (finder) err("Found duplicate key for %s", nodes[0].key); st_ins(&t, &nodes[0]); st_rem(&nodes[0]); } gettimeofday(&end, NULL); dbl = end.tv_usec - start.tv_usec; dbl *= 1000.0; dbl += (end.tv_sec - start.tv_sec) * 1e9; printf("Roughly %f nanoseconds per lkup-ins-rem (1 item deep max)\n", dbl / (double)NITER); for (i = 0; i < NOPS; i++) free(nodes[i].key); } int main() { int i, idx, tmp; int arr[NA]; char nstr[80], vstr[80]; void free(void *); char *strs[NUMSTR][2] = { {"key 1", "Hi there!" }, {"key2", "String 2!"}, {"Key 3!", "By now! this is over."}, {"key 1", "Overwrite."} }; struct cstree *t; char *s; struct stnode *np; t = cst_new(&cst_std_attr_skey, 1); for (i = 0; i < NUMSTR; i++) { cst_put(t, strs[i][0], strs[i][1]); s = cst_get(t, strs[i][0]); printf("Put (%s) at key (%s): %p\n", s, strs[i][0], s); fflush(stdout); } if (cst_get(t, "bye")) printf("found something I shouldn't have!\n"); fflush(stdout); s = cst_get(t, strs[1][0]); printf("Under key %s is the string %s\n", strs[1][0], s); printf("address is %p\n\n", s); fflush(stdout); s = cst_get(t, strs[2][0]); printf("Under key %s is the string %s\n", strs[2][0], s); printf("address is %p\n\n", s); fflush(stdout); s = cst_get(t, strs[0][0]); printf("Under key %s is the string %s\n", strs[0][0], s); printf("address is %p\n\n", s); fflush(stdout); print_splay(&t->tree); fflush(stdout); s = cst_del(t, strs[1][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); s = cst_del(t, strs[2][0]); printf("Deleted %s\n", s); printf("address is %p\n\n", s); fflush(stdout); if (cst_get(t, strs[1][0])) printf("Error! Thing not deleted! : %s\n", (char *)cst_get(t, strs[1][0])); fflush(stdout); print_splay(&t->tree); printf("\n"); cst_free(t); /* get rid of "Overwrite!" */ t = cst_new(&cst_std_attr_skey, 1); for ( i = 0 ; i < NA ; ++i ) arr[i] = i; for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); /* printf("\n"); print_splay(t); printf("\n"); fflush(stdout); */ sprintf(nstr, "k%03d", arr[i]); sprintf(vstr, "v%03d", arr[i]); cst_put(t, nstr, estrdup(vstr)); } printf("\n\n"); print_splay(&t->tree); printf("\n\n"); fflush(stdout); for ( i = 0 ; i < (NA-1) ; ++i ) { idx = abs(rand()) % (NA - i) + i; tmp = arr[idx]; arr[idx] = arr[i]; arr[i] = tmp; } for ( i = 0 ; i < NA ; ++i ) { printf("%d ", arr[i]); /* printf("\n"); printrbt(t); printf("\n\n"); fflush(stdout); */ sprintf(nstr, "k%03d", arr[i]); s = cst_del(t, nstr); free(s); } printf("\n\n"); fflush(stdout); print_splay(&t->tree); fflush(stdout); cst_apply(t, ourfree, NULL); cst_free(t); printf("Freed\n"); timeit(); printf("Ok!\n"); return 0; }
github188/catlib
include/cat/aux.h
/* * cat/aux.h -- Auxiliary functions * * by <NAME> * * Copyright 2007-2014 -- See accompanying license * */ #ifndef __cat_aux_h #define __cat_aux_h #include <cat/cat.h> /* These NEED to be extern so that function pointers can point to them */ extern int cmp_ptr(const void *, const void *); extern int cmp_str(const void *, const void *); extern int cmp_raw(const void *, const void *); extern int cmp_intptr(const void *, const void *); extern int cmp_uintptr(const void *, const void *); ulong uldivmod(ulong dend, ulong dsor, int div); #if CAT_HAS_LONGLONG ullong ulldivmod(ullong dend, ullong dsor, int div); #endif #endif /* __cat_aux_h */
github188/catlib
include/cat/io.h
<filename>include/cat/io.h<gh_stars>1-10 /* * cat/io.h -- Input/Output functions * * <NAME> * * Copyright 1999-2012 -- see accompanying license * */ #ifndef __cat_io_h #define __cat_io_h #include <cat/cat.h> #if CAT_HAS_POSIX #include <unistd.h> /* I/O functions */ /* * read 'len' bytes from 'fd'. Keeps trying to read bytes until it gets all * 'len' bytes or encounters an end of file or error. Returns a short count * on an end-of-file and a -1 on an error. Aborts on a parameter error: * (negative fd, NULL buf or negative len). Note that this function ignores * signal interruptions and keeps trying until a full read count completes. * This is fine for some applications, but not for others paying attention to * signal interruptions. */ ssize_t io_read(int fd, void *buf, ssize_t len); /* * write 'len' bytes from 'fd'. Keeps trying to write bytes until it gets all * 'len' bytes or encounters an end of file or error. Returns a short count * on an end-of-file and a -1 on an error. Aborts on a parameter error: * (negative fd, NULL buf or negative len). Note that this function ignores * signal interruptions and keeps trying until a full read count completes. * This is fine for some applications, but not for others paying attention to * signal interruptions. */ ssize_t io_write(int fd, void *buf, ssize_t len); /* * read up to 'len' bytes from 'fd'. Returns the number of bytes read or a -1 * on an error. Aborts on a parameter error: (negative fd, NULL buf or * negative len). Note that this function ignores signal interruptions and keeps * trying until read returns 0 or more or an error occurs. This is fine for some * applications, but not for others paying attention to signal interruptions. */ ssize_t io_read_upto(int fd, void *buf, ssize_t len); /* * write up to 'len' bytes from 'fd'. Returns the number of bytes read or a -1 * on an error. Aborts on a parameter error: (negative fd, NULL buf or * negative len). Note that this function ignores signal interruptions and keeps * trying until write returns 0 or more or an error occurs. This is fine for some * applications, but not for others paying attention to signal interruptions. */ ssize_t io_write_upto(int fd, void *buf, ssize_t len); /* I/O flags for file file descriptors */ /* * Check whether a file desriptor is ready for reading or writing or has a * pending exception. The caller can specify a timeout in seconds to wait * for the condition to arrive. If the timeout is < 0 then the call will * wait indefinitely. If the timeout is 0.0, the call will return immediately. * Returns -1 on an error, 1 if the condition is fulfilled and 0 if the * condition isn't satisfied. Aborts on negative file descriptor. This * function ignores an interrupted wait and tries again until successful. This * is fine for some applications, but not for those that may want the signal * to abort the wait. */ enum { CAT_IOT_READ = 1, CAT_IOT_WRITE = 2, CAT_IOT_EXCEPT = 3 }; int io_check_ready(int fd, int type, double timeout); /* * Enable non-blocking on a file descriptor. Returns 0 on success or -1 * on error. Aborts on a negative file descriptor. */ int io_setnblk(int fd); /* * Disable non-blocking on a file descriptor. Returns 0 on success or -1 * on error. Aborts on a negative file descriptor. */ int io_clrnblk(int fd); #endif /* CAT_HAS_POSIX */ #endif /* __cat_io_h */
github188/catlib
test/testcatstr.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <cat/catstr.h> const char *foo() { CS_DECLARE_Q(static, str1, 32); CS_DECLARE(str2, 16); cs_set_cstr(&str2, "hello world"); cs_format_d(&str1, "%s: %d\n", cs_to_cstr(&str2), 5); return cs_to_cstr(&str1); } int main(int argc, char *argv[]) { puts(foo()); return 0; }
github188/catlib
src/time.c
/* * time.c -- time manipulation functions * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_TIME_DO_DECL #define CAT_USE_INLINE 0 #define CAT_TIME_DO_DECL 1 #include <cat/time.h>
github188/catlib
include/cat/rbtree.h
/* * cat/rbtree.h -- Red-Black tree implementation * * by <NAME> * * Copyright 2004-2017 -- See accompanying license * */ #ifndef __cat_rbtree_h #define __cat_rbtree_h #include <cat/cat.h> #include <cat/aux.h> /* Structure for a Red-Black tree node: to be embedded in other structures */ struct rbnode { struct rbnode * p[3]; /* child/parent pointers */ char pdir; /* on the parent's left or right ? */ char col; /* node color (CRB_RED or CRB_BLACK) */ struct rbtree * tree; /* the tree that owns this node */ void * key; /* the key of the node */ } ; #define CRB_L 0 /* left node */ #define CRB_R 2 /* right node */ #define CRB_P 1 /* parent node */ #define CRB_N 3 /* Used to denote an exact node when given a (p,dir) pair */ #define CRB_RED 0 #define CRB_BLACK 1 /* Red-Black tree and root node */ struct rbtree { cmp_f cmp; /* Comparison function for the tree */ struct rbnode root; /* Root of the tree. */ } ; #define rb_left p[CRB_L] #define rb_right p[CRB_R] #define rb_par p[CRB_P] #define rb_root root.p[CRB_P] #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define PTRDECL static #define CAT_RB_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #define PTRDECL #endif /* CAT_USE_INLINE */ /* ----- Main Functions ------ */ /* Initialize a Red-Black tree. 'cmp' is the function to compare nodes with. */ DECL void rb_init(struct rbtree *t, cmp_f cmp); /* Initialize a node in a Red-Black tree. 'k' is the node's key. */ DECL void rb_ninit(struct rbnode *n, void *k); /* * Find a node in an Red-Black 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 = rb_lkup(); then one can call * rb_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 rbnode * rb_lkup(struct rbtree *t, const void *key, int *dir); /* * Insert a new node 'n' into a Red-Black tree 't' with 'loc' as the parent, * and dir indicating which pointer in 'loc' will point to 'n'. See rb_lkup() * for how to find the correct 'loc' and 'dir' values. */ DECL struct rbnode * rb_ins(struct rbtree *t, struct rbnode *node, struct rbnode *loc, int dir); /* Remove a node from a Red-Black tree */ DECL void rb_rem(struct rbnode *node); /* Apply 'func' to every node in 't' passing 'ctx' as state to func */ DECL void rb_apply(struct rbtree *t, apply_f func, void * ctx); /* Returns non-zero if 't' is empty or 0 if 't' is non-empty */ DECL int rb_isempty(struct rbtree *t); /* Return the root node of the 't' or NULL if the tree is empty. */ DECL struct rbnode * rb_getroot(struct rbtree *t); /* Return a pointer to the minimum node in 't' or NULL if the tree is empty */ DECL struct rbnode * rb_getmin(struct rbtree *t); /* Return a pointer to the maximum node in 't' or NULL if the tree is empty */ DECL struct rbnode * rb_getmax(struct rbtree *t); /* ----- Auxiliary (helper) functions (don't use) ----- */ DECL void rb_findloc(struct rbtree *t, const void *key, struct rbnode **p, int *dir); DECL void rb_ins_at(struct rbtree *t, struct rbnode *node, struct rbnode *par, int dir); DECL void rb_fix(struct rbnode *par, struct rbnode *cld, int dir); DECL void rb_rleft(struct rbnode *n); DECL void rb_rright(struct rbnode *n); /* ------ Implementation ----- */ #if defined(CAT_RB_DO_DECL) && CAT_RB_DO_DECL DECL void rb_init(struct rbtree *t, cmp_f cmp) { abort_unless(t); abort_unless(cmp); t->cmp = *cmp; rb_ninit(&t->root, NULL); t->root.pdir = CRB_P; } DECL void rb_ninit(struct rbnode *n, void *k) { abort_unless(n); n->p[0] = n->p[1] = n->p[2] = NULL; n->pdir = 0; n->col = CRB_RED; n->key = k; } DECL struct rbnode *rb_lkup(struct rbtree *t, const void *key, int *rdir) { struct rbnode *p; int dir; abort_unless(t); rb_findloc(t, key, &p, &dir); if ( rdir ) { *rdir = dir; return p; } else { if ( dir == CRB_N ) return p; else return NULL; } } DECL struct rbnode *rb_ins(struct rbtree *t, struct rbnode *node, struct rbnode *loc, int atdir) { struct rbnode *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 == CRB_L) || (dir == CRB_R) || ((dir == CRB_P) && (p == &t->root))); } else { rb_findloc(t, key, &p, &dir); } if ( dir == CRB_N ) { rb_fix(node, p->p[CRB_L], CRB_L); rb_fix(node, p->p[CRB_R], CRB_R); rb_fix(p->p[CRB_P], node, p->pdir); node->col = p->col; node->tree = t; p->tree = NULL; p->col = CRB_RED; rb_ninit(p, p->key); return p; } else { rb_ins_at(t, node, p, dir); node->tree = t; return NULL; } } /* currently an inorder traversal: we could add an arg to change this */ DECL void rb_apply(struct rbtree *t, apply_f func, void * ctx) { struct rbnode *trav; int dir = CRB_P; abort_unless(t); abort_unless(func); trav = t->rb_root; if ( ! trav ) return; do { switch(dir) { case CRB_P: if ( trav->p[CRB_L] ) trav = trav->p[CRB_L]; /* dir stays the same */ else if ( trav->p[CRB_R] ) trav = trav->p[CRB_R]; /* dir stays the same */ else { func(trav, ctx); dir = trav->pdir; trav = trav->p[CRB_P]; } break; case CRB_L: if ( trav->p[CRB_R] ) { dir = CRB_P; trav = trav->p[CRB_R]; /* dir stays the same */ } else { func(trav, ctx); dir = trav->pdir; trav = trav->p[CRB_P]; } break; case CRB_R: func(trav, ctx); dir = trav->pdir; trav = trav->p[CRB_P]; break; } } while ( trav != &t->root ); } DECL void rb_findloc(struct rbtree *t, const void *key, struct rbnode **pn, int *pd) { struct rbnode *tmp, *par; int dir = CRB_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 = CRB_L; else if ( dir > 0 ) dir = CRB_R; else { *pn = par; *pd = CRB_N; return; } } *pn = par; *pd = dir; } #define COL(node) ((node) ? (node)->col : CRB_BLACK) DECL void rb_ins_at(struct rbtree *t, struct rbnode *node, struct rbnode *par, int dir) { struct rbnode *gp, *unc, *tmp; abort_unless(t); abort_unless(node); abort_unless(par); abort_unless(dir >= CRB_L && dir <= CRB_R); node->col = CRB_RED; rb_fix(par, node, dir); while ( node != t->rb_root && (par = node->p[CRB_P])->col == CRB_RED ) { if ( par->pdir == CRB_L ) { gp = par->p[CRB_P]; unc = gp->p[CRB_R]; if ( COL(unc) == CRB_RED ) { par->col = CRB_BLACK; unc->col = CRB_BLACK; gp->col = CRB_RED; node = gp; } else { if ( node->pdir == CRB_R ) { tmp = node; node = par; par = tmp; rb_rleft(node); } par->col = CRB_BLACK; gp->col = CRB_RED; rb_rright(gp); } } else { gp = par->p[CRB_P]; unc = gp->p[CRB_L]; if ( COL(unc) == CRB_RED ) { par->col = CRB_BLACK; unc->col = CRB_BLACK; gp->col = CRB_RED; node = gp; } else { if ( node->pdir == CRB_L ) { tmp = node; node = par; par = tmp; rb_rright(node); } par->col = CRB_BLACK; gp->col = CRB_RED; rb_rleft(gp); } } } t->rb_root->col = CRB_BLACK; } DECL struct rbnode *rb_findrep(struct rbnode *node) { struct rbnode *tmp; abort_unless(node); tmp = node->p[CRB_L]; if ( ! tmp ) return node->p[CRB_R]; else { while ( tmp->p[CRB_R] ) tmp = tmp->p[CRB_R]; } return tmp; } DECL void rb_rem(struct rbnode *node) { struct rbnode *tmp, *par; int cdir, oldc; struct rbtree *t; abort_unless(node); t = node->tree; tmp = rb_findrep(node); if ( ! tmp ) { par = node->p[CRB_P]; cdir = node->pdir; rb_fix(par, NULL, cdir); oldc = node->col; } else if ( tmp == node->p[CRB_L] || tmp == node->p[CRB_R] ) { par = tmp; if ( tmp == node->p[CRB_L] ) { rb_fix(tmp, node->p[CRB_R], CRB_R); cdir = CRB_L; } else cdir = CRB_R; rb_fix(node->p[CRB_P], tmp, node->pdir); oldc = tmp->col; tmp->col = node->col; } else { cdir = tmp->pdir; par = tmp->p[CRB_P]; rb_fix(par, tmp->p[CRB_L], cdir); oldc = tmp->col; tmp->col = node->col; rb_fix(tmp, node->p[CRB_L], CRB_L); rb_fix(tmp, node->p[CRB_R], CRB_R); rb_fix(node->p[CRB_P], tmp, node->pdir); } rb_ninit(node, node->key); if ( oldc == CRB_RED ) return; while ( cdir != CRB_P && COL(par->p[cdir]) == CRB_BLACK ) { if ( cdir == CRB_L ) { tmp = par->p[CRB_R]; if ( tmp->col == CRB_RED ) { tmp->col = CRB_BLACK; par->col = CRB_RED; rb_rleft(par); tmp = par->p[CRB_R]; } if ( COL(tmp->p[CRB_L]) == CRB_BLACK && COL(tmp->p[CRB_R]) == CRB_BLACK ) { tmp->col = CRB_RED; cdir = par->pdir; par = par->p[CRB_P]; } else { if ( COL(tmp->p[CRB_R]) == CRB_BLACK ) { tmp->p[CRB_L]->col = CRB_BLACK; tmp->col = CRB_RED; rb_rright(tmp); tmp = par->p[CRB_R]; } tmp->col = par->col; par->col = CRB_BLACK; tmp->p[CRB_R]->col = CRB_BLACK; rb_rleft(par); par = &t->root; cdir = CRB_P; } } else { tmp = par->p[CRB_L]; if ( tmp->col == CRB_RED ) { tmp->col = CRB_BLACK; par->col = CRB_RED; rb_rright(par); tmp = par->p[CRB_L]; } if ( COL(tmp->p[CRB_L]) == CRB_BLACK && COL(tmp->p[CRB_R]) == CRB_BLACK ) { tmp->col = CRB_RED; cdir = par->pdir; par = par->p[CRB_P]; } else { if ( COL(tmp->p[CRB_L]) == CRB_BLACK ) { tmp->p[CRB_R]->col = CRB_BLACK; tmp->col = CRB_RED; rb_rleft(tmp); tmp = par->p[CRB_L]; } tmp->col = par->col; par->col = CRB_BLACK; tmp->p[CRB_L]->col = CRB_BLACK; rb_rright(par); par = &t->root; cdir = CRB_P; } } } if ( par->p[cdir] ) par->p[cdir]->col = CRB_BLACK; } #undef COL DECL int rb_isempty(struct rbtree *t) { abort_unless(t); return t->rb_root == NULL; } DECL struct rbnode * rb_getroot(struct rbtree *t) { abort_unless(t); return t->rb_root; } DECL struct rbnode * rb_getmin(struct rbtree *t) { struct rbnode *node; abort_unless(t); node = t->rb_root; if ( node != NULL ) { while ( node->p[CRB_L] != NULL ) node = node->p[CRB_L]; } return node; } DECL struct rbnode * rb_getmax(struct rbtree *t) { struct rbnode *node; abort_unless(t); node = t->rb_root; if ( node != NULL ) { while ( node->p[CRB_R] != NULL ) node = node->p[CRB_R]; } return node; } DECL void rb_fix(struct rbnode *par, struct rbnode *cld, int dir) { abort_unless(par); abort_unless(dir >= CRB_L && dir <= CRB_R); par->p[dir] = cld; if ( cld ) { cld->pdir = dir; cld->p[CRB_P] = par; } } DECL void rb_rleft(struct rbnode *n) { struct rbnode *c; abort_unless(n); c = n->p[CRB_R]; abort_unless(c); rb_fix(n, c->p[CRB_L], CRB_R); rb_fix(n->p[CRB_P], c, n->pdir); rb_fix(c, n, CRB_L); } DECL void rb_rright(struct rbnode *n) { struct rbnode *c; abort_unless(n); c = n->p[CRB_L]; abort_unless(c); rb_fix(n, c->p[CRB_R], CRB_L); rb_fix(n->p[CRB_P], c, n->pdir); rb_fix(c, n, CRB_R); } #endif /* CAT_RB_DO_DECL */ #undef PTRDECL #undef DECL #undef CAT_RB_DO_DECL #endif /* __cat_rb_h */
github188/catlib
include/cat/ring.h
/* * cat/ring.h -- Ring Buffer * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_ring_h #define __cat_ring_h #include <cat/cat.h> /* N.B. First two fields match struct raw */ struct ring { size_t alloc; byte_t * data; size_t start; size_t len; } ; #define ring_avail(r) ((r)->alloc - (r)->len) void ring_init(struct ring *r, void *data, size_t len); void ring_reset(struct ring *r); size_t ring_put(struct ring *r, char *in, size_t len, int overwrite); size_t ring_get(struct ring *r, char *out, size_t len); size_t ring_last(struct ring *r); #endif /* __cat_ring_h */
github188/catlib
include/cat/archops.h
/* * include/cat/archops.h -- Operations accelerated on native platform * * Include bitops.h to get these functions. * * by <NAME> * * Copyright 2008-2015 -- See accompanying license * */ #ifndef __cat_archops_h #define __cat_archops_h #include <cat/cat.h> extern char num_bits_array[]; extern char num_leading_zeros_array[]; #define nbits8(x) (num_bits_array[(uchar)(x) & 0xff]) #define nlz8(x) (num_leading_zeros_array[(uchar)(x) & 0xff]) #if CAT_USE_INLINE #define INLINE inline #else /* CAT_USE_INLINE */ #define INLINE #endif /* CAT_USE_INLINE */ #define CAT_HAS_NLZ_32 0 #define CAT_HAS_NTZ_32 0 #define CAT_HAS_POP_32 0 #define CAT_HAS_NLZ_64 0 #define CAT_HAS_NTZ_64 0 #define CAT_HAS_POP_64 0 #if __i386__ && !CAT_ANSI89 #undef CAT_HAS_NLZ_32 #undef CAT_HAS_NTZ_32 #define CAT_HAS_NLZ_32 1 #define CAT_HAS_NTZ_32 1 static INLINE uint32_t ilog2_32(uint32_t x) { if ( x == 0 ) { return -1; } else { int r; asm("bsr %1, %%eax\n" "mov %%eax, %0\n" : "=r" (r) : "r" (x) : "%eax"); return r; } } static INLINE uint32_t nlz_32(uint32_t x) { if ( x == 0 ) { return 32; } else { int r; asm("bsr %1, %%eax\n" "mov %%eax, %0\n" : "=r" (r) : "r" (x) : "%eax"); return 31 - r; } } static INLINE uint32_t ntz_32(uint32_t x) { if ( x == 0 ) { return 32; } else { int r; asm("bsf %1, %%eax\n" "mov %%eax, %0\n" : "=r" (r) : "r" (x) : "%eax"); return r; } } #else /* more architectures here as needed */ #endif /* --------------------- Default Definitions ---------------------- */ #if !CAT_HAS_NLZ_32 static INLINE int nlz_32(uint32_t x) { int i = 1, b, n = 0; do { b = nlz8(x >> (32 - (i << 3))); n += b; i++; } while ( b == 8 && i <= sizeof(x) ); return n; } static INLINE int ilog2_32(uint32_t x) { if ( x == 0 ) return -1; else return 31 - nlz_32(x); } #endif /* CAT_HAS_NLZ_32 */ #if !CAT_HAS_POP_32 static INLINE int pop_32(uint32_t x) { x = (x & 0x55555555) + ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F); x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF); x = x + (x >> 16); return x & 0x3F; } #endif /* !CAT_HAS_POP_32 */ #if !CAT_HAS_NTZ_32 static INLINE int ntz_32(uint32_t x) { return pop_32(~x & (x-1)); } #if CAT_HAS_POP_32 #undef CAT_HAS_NTZ_32 #define CAT_HAS_NTZ_32 1 #endif /* CAT_HAS_POP_32 */ #endif /* !CAT_HAS_NTZ_32 */ /* ------ 64 Bit ------ */ #if CAT_64BIT #if !CAT_HAS_NLZ_64 #if CAT_HAS_NLZ_32 static INLINE int nlz_64(uint64_t x) { int v; if ( x == 0 ) return 64; v = nlz_32(x >> 32); if ( v == 32 ) v += nlz_32(x & 0xFFFFFFFF); return v; } #else /* CAT_HAS_NLZ_32 */ static INLINE int nlz_64(uint64_t x) { int i = 1, b, n = 0; do { b = nlz8(x >> (64 - (i << 3))); n += b; i++; } while ( b == 8 && i <= sizeof(x) ); return n; } #endif /* CAT_HAS_NLZ_32 */ static INLINE int ilog2_64(uint64_t x) { if ( x == 0 ) return -1; else return 63 - nlz_64(x); } #endif /* CAT_HAS_NLZ_64 */ #if !CAT_HAS_POP_64 #if CAT_HAS_POP_32 static INLINE int pop_64(uint64_t x) { return pop_32(x >> 32) + pop_32(x & 0xFFFFFFFF); } #else /* CAT_HAS_POP_32 */ static int INLINE pop_64(uint64_t x) { #if CAT_HAS_LONGLONG x = (x & 0x5555555555555555LL) + ((x >> 1) & 0x5555555555555555LL); x = (x & 0x3333333333333333LL) + ((x >> 2) & 0x3333333333333333LL); x = (x & 0x0F0F0F0F0F0F0F0FLL) + ((x >> 4) & 0x0F0F0F0F0F0F0F0FLL); x = (x & 0x00FF00FF00FF00FFLL) + ((x >> 8) & 0x00FF00FF00FF00FFLL); x = (x & 0x0000FFFF0000FFFFLL) + ((x >> 16) & 0x0000FFFF0000FFFFLL); #else /* CAT_HAS_LONGLONG */ x = (x & 0x5555555555555555L) + ((x >> 1) & 0x5555555555555555L); x = (x & 0x3333333333333333L) + ((x >> 2) & 0x3333333333333333L); x = (x & 0x0F0F0F0F0F0F0F0FL) + ((x >> 4) & 0x0F0F0F0F0F0F0F0FL); x = (x & 0x00FF00FF00FF00FFL) + ((x >> 8) & 0x00FF00FF00FF00FFL); x = (x & 0x0000FFFF0000FFFFL) + ((x >> 16) & 0x0000FFFF0000FFFFL); #endif /* CAT_HAS_LONGLONG */ x = x + (x >> 32); return x & 0x7F; } #endif /* CAT_HAS_POP_32 */ #endif /* CAT_HAS_POP_64 */ #if !CAT_HAS_NTZ_64 #if CAT_HAS_NTZ_32 static INLINE int ntz_64(uint64_t x) { int v; if ( x == 0 ) return 64; v = ntz_32(x & 0xFFFFFFFF); if ( v == 32 ) v += ntz_32(x >> 32); return v; } #else /* CAT_HAS_NLZ_32 */ static INLINE int ntz_64(uint64_t x) { return pop_64(~x & (x-1)); } #if CAT_HAS_POP_64 || CAT_HAS_NTZ_32 #undef CAT_HAS_NTZ_64 #define CAT_HAS_NTZ_64 1 #endif /* CAT_HAS_POP_64 */ #endif /* CAT_HAS_NTZ_32 */ #endif /* !CAT_HAS_NLZ_64 */ #endif /* CAT_HAS_LONGLONG */ #undef INLINE #endif /* __cat_archops_h */
github188/catlib
include/std/ctype.h
<gh_stars>1-10 /* * ctype.h -- C standard ctype.h library. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_ctype_h #define __cat_ctype_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 /* ctype.h */ int isalnum(int c); int isdigit(int c); int isxdigit(int c); int isspace(int c); int isprint(int c); int isalpha(int c); int islower(int c); int isupper(int c); int toupper(int c); int tolower(int c); #endif /* !CAT_USE_STDLIB */ #endif /* __cat_ctype_h */
github188/catlib
test/testdl.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <cat/dlist.h> #include <cat/stduse.h> #include <stdio.h> int main(int argc, char *argv[]) { struct dlist *node, list, *trav; struct list list2; cat_time_t ct; int arr1[] = { 10, 15, 5, 7, 12, 2, 7 }, arr2[] = { 9, 1, 6, 10, 6 }, s1 = sizeof(arr1) / sizeof(arr1[0]), s2 = sizeof(arr2) / sizeof(arr1[0]), i, j = 0; printf("Initial: "); for ( i = 0 ; i < s1 ; ++i ) printf("%u/%u ", ++j, arr1[i]); printf(" | "); for ( i = 0 ; i < s2 ; ++i ) printf("%u/%u ", ++j, arr2[i]); printf("\n"); j=0; dl_init(&list, tm_zero); for ( i = 0 ; i < s1 ; ++i ) { ++j; node = cdl_new(tm_lset(arr1[i], 0), int2ptr(j)); dl_ins(&list, node); } dl_first(&list, &ct); printf("The first is at %u\n", (uint)tm_sec(ct)); node = dl_deq(&list); printf("The first was %u at %u\n\n", (uint)ptr2uint(cdl_data(node)), (uint)tm_sec(node->ttl)); cdl_free(node); printf("Nodes from advance 10: "); l_init(&list2); dl_adv(&list, tm_lset(10, 0), &list2); while ( ! l_isempty(&list2) ) { trav = container(l_head(&list2), struct dlist, entry); printf("%u/%u ", (uint)ptr2uint(cdl_data(trav)), (uint)tm_sec(trav->ttl)); l_rem(&trav->entry); cdl_free(trav); } printf("\n\n"); for ( i = 0 ; i < s2 ; ++i ) { ++j; node = cdl_new(tm_lset(arr2[i], 0), int2ptr(j)); dl_ins(&list, node); } printf("After inserting arr2 array is :\n\t"); while ( node = dl_deq(&list) ) { printf("%u/", (uint)ptr2uint(cdl_data(node))); printf("%u ", (uint)tm_sec(node->ttl)); cdl_free(node); } printf("\n"); return 0; }
github188/catlib
include/cat/shell.h
<gh_stars>1-10 /* * shell.h -- Dumb program shell. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __shell_h #define __shell_h #include <cat/cat.h> #include <cat/mem.h> #define CAT_MAX_CMD_ARGS 32 #define CAT_MAX_VARS 32 #define CAT_MAX_VARNLEN 32 struct shell_env; enum { SVT_NIL = 0, SVT_INT, SVT_UINT, SVT_DOUBLE, SVT_STRING, SVT_PTR }; struct shell_value { int sval_type; attrib_t sval_val; struct memmgr * sval_mm; free_f sval_free; }; #define sval_int sval_val.int_val #define sval_uint sval_val.uint_val #define sval_dbl sval_val.dbl_val #define sval_str sval_val.ptr_val #define sval_ptr sval_val.ptr_val typedef int (*shell_cmd_f)(struct shell_env *env, int nargs, char *args[], struct shell_value *rv); struct shell_cmd_entry { char * cmd_name; shell_cmd_f cmd_func; }; struct shell_var { char sv_name[CAT_MAX_VARNLEN]; struct shell_value sv_value; }; struct shell_env { struct shell_cmd_entry *se_cmds; uint se_ncmds; struct shell_var se_vars[CAT_MAX_VARS]; void * se_ctx; }; #define DECLARE_SHELL_ENV(name, cmdarray) \ struct shell_env name = { cmdarray, \ sizeof(cmdarray)/sizeof(struct shell_cmd_entry),\ { 0 }, NULL } void shell_env_init(struct shell_env *env, struct shell_cmd_entry *ents, unsigned nents, void *ctx); int shell_parse(char *str, char **retvar, char *args[CAT_MAX_CMD_ARGS]); int shell_run(struct shell_env *env, char *cmdstr); int shell_is_var(const char *str); struct shell_var *shell_find_var(struct shell_env *env, const char *str); void shell_free_var(struct shell_var *sv); int shell_arg2int(struct shell_env *env, const char *str, int *rv); int shell_arg2uint(struct shell_env *env, const char *str, uint *rv); int shell_arg2dbl(struct shell_env *env, const char *str, double *rv); int shell_arg2str(struct shell_env *env, char *str, char **rv); int shell_arg2ptr(struct shell_env *env, char *str, void **rv); #endif /* __shell_h */
github188/catlib
test/markov2.c
/* * by <NAME> * * Copyright 2003-2015 -- See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> #include <cat/grow.h> #include <cat/hash.h> #include <cat/list.h> #include <cat/err.h> #include <sys/time.h> #include <cat/stduse.h> #include <cat/cds.h> #include <stdio.h> #include <string.h> #define NPREF 2 #define NONWORD "\n" #define I2D(_x) int2ptr((_x) + 1) #define D2I(_x) (ptr2int(_x) - 1) #define END -1 #define MAXGEN 10000 #define HTSIZ 4096 #define MAXWORD 80 #define STR(x) ((char *)&Strings.data[x]) struct chtab *Prefix_tbl; struct chtab *Word_tbl; struct raw Strings = { 0, NULL }; void add(int prefixes[NPREF], int word) { struct hnode *node; struct clist *list; unsigned hash; struct raw key; key.data = (byte_t*)prefixes; key.len = sizeof(int) * NPREF; list = cht_get(Prefix_tbl, &key); if ( list == NULL ) { list = cl_new(NULL, 1); cht_put(Prefix_tbl, &key, list); } cl_enq(list, int2ptr(word)); memmove(prefixes, prefixes + 1, (NPREF-1) * sizeof(int)); prefixes[NPREF-1] = word; } void generate(void) { int i, j, n, word; struct hnode *node; struct clist *list; struct clist_node *t, *h; int prefixes[NPREF]; struct raw key; key.data = (byte_t*)prefixes; key.len = sizeof(prefixes); for ( i = 0 ; i < NPREF ; ++i ) prefixes[i] = i * sizeof(NONWORD); for ( i = 0 ; i < MAXGEN ; ++i ) { list = cht_get(Prefix_tbl, &key); abort_unless(list != NULL); h = cl_first(list); for ( n = 2, t = cl_next(h) ; t != cl_end(list) ; t = cl_next(t), ++n ) if ( (random() % n) == 0 ) h = t; word = ptr2int(h->data); if ( word == END ) return; memmove(prefixes, prefixes + 1, (NPREF-1) * sizeof(int)); prefixes[NPREF-1] = word; printf("%s\n", STR(word)); } } int main(int argc, char **argv) { int i, l, idx; int rv; unsigned long cur; char fmt[32]; struct timeval tv; int prefixes[NPREF]; void *d; gettimeofday(&tv, NULL); srandom(tv.tv_usec); Prefix_tbl = cht_new(HTSIZ, &cht_std_attr_rkey, NULL, 1); Word_tbl = cht_new(HTSIZ, &cht_std_attr_skey, NULL, 1); if (grow(&Strings.data, &Strings.len, NPREF * sizeof(NONWORD) + MAXWORD) < 0) errsys("Out of memory\n"); for ( i = 0 ; i < NPREF ; ++i ) { prefixes[i] = sizeof(NONWORD) * i; sprintf(STR(sizeof(NONWORD) * i), NONWORD); } cur = NPREF * sizeof(NONWORD); sprintf(fmt, "%%%ds", MAXWORD - 1); while ( scanf(fmt, STR(cur)) > 0 ) { d = cht_get(Word_tbl, STR(cur)); if ( d == NULL ) { cht_put(Word_tbl, STR(cur), I2D(cur)); l = strlen(STR(cur)) + 1; rv = grow(&Strings.data, &Strings.len, cur + l + MAXWORD); if ( rv < 0 ) errsys("Could not grow string buffer:"); idx = cur; cur += l; } else { idx = D2I(d); } add(prefixes, idx); } add(prefixes, END); cht_free(Word_tbl); printf("Generating...\n"); generate(); cht_free(Prefix_tbl); return 0; }
github188/catlib
src/crc.c
/* * crc.c -- Cyclic Redundancy Check implementation * * by <NAME> * * Copyright 2015 See accompanying license * */ #include <cat/crc.h> static byte_t rev8(byte_t x) { x = ((x >> 4) & 0x0F) | (x << 4); x = ((x >> 2) & 0x33) | ((x << 2) & 0xCC); x = ((x >> 1) & 0x55) | ((x << 1) & 0xAA); return x; } static ulong rev32(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; } void crc32t_be_init(struct crc32tab *tab, ulong poly) { int i, j; ulong r; for ( i = 0; i < 256; ++i ) { r = i << 24; for ( j = 0; j < 8; ++j ) { if ( (r >> 31) & 1 ) r = (r << 1) ^ poly; else r = (r << 1); } tab->resid[i] = r & 0xFFFFFFFF; } } ulong crc32t_be(const struct crc32tab *tab, const void *voidp, size_t size, ulong crc) { const byte_t *p; for ( p = voidp ; size > 0 ; --size, ++p ) crc = tab->resid[(*p ^ (crc >> 24)) & 0xFF] ^ (crc << 8); return crc & 0xFFFFFFFF; } void crc32t_le_init(struct crc32tab *tab, ulong poly) { int i, j; ulong r; for ( i = 0; i < 256; ++i ) { r = rev8(i) << 24; for ( j = 0; j < 8; ++j ) { if ( (r >> 31) & 1 ) r = (r << 1) ^ poly; else r = (r << 1); } tab->resid[i] = rev32(r & 0xFFFFFFFF); } } ulong crc32t_le(const struct crc32tab *tab, const void *voidp, size_t size, ulong crc) { const byte_t *p; for ( p = voidp ; size > 0 ; --size, ++p ) crc = tab->resid[(*p ^ crc) & 0xFF] ^ (crc >> 8); return crc; } static struct crc32tab _crc32_table; static int _crc32_table_initialized = 0; void crc32_init(void) { crc32t_le_init(&_crc32_table, CAT_CRC32_POLY); _crc32_table_initialized = 1; } ulong crc32_start(void) { if (!_crc32_table_initialized) crc32_init(); return 0xFFFFFFFF; } ulong crc32_step(const void *p, size_t size, ulong crc) { return crc32t_le(&_crc32_table, p, size, crc); } ulong crc32_finish(ulong crc) { return crc ^ 0xFFFFFFFF; }
github188/catlib
attic/dict.h
/* * cat/dict.h -- Abstract dictionary interface * * by <NAME> * * Copyright 2005 See accompanying license * */ #ifndef __cat_dict_h #define __cat_dict_h #include <cat/cat.h> #include <cat/aux.h> /* dictionary types */ #include <cat/list.h> #include <cat/avl.h> #include <cat/hash.h> #include <cat/rbtree.h> #define CAT_ST_STR 0 #define CAT_ST_RAW 1 #define CAT_ST_PTR 2 #define CAT_ST_NUM 3 #define CAT_ST_RAWCPY 4 #define CAT_ST_OTHER 5 #define CAT_DT_LIST 0 #define CAT_DT_HASHTABLE 1 #define CAT_DT_AVLTREE 2 #define CAT_DT_RBTREE 3 struct dictaux { cmp_f cmp; hash_f hash; void * hctx; void (*dinit)(void *d, void * void (*ninit) }; struct dict { int storetype; int dicttype; void * (*nnew)(void *k, void *d, void *ctx); void * (*nfree)(void *n, void *ctx); void * nctx; struct dictaux * aux; }; struct dict * d_new(int dtype, int stype, struct dictsys *ds); void d_free(struct dict *d); void * d_get(struct dict *d, void *key); void * d_put(struct dict *d, void *key, void *data); void * d_clr(struct dict *d, void *key); /* helpers */ struct rbnode *rb_snalloc(void *key, void *data, void *ctx); void rb_snfree(struct rbnode *n, void *ctx); #endif /* __cat_dict_h */
github188/catlib
src/optparse.c
/* * optparse.c -- Command line option parsing * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/optparse.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> int optparse_reset(struct clopt_parser *clp, int argc, char *argv[]) { size_t n; struct clopt *opt; if ( clp == NULL || argc < 1 || argv == NULL ) return -1; for ( n = 0; n < clp->num ; ++n ) { opt = &clp->options[n]; if ( opt->type < CLOPT_NOARG || opt->type > CLOPT_DOUBLE ) return -1; if ( !isalnum(opt->ch) && opt->str == NULL ) return -1; } clp->argc = argc; clp->argv = argv; clp->vidx = 1; clp->non_opt = 1; clp->chptr = NULL; return 0; } static void movedown(char *argv[], int lo, int hi) { char *hold = argv[hi]; if ( lo < hi ) { memmove(&argv[lo + 1], &argv[lo], (hi - lo) * sizeof(char *)); argv[lo] = hold; } } static int read_arg(struct clopt *opt, const char *arg) { char *cp; switch(opt->type) { case CLOPT_STRING: opt->val.str_val = (char *)arg; break; case CLOPT_INT: opt->val.int_val = strtol(arg, &cp, 0); if ( cp == arg || *cp != '\0' || *arg == '\0' ) return -1; break; case CLOPT_UINT: opt->val.uint_val = strtoul(arg, &cp, 0); if ( cp == arg || *cp != '\0' || *arg == '\0' ) return -1; break; case CLOPT_DOUBLE: opt->val.dbl_val = strtod(arg, &cp); if ( cp == arg || *cp != '\0' || *arg == '\0' ) return -1; break; default: abort_unless(0); } return 0; } char *clopt_name(struct clopt *opt, char *buf, size_t buflen) { int n = 0; if ( buflen < 1 ) return NULL; *buf = '\0'; if ( isalnum(opt->ch) ) { if ( buflen < 3 ) return buf; buf[0] = '-'; buf[1] = opt->ch; if ( opt->str == NULL ) { buf[2] = '\0'; return buf; } else { buf[2] = ','; n = 3; } } if ( opt->str != NULL ) snprintf(buf + n, buflen - n, "%s", opt->str); return buf; } static int parse_long_opt(struct clopt_parser *clp, struct clopt **optp) { int i; const char *cp = clp->argv[clp->vidx], *end; size_t elen; struct clopt *opt = NULL; char onamestr[64]; end = strchr(cp, '='); if ( end != NULL ) elen = end - cp; else elen = strlen(cp); for ( i = 0; i < clp->num; ++i ) { opt = &clp->options[i]; if ( opt->str != NULL && strncmp(opt->str, cp, elen) == 0 ) break; } if ( opt == NULL ) { *optp = NULL; clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Unknown option: %s", cp); return CLORET_UNKOPT; } *optp = opt; if ( opt->type != CLOPT_NOARG ) { if ( end == NULL ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "No parameter for option %s", clopt_name(opt, onamestr, sizeof(onamestr))); return CLORET_NOPARAM; } if ( read_arg(opt, end + 1) < 0 ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Bad parameter for option %s: %s", clopt_name(opt, onamestr, sizeof(onamestr)), end + 1); opt->val.str_val = (char *)end + 1; return CLORET_BADPARAM; } } else if ( end != NULL ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Unwanted parameter for option %s: %s", clopt_name(opt, onamestr, sizeof(onamestr)), end + 1); opt->val.str_val = (char *)end + 1; return CLORET_BADPARAM; } movedown(clp->argv, clp->non_opt++, clp->vidx++); return 0; } static int parse_short_opts(struct clopt_parser *clp, struct clopt **optp) { int i; struct clopt *opt = NULL; const char *cp = clp->chptr; char onamestr[64]; for ( i = 0; i < clp->num ; ++i ) { opt = &clp->options[i]; if ( isalnum(opt->ch) && opt->ch == *cp ) break; } if ( i >= clp->num ) { *optp = NULL; clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Unknown option: -%c", *cp); return CLORET_UNKOPT; } *optp = opt; if ( opt->type != CLOPT_NOARG ) { if ( cp[1] != '\0' ) { /* argument is remainder of the string */ if ( read_arg(opt, cp + 1) < 0 ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Bad parameter for option %s: %s", clopt_name(opt, onamestr, sizeof(onamestr)), cp + 1); opt->val.str_val = (char *)cp + 1; return CLORET_BADPARAM; } } else { if ( clp->vidx >= clp->argc - 1 ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "No parameter for option %s", clopt_name(opt, onamestr, sizeof(onamestr))); return CLORET_NOPARAM; } if ( read_arg(opt, clp->argv[clp->vidx+1]) < 0 ) { clp->argc = -1; snprintf(clp->errbuf, sizeof(clp->errbuf), "Bad parameter for option %s: %s", clopt_name(opt, onamestr, sizeof(onamestr)), clp->argv[clp->vidx+1]); opt->val.str_val = clp->argv[clp->vidx+1]; return CLORET_BADPARAM; } movedown(clp->argv, clp->non_opt++, clp->vidx++); } movedown(clp->argv, clp->non_opt++, clp->vidx++); clp->chptr = NULL; } else { if ( *++clp->chptr == '\0' ) { movedown(clp->argv, clp->non_opt++, clp->vidx++); clp->chptr = NULL; } } return 0; } int optparse_next(struct clopt_parser *clp, struct clopt **optp) { int i; char **argv; abort_unless(clp); abort_unless(optp); if ( clp->argc <= 0 ) { snprintf(clp->errbuf, sizeof(clp->errbuf), "Must call optparse_reset() upon error return code"); return CLORET_RESET; } if ( clp->vidx < 0 ) return clp->non_opt; if ( clp->chptr != NULL ) return parse_short_opts(clp, optp); i = clp->vidx; argv = clp->argv; while ( (i < clp->argc) && ((argv[i][0] != '-')||(argv[i][1] == '\0')) ) i = ++clp->vidx; if ( i >= clp->argc ) return clp->non_opt; if ( strcmp(argv[i], "--") == 0 ) { movedown(clp->argv, clp->non_opt++, clp->vidx); clp->vidx = -1; return clp->non_opt; } if ( strncmp(argv[i], "--", 2) == 0 ) { return parse_long_opt(clp, optp); } else { clp->chptr = &argv[i][1]; return parse_short_opts(clp, optp); } } static void adj_str(char **cp, size_t *remlen, size_t *linelen, size_t added) { if ( added < *remlen ) { *remlen -= added; (*cp) += added; } else { (*cp) += *remlen; added = *remlen; *remlen = 0; } *linelen += added; } void optparse_print(struct clopt_parser *clp, char *str, size_t ssize) { int i; char *cp = str; char pad[80]; size_t fsz, lsz; struct clopt *opt; abort_unless(ssize > 1); if ( ssize == 0 ) { return; } else if ( ssize == 1 ) { *str = '\0'; return; } ssize -= 1; for ( i = 0; i < clp->num; ++i ) { opt = &clp->options[i]; if ( !isalnum(opt->ch) && opt->str == NULL ) continue; lsz = 0; if ( isalnum(opt->ch) ) { fsz = (size_t)snprintf(cp, ssize, " -%c%s", opt->ch, (opt->str == NULL) ? "" : ", "); adj_str(&cp, &ssize, &lsz, fsz); } else { fsz = (size_t)snprintf(cp, ssize, " "); adj_str(&cp, &ssize, &lsz, fsz); } if ( opt->str != NULL ) { fsz = (size_t)snprintf(cp, ssize, "%s", opt->str); adj_str(&cp, &ssize, &lsz, fsz); } if ( opt->argnam != NULL ) { fsz = (size_t)snprintf(cp, ssize, " %s", opt->argnam); adj_str(&cp, &ssize, &lsz, fsz); } if ( lsz < 40 ) { memset(pad, ' ', 40-lsz); pad[40-lsz] = '\0'; fsz = (size_t)snprintf(cp, ssize, "%s", pad); adj_str(&cp, &ssize, &lsz, fsz); } else { fsz = (size_t)snprintf(cp, ssize, " "); adj_str(&cp, &ssize, &lsz, fsz); } fsz = (size_t)snprintf(cp, ssize, "%s\n", opt->desc); adj_str(&cp, &ssize, &lsz, fsz); } }
github188/catlib
src/avl.c
/* * cat/avl.c -- AVL tree implementation * * by <NAME> * * Copyright 2003 - 2012 See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_AVL_DO_DECL #define CAT_USE_INLINE 0 #define CAT_AVL_DO_DECL 1 #include <cat/avl.h>
github188/catlib
include/cat/inport.h
/* * inport.c -- generic input API. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_inport_h #define __cat_inport_h #include <cat/cat.h> struct inport; /* len must be >= 0 or returns error */ /* returns: -1 on error, 0 on EOF, > 0 == # of bytes */ typedef int (*inp_read_f)(struct inport *in, void *buf, int len); typedef int (*inp_close_f)(struct inport *in); struct inport { inp_read_f read; inp_close_f close; }; /* len must be less than INT_MAX or returns error */ /* returns: -1 on err, 0 on EOF, > 0 == # of bytes */ int inp_read(struct inport *in, void *buf, int len); /* returns -1 on both end of file or error, otherwise char */ int inp_getc(struct inport *in); /* no return */ int inp_close(struct inport *in); struct cstr_inport { struct inport in; const char * str; size_t slen; size_t off; }; void csinp_init(struct cstr_inport *csi, const char *s); void csinp_reset(struct cstr_inport *csi); void csinp_clear(struct cstr_inport *csi); void ninp_init(struct inport *in); extern struct inport null_inport; #endif /* __cat_inport_h */
github188/catlib
include/cat/pool.h
/* * pool.h -- fixed size element memory pools. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __pool_h #define __pool_h #include <cat/cat.h> #include <cat/list.h> #define IMAX ((int)(((unsigned)~0) >> 1)) typedef union { cat_align_t align; struct list list; } cat_pitem_t; struct pool { struct list items; size_t fill; size_t max; #if defined(CAT_DEBUG) && CAT_DEBUG char * base; size_t lim; #endif }; #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_POOL_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #endif /* CAT_USE_INLINE */ DECL size_t pl_isiz(size_t siz, int align); DECL void pl_init(struct pool *p, size_t siz, int align, void *mem, size_t mlen); DECL void * pl_alloc(struct pool *p); DECL void pl_free(struct pool *p, void *item); #if defined(CAT_POOL_DO_DECL) && CAT_POOL_DO_DECL DECL size_t pl_isiz(size_t siz, int align) { size_t n, alen = 0; abort_unless(siz > 0); abort_unless(align < 0 || (align < sizeof(int) * 8 - 1)); if ( align >= 0 && (align < sizeof(int) * 8 - 1) ) alen = 1 << align; if ( alen < sizeof(cat_pitem_t) ) alen = sizeof(cat_pitem_t); if ( siz < alen ) siz = alen; n = siz % alen; if ( n > 0 ) { abort_unless(siz <= IMAX - (alen - n)); siz += alen - n; } return siz; } DECL void pl_init(struct pool *p, size_t siz, int align, void *mem, size_t mlen) { size_t i, n; char *cp; struct list *lp; abort_unless(p); abort_unless(mem); abort_unless(siz > 0); abort_unless(align < 0 || (align < sizeof(int) * 8 - 1)); abort_unless(mlen > 0); siz = pl_isiz(siz, align); l_init(&p->items); n = mlen / siz; cp = mem; #if defined(CAT_DEBUG) && CAT_DEBUG p->base = mem; p->lim = mlen; #endif /* XXX This is not the appropriate test: what is? */ /* abort_unless((unsigned)cp % sizeof(cat_align_t) == 0); */ abort_unless((align < 0) || ((uint)(ptrdiff_t)cp % (1 << align) == 0)); for ( i = 0 ; i < n ; ++i ) { lp = (struct list *)cp; l_ins(p->items.prev, lp); cp += siz; } p->fill = p->max = n; } DECL void * pl_alloc(struct pool *p) { struct list *lp, *prev; abort_unless(p); if ( ! p->fill ) return NULL; p->fill -= 1; prev = &p->items; lp = prev->next; abort_unless(lp && lp->next && lp->next->prev == lp); prev->next = lp->next; lp->next->prev = prev; return (char *)lp; } DECL void pl_free(struct pool *p, void *item) { struct list *lp; abort_unless(p); abort_unless(item); lp = (struct list *)item; #if defined(CAT_DEBUG) && CAT_DEBUG abort_unless((char *)item >= p->base && (char *)item < p->base+p->lim); #endif /* CAT_DEBUG */ l_ins(&p->items, lp); p->fill += 1; } #endif /* defined(CAT_POOL_DO_DECL) && CAT_POOL_DO_DECL */ #undef DECL #undef CAT_POOL_DO_DECL #endif /* __pool_h */
github188/catlib
attic/ex.c
/* * ex.c -- Exception handling via longjmp() * * by <NAME> * * Copyright 2003, See accompanying license * */ #include <cat/cat.h> #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <stdlib.h> #include <cat/ex.h> #include <cat/err.h> #if defined(CAT_USE_PTHREADS) && CAT_USE_PTHREADS #include <pthread.h> static pthread_once_t cat_exonce = PTHREAD_ONCE_INIT; static pthread_key cat_exkey; static void clrexstack(void *stack) { free(stack); } static void initex(void) { if ( pthread_key_create(&cat_exkey, clrexstack) < 0 ) errsys("pthread_key_create in initex:\n\t"); } #else /* CAT_USE_PTHREADS */ static struct ex_stack ExStack = { -1, NULL }; #endif /* CAT_USE_PTHREADS */ int ex_try(void) { struct ex_stack *esp; struct ex_ent *eep; #if defined(CAT_USE_PTHREADS) && CAT_USE_PTHREADS /* memory leak: must free the memory before this thread terminates */ pthread_once(&cat_exonce, initex()); if ( !(esp = pthread_getpsecific(cat_exkey)) ) { esp = malloc(sizeof(*esp)); if ( !esp ) err("ex_try: out of memory\n"); memset(esp, 0, sizeof(*esp)); esp->top = -1; esp->uncaught = 0; pthread_setspecific(cat_exkey, esp); } #else /* CAT_USE_PTHREADS */ esp = &ExStack; #endif /* CAT_USE_PTHREADS */ if ( esp->top == MAXEXSTK ) err( "too many nested ex_try()s! (max = %d)\n", MAXEXSTK); eep = &esp->stack[++esp->top]; eep->data = 0; return setjmp(eep->env) ? 0 : 1; } static struct ex_stack *getexstack() { struct ex_stack *esp; #if defined(CAT_USE_PTHREADS) && CAT_USE_PTHREADS if ( (esp = pthread_getspecific(cat_exkey)) ) errsys("pthread_getspecific:\n\t"); #else /* CAT_USE_PTHREADS */ esp = &ExStack; #endif /* CAT_USE_PTHREADS */ return esp; } void ex_throw(void *data) { struct ex_stack *esp; esp = getexstack(); if ( esp->top < 0 ) { if ( !esp->uncaught ) err("Uncaught exception: %s\nTerminating!\n", data); else { esp->uncaught(data); exit(-1); } } esp->stack[esp->top].data = data; longjmp(esp->stack[esp->top].env, 1); } void * ex_get(void) { struct ex_stack *esp; esp = getexstack(); if ( esp->top < 0 ) err("Attempt to obtain data when exception stack is empty!\n"); return esp->stack[esp->top].data; } void ex_end(void) { struct ex_stack *esp; esp = getexstack(); if ( esp->top < 0 ) err("Exception end with no begin! (terminating)"); esp->top--; } void ex_setu(void (*uncaught)(void *)) { struct ex_stack *esp; esp = getexstack(); esp->uncaught = uncaught; } /* * * void printandfree(void *string) * { * printf("Uncaught exception %s\n", string); * free(string); * } * * * ex_setu(printandfree); * * * if ( ex_try() ) * { * * if ( some_error ) * ex_throw(str_dup("Hello World")); * * } else { * char *exc; * exc = ex_get(); * printf("We caught an error: %s\n", exc); * free(exc); * } * ex_end(); * * ex_throw(str_dup("Another exception!\n")); * * */ #endif /* if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB */
github188/catlib
src/emit.c
/* * emit.c -- generic interface to output stream. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/emit.h> #include <limits.h> #include <string.h> int emit_char(struct emitter *em, char ch) { abort_unless(em && em->emit_func); if ( em->emit_state != EMIT_OK ) return -1; return (*em->emit_func)(em, &ch, sizeof(char)); } int emit_raw(struct emitter *em, const void *buf, size_t len) { abort_unless(em && em->emit_func); if ( em->emit_state != EMIT_OK ) return -1; if ( len > INT_MAX ) return -1; return (*em->emit_func)(em, buf, len); } int emit_string(struct emitter *em, const char *s) { size_t len; abort_unless(s); len = strlen(s); return emit_raw(em, s, len); } static int null_emit_func(struct emitter *em, const void *buf, size_t len) { return 0; } int init_null_emitter(struct emitter *em) { abort_unless(em); em->emit_state = EMIT_OK; em->emit_func = null_emit_func; return 0; } struct emitter null_emitter = { EMIT_OK, &null_emit_func }; static int str_emit_func(struct emitter *em, const void *buf, size_t len) { struct string_emitter *se; size_t tocopy; se = (struct string_emitter *)em; abort_unless(se->se_raw.len >= se->se_fill); tocopy = len; if ( tocopy > se->se_raw.len - se->se_fill ) tocopy = se->se_raw.len - se->se_fill; memmove(se->se_raw.data + se->se_fill, buf, tocopy); se->se_fill += tocopy; if ( se->se_raw.len == se->se_fill ) se->se_emitter.emit_state = EMIT_EOS; return 0; } void string_emitter_init(struct string_emitter *se, char *str, size_t len) { struct emitter *e; abort_unless(se); abort_unless(str && len >= 1); e = &se->se_emitter; e->emit_state = EMIT_OK; e->emit_func = str_emit_func; se->se_fill = 0; se->se_raw.data = str; se->se_raw.len = len - 1; } void string_emitter_terminate(struct string_emitter *se) { abort_unless(se && se->se_fill <= se->se_raw.len); se->se_raw.data[se->se_fill] = '\0'; se->se_emitter.emit_state = EMIT_EOS; }
github188/catlib
include/cat/pcache.h
/* * pcache.h -- dynamically resizing memory pools. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __pcache_h #define __pcache_h #include <cat/cat.h> #include <cat/mem.h> #include <cat/pool.h> #ifndef PC_DEF_SIZE #define PC_DEF_SIZE 65536 #endif /* PC_DEF_SIZE */ struct pcache { struct list avail; struct list full; struct list empty; size_t asiz; size_t pgsiz; unsigned npools; unsigned maxpools; unsigned hiwat; struct memmgr * mm; }; struct pc_pool { struct list entry; struct pcache * cache; struct pool pool; }; union pc_pool_u { cat_align_t align; struct pc_pool pool; }; void pc_init(struct pcache *pc, size_t asiz, size_t pgsiz, uint hiwat, uint maxpools, struct memmgr *mm); void pc_freeall(struct pcache *pc); void *pc_alloc(struct pcache *pc); void pc_free(void *item); void pc_addpg(struct pcache *pc, void *page, size_t size); void pc_delpg(void *page); /* Each pool item will require one of these as overhead, so it's often */ /* good to account for this when one wants to cache align pool items. */ typedef union { struct pc_pool * pool; cat_align_t align; } cat_pcpad_t; #endif /* __pcache_h */
github188/catlib
attic/mem2.h
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __mem2_h #define __mem2_h #include <cat/cat.h> #include <cat/aux.h> #include <cat/pool.h> #include <cat/pcache.h> #include <cat/hash.h> #include <cat/avl.h> #include <cat/rbtree.h> void pl_memsys(struct pool *p, struct memsys *m); void pc_memsys(struct pcache *p, struct memsys *m); struct nfactory { union { struct hashsys hsys; struct avlsys asys; struct rbsys rbsys; } nf_u; struct memsys * nf_msys; int nf_klen; }; #define nf_hsys nf_u.hsys #define nf_asys nf_u.asys #define nf_rbsys nf_u.rbsys void nf_initht(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp, hash_f hash, void *hctx); void nf_initavl(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp); void nf_initrb(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp); #if 0 Example: struct pcache PagePC; struct memsys PageMC, HNodeMC, ANodeMC, RBNodeMC; struct pcache HNodePC, ANodePC, RBNodePC; struct nfactory HNodeFac, ANodeFac, RBNodeFac; pc_init(&PagePC, 4096, 65536 + 16 * sizeof(union pc_pool_u), 8, 0, xstdmem); pc_memsys(&PagePC, &PageMC); pc_init(&HNodePC, sizeof(struct hnode)+hkeylen, 4096, 0, 0, &PageMC); pc_memsys(&HNodePC, &HNodeMC); nf_initht(&HNodeFac, hkeylen, &HNodeMC, cmp_raw, ht_rhash, NULL); pc_init(&ANodePC, sizeof(struct anode)+akeylen, 4096, 0, 0, &PageMC); pc_memsys(&ANodePC, &ANodeMC); nf_initavl(&ANodeFac, akeylen, &ANodeMC, cmp_raw); pc_init(&RBNodePC, sizeof(struct rbnode)+rbkeylen, 4096, 0, 0, &PageMC); pc_memsys(&RBNodePC, &RBNodeMC); nf_initrb(&RBNodeFac, rbkeylen, &RBNodeMC, cmp_raw); .... struct htab ConTab; ht_init(&ConTab, xmalloc(sizeof(struct list) * LEN), LEN, &HNodeFac.nf_hsys); struct rbtree Personnel; rb_init(&Personnel, &RBNodeFac); #endif /* 0 */ #endif /* __mem2_h */
github188/catlib
test/testsiphash.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2015 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <cat/hash.h> #include <cat/crypto.h> #include <cat/stduse.h> #define NUMSTR 4 #define NOPS 65536 #define NITER (128 * NOPS) void time_ht() { struct htab t; struct hnode **buckets; uint nbuckets = 128 * 1024; const char mykey[256] = "Hello world! It's a beautiful day!"; struct hnode nodes[NOPS], *node; struct ht_sh24_ctx hctx; int i, j; struct timeval start, end; double usec; uint h; buckets = emalloc(sizeof(struct hnode *) * nbuckets); ht_sh24_init(&hctx, mykey, strlen(mykey)); ht_init(&t, buckets, nbuckets, &cmp_str, &ht_sh24_shash, &hctx); for (i = 0; i < NOPS; i++) ht_ninit(&nodes[i], str_fmt_a("node%d", i)); 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 ) { 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() { time_ht(); return 0; }
github188/catlib
test/testpspawn.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <unistd.h> #include <cat/cat.h> #include <cat/pspawn.h> #include <cat/err.h> #define DBG fprintf(stderr, "DBG:%s:%d\n", __FILE__, __LINE__); extern char **environ; void test1(char *file) { struct pspawn *ps; struct ps_spec spec; struct ps_fd_entry *psfde; FILE *pin, *pout, *perr; char *t1[] = { "/bin/cat", NULL, "-", NULL }; char line[256]; int running; t1[1] = file; ps_spec_init(&spec); psfde = ps_spec_add_pipe(&spec,PSFD_IN|PSFD_STDIO|PSFD_LINEBUF); ps_fde_addfd(psfde, 0); psfde = ps_spec_add_pipe(&spec, PSFD_OUT|PSFD_STDIO|PSFD_FULLBUF); ps_fde_addfd(psfde, 1); ps_spec_keepfd(&spec, 2); /* ps_fde_addfd(psfde, 2); */ ps = ps_launch(t1, NULL, &spec); if (ps == NULL) errsys("error launching /bin/cat:\n"); printf("1: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); pin = ps_get_locfile(ps, 0); if (pin == NULL) err("Couldn't find input file"); fputs("Hello World\n", pin); fputs("Another line\n", pin); ps_closeio(ps, 0); printf("2: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); pout = ps_get_locfile(ps, 1); if (pout == NULL) errsys("Can't find process output\n"); while (fgets(line, sizeof(line), pout)) printf("line> %s", line); printf("3: Process %d is %s\n", ps->cpid, (running = ps_running(ps)) ? "running" : "not running"); fflush(stdout); if (running) { sleep(1); printf("4: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); } printf("cleanup return code = %d\n", ps_cleanup(ps, 1)); printf("Done 1\n"); } void test2(char *file) { struct pspawn *ps; FILE *pin, *pout, *perr; char line[256]; int running; ps = ps_spawn("el01", environ, "/bin/cat", file, "-", NULL); if (ps == NULL) errsys("error2 launching /bin/cat:\n"); printf("4: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); pin = ps_get_locfile(ps, 0); if (pin == NULL) err("Couldn't find input file"); fputs("Hello World 2\n", pin); fputs("Another line 2\n", pin); ps_closeio(ps, 0); printf("5: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); pout = ps_get_locfile(ps, 1); if (pout == NULL) errsys("Can't find process output\n"); while (fgets(line, sizeof(line), pout)) printf("line> %s", line); printf("6: Process %d is %s\n", ps->cpid, (running = ps_running(ps)) ? "running" : "not running"); fflush(stdout); if (running) { sleep(1); printf("6: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); } printf("cleanup return code = %d\n", ps_cleanup(ps, 1)); printf("Done 2\n"); } void test3() { struct pspawn *ps; FILE *pin, *pout, *perr; char line[256]; int running; if ((ps = ps_spawn("el01+2", environ, "/usr/bin/env", NULL)) == NULL) errsys("error2 launching /bin/cat:\n"); printf("7: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); if ((pout = ps_get_locfile(ps, 1)) == NULL) errsys("Can't find process output\n"); while (fgets(line, sizeof(line), pout)) printf("line> %s", line); printf("8: Process %d is %s\n", ps->cpid, (running = ps_running(ps)) ? "running" : "not running"); fflush(stdout); if (running) { sleep(1); printf("9: Process %d is %s\n", ps->cpid, ps_running(ps) ? "running" : "not running"); fflush(stdout); } printf("cleanup return code = %d\n", ps_cleanup(ps, 1)); printf("Done 3\n"); } int main(int argc, char *argv[]) { if (argc < 2) err("usage: %s file\n", argv[0]); ps_ignore_sigcld(); test1(argv[1]); test2(argv[1]); test3(); return 0; }
github188/catlib
src/sort.c
/* * sort.c -- Sorting routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/sort.h> #include <string.h> #define PTRSWAP 0 #define BULKLONG 1 #define BULKBYTE 2 #define SWAPTYPE(a, size) \ (((size) == sizeof(void *)) && \ (((byte_t *)(a) - (byte_t *)0) % sizeof(cat_align_t) == 0)) ? \ PTRSWAP : \ (((size) % sizeof(long) == 0) && \ (((byte_t *)(a) - (byte_t *)0) % sizeof(cat_align_t) == 0)) ? \ BULKLONG : \ BULKBYTE #define SWAP(a,b,type) \ switch (type) { \ case PTRSWAP: { \ void *__t = *(void **)(a); \ *(void **)(a) = *(void **)(b); \ *(void **)(b) = __t; \ } \ break; \ case BULKLONG: { \ register size_t __n = esize / sizeof(long); \ register long *__ap = (long *)(a); \ register long *__bp = (long *)(b); \ register long __t; \ do { \ __t = *__ap; \ *__ap++ = *__bp; \ *__bp++ = __t; \ } while ( --__n > 0 ); \ } \ break; \ default: { \ register size_t __n = esize; \ register byte_t *__ap = (byte_t *)(a); \ register byte_t *__bp = (byte_t *)(b); \ register byte_t __t; \ do { \ __t = *__ap; \ *__ap++ = *__bp; \ *__bp++ = __t; \ } while ( --__n > 0 ); \ } \ } static void isort_i(void *arr, const size_t nelem, const size_t esize, cmp_f cmp, int swaptype) { byte_t *start = arr, *p1, *p2, *tmp; const byte_t * const end = (byte_t *)arr + nelem * esize; for ( p1 = start + esize ; p1 < end ; p1 += esize ) { for ( p2 = p1 ; p2 > start ; p2 -= esize ) { tmp = p2 - esize; if ((*cmp)(tmp, p2) > 0) { SWAP(tmp, p2, swaptype); } else { break; } } } } void isort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp) { int type = SWAPTYPE(arr, esize); if ( arr == NULL || nelem <= 1 || esize == 0 || cmp == NULL ) return; isort_i(arr, nelem, esize, cmp, type); } static void ssort_i(void *arr, const size_t nelem, const size_t esize, cmp_f cmp, int swaptype) { byte_t *p1, *p2, *min; const byte_t * const end = (byte_t *)arr + nelem * esize; for ( p1 = arr ; p1 < end - esize ; p1 += esize ) { min = p1; for ( p2 = p1 + esize ; p2 < end ; p2 += esize ) if ((*cmp)(min, p2) > 0) min = p2; if ( min != p1 ) SWAP(p1, min, swaptype); } } void ssort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp) { int type = SWAPTYPE(arr, esize); if ( arr == NULL || nelem <= 1 || esize == 0 || cmp == NULL ) return; ssort_i(arr, nelem, esize, cmp, type); } static void reheap_down(void *arr, const size_t nelem, const size_t esize, cmp_f cmp, int swaptype, size_t pos) { int didswap; size_t cld; byte_t *ep, *cp; if ( pos >= nelem ) return; do { if ( (cld = (pos << 1) + 1) >= nelem ) break; didswap = 0; ep = (byte_t *)arr + pos * esize; /* find the max child */ cp = (byte_t *)arr + cld * esize; if ( ( cld + 1 < nelem ) && ( (*cmp)(cp + esize, cp) > 0 ) ) { ++cld; cp += esize; } if ( (*cmp)(ep, cp) < 0 ) { didswap = 1; SWAP(ep, cp, swaptype); pos = cld; } } while ( didswap ); } static void hsort_i(void *arr, size_t nelem, const size_t esize, cmp_f cmp, int swaptype) { size_t i; byte_t *ep; /* build the max heap */ i = nelem >> 1; do { reheap_down(arr, nelem, esize, cmp, swaptype, i); } while ( i-- > 0 ); while ( nelem > 1 ) { --nelem; ep = (byte_t *)arr + nelem * esize; SWAP((byte_t*)arr, ep, swaptype); reheap_down(arr, nelem, esize, cmp, swaptype, 0); } } void hsort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp) { int type = SWAPTYPE(arr, esize); if ( arr == NULL || nelem <= 1 || esize == 0 || cmp == NULL ) return; hsort_i(arr, nelem, esize, cmp, type); } #define QS_MAXDEPTH 48 struct qswork { byte_t *start; size_t nelem; int qdepth; }; #define PUSH(__stk, __t, __s, __ne, __qd) \ __stk[__t].start = __s; \ __stk[__t].nelem = __ne; \ __stk[__t++].qdepth = __qd; #define POP(__stk, __t, __s, __ne, __qd) \ __s = __stk[--__t].start; \ __ne = __stk[__t].nelem; \ __qd = __stk[__t].qdepth; static byte_t *median3(byte_t *m1, byte_t *m2, byte_t *m3, cmp_f cmp) { if ( (*cmp)(m1, m2) < 0 ) { /* (1,2,3),(3,1,2),(1,3,2) */ if ( (*cmp)(m2, m3) < 0 ) { /* (1,2,3) */ return m2; } else if ( (*cmp)(m1, m3) < 0 ) { /* (1,3,2) */ return m3; } else { /* (3,1,2) */ return m1; } } else { /* m2 >= m1 */ /* (2,1,3),(2,3,1),(3,2,1) */ if ( (*cmp)(m1, m3) < 0 ) { /* (2,1,3) */ return m1; } else if ( (*cmp)(m2, m3) < 0 ) { /* (2,3,1) */ return m3; } else { /* (3,2,1) */ return m2; } } } #define ISORT_THRESH 8 /* This is actually an "intro-sort" because it will only sort down to 2log2 */ /* of the number of elements and will heap sort sub arrays past that. This */ /* guarantees nlogn performance. Also, the sort uses insertion sort for */ /* subarrays of 8 elements or less. */ void qsort_array(void *arr, const size_t nelem, const size_t esize, cmp_f cmp) { byte_t *start, *pivot, *lo, *hi, *end, *m1, *m2, *m3; int bailout_depth = 0, depth; struct qswork stack[QS_MAXDEPTH]; int top = 0; size_t n, nlo, stride; const int swaptype = SWAPTYPE(arr, esize); if ( arr == NULL || nelem <= 1 || esize == 0 || cmp == NULL ) return; if ( nelem <= ISORT_THRESH ) { isort_i(arr, nelem, esize, cmp, swaptype); return; } /* find 2*floor(log2(nelem)) */ n = nelem; while ( (n >>= 1) ) ++bailout_depth; bailout_depth = bailout_depth * 2; if ( bailout_depth > QS_MAXDEPTH-3 ) bailout_depth = QS_MAXDEPTH-3; start = arr; n = nelem; depth = 1; while ( 1 ) { /* heap sort past the log2 of # of elements in recurse depth */ if ( depth > bailout_depth ) { hsort_i(start, n, esize, cmp, swaptype); if ( top == 0 ) break; POP(stack, top, start, n, depth); continue; } /* actual quicksort: we must have 9 or more elements now */ m1 = start; lo = start + esize; m2 = start + (n >> 1) * esize; end = start + esize * n; m3 = hi = end - esize; if ( n > 64 ) { stride = esize * (n / 9); m1 = median3(m1, m1 + stride, m1 + stride * 2, cmp); m2 = median3(m2 - stride, m2, m2 + stride, cmp); m3 = median3(m3 - stride * 2, m3 - stride, m3, cmp); } pivot = median3(m1, m2, m3, cmp); if ( pivot != start ) SWAP(start, pivot, swaptype); while ( 1 ) { while ( (*cmp)(start, lo) >= 0 ) { if ( lo == hi ) { hi += esize; goto done_inner; } lo += esize; } while ( (*cmp)(start, hi) < 0 ) { if ( lo == hi ) { lo -= esize; goto done_inner; } hi -= esize; } SWAP(lo, hi, swaptype); if ( lo + esize == hi ) goto done_inner; lo += esize; hi -= esize; } done_inner: /* swap the pivot to the end of the low array */ SWAP(start, lo, swaptype); depth += 1; n = (end - hi) / esize; if ( n > ISORT_THRESH ) { nlo = (lo - start) / esize; if ( nlo > ISORT_THRESH ) { PUSH(stack, top, start, nlo, depth); } else { isort_i(start, nlo, esize, cmp, swaptype); } start = hi; } else { isort_i(hi, n, esize, cmp, swaptype); n = (lo - start) / esize; if ( n <= ISORT_THRESH ) { isort_i(start, n, esize, cmp, swaptype); if ( top == 0 ) break; POP(stack, top, start, n, depth); } } } } void array_to_voidp(void **varr, void *arr, size_t nelem, size_t esize) { byte_t *p = arr; if ( (nelem < 1) || (esize == 0) || (~(size_t)0 / esize < nelem) ) return; do { *varr++ = p; p += esize; } while ( --nelem > 0 ); } void permute_array(void *arr, void *tmp, void **varr, size_t nelem, size_t esize) { byte_t *ap = arr, *phi, *lastp, *hold; size_t hi, to; if ( (nelem < 2) || (esize == 0) || (~(size_t)0 / esize < nelem) ) return; for ( hi = 0, phi = ap; hi < nelem ; ++hi, phi += esize ) { if ( varr[hi] == phi ) continue; to = hi; lastp = phi; memcpy(tmp, phi, esize); do { memcpy(lastp, varr[to], esize); hold = lastp; lastp = varr[to]; varr[to] = hold; to = (lastp - ap) / esize; } while ( varr[to] != phi ); memcpy(lastp, tmp, esize); varr[to] = lastp; } }
github188/catlib
src/socks5.c
/* * socks5.c -- SOCKS5 protocol routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/socks5.h> #if CAT_HAS_POSIX #include <stdlib.h> #include <string.h> #include <errno.h> #include <cat/pack.h> #include <cat/netinc.h> #include <cat/io.h> void socks5_sa_to_s5a(struct socks5addr *s5a, struct sockaddr *sa) { abort_unless(s5a != NULL && sa != NULL); abort_unless(sa->sa_family == AF_INET || sa->sa_family == AF_INET6); if ( sa->sa_family == AF_INET ) { struct sockaddr_in *sin = (struct sockaddr_in *)sa; s5a->type = SOCKS5_AT_IPV4; s5a->len = 4; memcpy(s5a->addr_u.v4addr, &sin->sin_addr, 4); s5a->port = ntoh16(sin->sin_port); } else { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; s5a->type = SOCKS5_AT_IPV6; s5a->len = 16; memcpy(s5a->addr_u.v6addr, &sin6->sin6_addr, 16); s5a->port = ntoh16(sin6->sin6_port); } } void socks5_dn_to_s5a(struct socks5addr *s5a, char *domainname, ushort port) { size_t slen; abort_unless(s5a != NULL && domainname != NULL); slen = strlen(domainname); abort_unless(slen <= 255); s5a->type = SOCKS5_AT_DN; s5a->len = slen; memcpy(s5a->addr_u.dn, domainname, slen + 1); s5a->port = port; } int socks5_anon_probe(int fd) { char buf[64]; int len; byte_t v, m; len = pack(buf, sizeof(buf), "bbb", 5, 1, 0); if ( io_write(fd, buf, len) < len ) return -1; if ( io_read(fd, buf, 2) < 2 ) return -1; unpack(buf, 2, "bb", &v, &m); if ( v != 5 ) { errno = EIO; return -1; } if ( m != 0 ) { errno = EACCES; return -1 - m; } return 0; } static int resp_ok(int r_v, int r_rc, int r_at, int atype) { if ( r_v != 5 ) { errno = EIO; return -1; } if ( r_at != atype ) { if ( (r_at != SOCKS5_AT_IPV4) && (r_at != SOCKS5_AT_DN) && (r_at != SOCKS5_AT_IPV6) ) { errno = EIO; return -1; } if ( atype != SOCKS5_AT_DN ) { errno = EIO; return -1; } } if ( r_rc != 0 ) return -1 - r_rc; return 0; } int socks5_recvresp(int fd, int cmd, int atype, struct socks5addr *outsa) { byte_t buf[SOCKS5_MAXLEN], *bp; int len, rok; ssize_t rv; byte_t r_v, r_rc, r_r, r_at; if ( cmd == SOCKS5_CT_UDP ) { /* get the return packet in one big whomp */ if ( (rv = recv(fd, buf, SOCKS5_MAXLEN, 0)) < 0 ) return -1; /* min response size is 4 bytes + 1-byte len + 2 bytes */ if ( rv < 7 ) { errno = EIO; return -1; } /* validate return codes. Ignore reserved bits. Ensure */ /* version is correct. Make sure address type matches or is */ /* valid address if the address we sent was a domain name */ unpack(buf, 4, "bbbb", &r_v, &r_rc, &r_r, &r_at); if ( (rok = resp_ok(r_v, r_rc, r_at, atype)) != 0 ) return rok; /* Set the correct length for the data */ if ( r_at == SOCKS5_AT_IPV4 ) { len = 4; } else if ( r_at == SOCKS5_AT_DN ) { len = *((byte_t *)buf + 4); } else { len = 16; } if ( len > rv - 6 ) { errno = EIO; return -1; } bp = buf + 4; } else { /* read the first part of the response */ if ( io_read(fd, buf, 4) < 4 ) return -1; /* validate return codes. Ignore reserved bits. Ensure */ /* version is correct. Make sure address type matches or is */ /* valid address if the address we sent was a domain name */ unpack(buf, 4, "bbbb", &r_v, &r_rc, &r_r, &r_at); if ( (rok = resp_ok(r_v, r_rc, r_at, atype)) != 0 ) return rok; /* determine the length of the return address */ if ( r_at == SOCKS5_AT_IPV4 ) { len = 4; } else if ( r_at == SOCKS5_AT_DN ) { if ( io_read(fd, buf, 1) < 1 ) return -1; len = *(byte_t *)buf; } else { len = 16; } /* read the actual response */ if ( io_read(fd, buf, len + 2) < len + 2 ) return -1; bp = buf; } /* report the response if the outsa was requested */ if ( outsa != NULL ) { outsa->type = r_at; outsa->len = len; memcpy(&outsa->addr_u, bp, len); if ( r_at == SOCKS5_AT_DN ) outsa->addr_u.dn[len] = '\0'; unpack(bp + len, 2, "h", &outsa->port); } return 0; } int socks5_sendreq(int fd, int cmd, struct socks5addr *s5a) { byte_t buf[SOCKS5_MAXLEN]; int len; struct raw ra; abort_unless(cmd >= SOCKS5_CT_CONNECT && cmd <= SOCKS5_CT_UDP); abort_unless(s5a != NULL); abort_unless(s5a->type == SOCKS5_AT_IPV4 || s5a->type == SOCKS5_AT_DN || s5a->type == SOCKS5_AT_IPV6); if ( s5a->type == SOCKS5_AT_IPV4 ) { abort_unless(s5a->len == 4); } else if ( s5a->type == SOCKS5_AT_DN ) { abort_unless(s5a->len <= 255); } else { abort_unless(s5a->len == 16); } /* form the request */ len = pack(buf, sizeof(buf), "bbbb", 5, cmd, 0, s5a->type); ra.data = (byte_t*)&s5a->addr_u; ra.len = s5a->len; len += pack(buf + len, sizeof(buf) - len, "rh", &ra, s5a->port); /* write the request */ if ( io_write(fd, buf, len) < len ) return -1; return 0; } int socks5_anon_conn(int fd, struct socks5addr *insa, struct socks5addr *outsa) { int rv; if ( (rv = socks5_anon_probe(fd)) != 0 ) return rv; if ( (rv = socks5_sendreq(fd, SOCKS5_CT_CONNECT, insa)) != 0 ) return rv; return socks5_recvresp(fd, SOCKS5_CT_CONNECT, insa->type, outsa); } #endif /* CAT_HAS_POSIX */
github188/catlib
src/pspawn.c
<filename>src/pspawn.c /* * pspawn.c -- intelligent (co-)process spawing API * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #if CAT_HAS_POSIX #define DBG fprintf(stderr, "DBG:%s:%d\n", __FILE__, __LINE__); #ifndef CAT_PS_MAXFDS #define CAT_PS_MAXFDS 1024 #endif #include <cat/pspawn.h> #include <cat/cds.h> #include <cat/bitset.h> #include <cat/io.h> #include <stdarg.h> #include <limits.h> #include <unistd.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> /* data structures */ CDS_NEWSTRUCT(struct list, int, fdnode_t); #define ln_to_fd(node) CDS_DATA(node, fdnode_t) #define ln_to_fde(node) container(node, struct ps_fd_entry, entry) /* Helper functions */ static struct ps_fd_entry *ps_spec_newfde(struct ps_spec *spec, int type); static int ps_fds_type_ok(int type); static void ps_fd_entry_cleanup(struct ps_fd_entry *psfde); static struct ps_fd_entry *ps_fde_find(struct pspawn *ps, int remfd); static int spec_ok(struct ps_spec *spec); static int create_pipes(struct pspawn *ps); static int open_stdio_files(struct pspawn *ps); static int open_rdr_files(struct pspawn *ps); static int set_up_fds(struct pspawn *ps, int *retfd); static int set_up_fd(struct pspawn *ps, bitset_t *pipefds, int tfd, int sfd, int *retfd, int *nomap); static void ps_launch_child(struct pspawn *ps, int pipefds[2], char * const *argv, char * const *envp); static int ps_launch_parent(struct pspawn *ps, int pipefds[2]); void ps_ignore_sigcld() { signal(SIGCHLD, SIG_IGN); } void ps_spec_init(struct ps_spec *spec) { l_init(&spec->fdelist); } void ps_spec_cleanup(struct ps_spec *spec) { struct list *node; struct ps_fd_entry *psfde; while ( (node = l_deq(&spec->fdelist)) != NULL ) { psfde = ln_to_fde(node); ps_fd_entry_cleanup(psfde); free(psfde); } } static void ps_fd_entry_cleanup(struct ps_fd_entry *e) { struct list *node; if ( e->file != NULL ) { fclose(e->file); e->file = NULL; } else if ( e->locfd >= 0 ) { close(e->locfd); } if ( (e->pipefd >= 0) && (e->type != PSFD_REMAP) ) close(e->pipefd); e->locfd = -1; e->pipefd = -1; while ( (node = l_deq(&e->remfds)) != NULL ) CDS_FREE(node); } int ps_spec_copy(struct ps_spec *dst, const struct ps_spec *src) { struct list *t, *t2; struct ps_fd_entry *old, *new; fdnode_t *fdn; abort_unless(dst != NULL); abort_unless(src != NULL); ps_spec_init(dst); l_for_each(t, &src->fdelist) { old = ln_to_fde(t); if ( (new = ps_spec_newfde(dst, old->type)) == NULL ) goto err; new->pipefd = old->pipefd; new->locfd = old->locfd; l_for_each(t2, &old->remfds) { CDS_NEW(fdn, ln_to_fd(t2)); if ( fdn == NULL ) goto err; l_enq(&new->remfds, &fdn->node); } } return 0; err: ps_spec_cleanup(dst); return -1; } static struct ps_fd_entry *ps_spec_newfde(struct ps_spec *spec, int type) { struct ps_fd_entry *psfde; psfde = malloc(sizeof(struct ps_fd_entry)); if ( psfde == NULL ) return NULL; psfde->locfd = -1; psfde->pipefd = -1; l_init(&psfde->remfds); psfde->type = type; psfde->file = NULL; psfde->path = NULL; psfde->mode = 0644; l_enq(&spec->fdelist, &psfde->entry); return psfde; } struct ps_fd_entry *ps_spec_add_pipe(struct ps_spec *spec, int type) { if ( !ps_fds_type_ok(type) || ((type & PSFD_FSRDR) != 0) || ((type & PSFD_REMAP) != 0) ) { errno = EINVAL; return NULL; } return ps_spec_newfde(spec, type); } struct ps_fd_entry *ps_spec_add_remap(struct ps_spec *spec, int fd) { struct ps_fd_entry *psfde; if ( fd < 0 ) { errno = EINVAL; return NULL; } if ( (psfde = ps_spec_newfde(spec, PSFD_REMAP)) != NULL ) psfde->pipefd = fd; return psfde; } struct ps_fd_entry *ps_spec_keepfd(struct ps_spec *spec, int fd) { struct ps_fd_entry *psfde = ps_spec_add_remap(spec, fd); if ( psfde != NULL ) ps_fde_addfd(psfde, fd); return psfde; } struct ps_fd_entry *ps_spec_add_fsrdr(struct ps_spec *spec, int type, const char *path) { struct ps_fd_entry *psfde; if ( (path == NULL) || (*path == '\0') ) { errno = EINVAL; return NULL; } type |= PSFD_FSRDR; if ( !ps_fds_type_ok(type) ) { errno = EINVAL; return NULL; } if ( (psfde = ps_spec_newfde(spec, type)) != NULL ) psfde->path = path; return psfde; } void ps_rdr_set_mode(struct ps_fd_entry *psfde, uint mode) { if ( (psfde == NULL) || ((psfde->type & PSFD_FSRDR) != 0) ) return; psfde->mode = mode; } /* rules: - if type is 'remap' no other bits must be set - if type contains 'fsrdr' then no buffer flags, or stdio can be set - 'append' can only be set on if 'filerdr' is set and dir is 'out' - direction bits must be non-zero (unless type == 'preserve') - buffer bits must be non-zero if STDIO flag is set */ static int ps_fds_type_ok(int type) { if ( type == PSFD_REMAP ) return 1; if ( (type & PSFD_REMAP) != 0 ) return 0; if ( ((type & PSFD_FSRDR) != 0) && ((type & (PSFD_STDIO|PSFD_BMASK)) != 0) ) return 0; if ( (((type & PSFD_FSRDR) == 0) || ((type &PSFD_DMASK) != PSFD_OUT)) && ((type & (PSFD_APPEND)) != 0) ) return 0; if ( (type & PSFD_DMASK) == 0 ) return 0; if ( ((type & PSFD_STDIO) != 0) && ((type & PSFD_BMASK) == 0) ) return 0; return 1; } void ps_spec_del_fde(struct ps_spec *spec, struct ps_fd_entry *psfde) { ps_fd_entry_cleanup(psfde); l_rem(&psfde->entry); free(psfde); } int ps_fde_addfd(struct ps_fd_entry *psfde, int fd) { fdnode_t *fdn; CDS_NEW(fdn, fd); if ( fdn == NULL ) return -1; l_enq(&psfde->remfds, &fdn->node); return 0; } void ps_fde_delfd(struct ps_fd_entry *psfde, int fd) { struct list *t, *h, *remfdl = &psfde->remfds; t = l_head(remfdl); while ( t != l_end(remfdl) ) { h = t; t = t->next; if ( ln_to_fd(h) == fd ) { l_rem(h); CDS_FREE(h); } } } struct pspawn * ps_launch(char * const argv[], char * const envp[], struct ps_spec *spec) { struct pspawn *ps; int retpipe[2] = { -1, -1 }; int rerrno = 0; pid_t pid; if ( (argv == NULL) || (*argv == NULL) || !spec_ok(spec) ) { errno = EINVAL; return NULL; } if ( (ps = calloc(1, sizeof(*ps))) == NULL ) return NULL; ps->cpid = -1; if ( ps_spec_copy(&ps->spec, spec) < 0 ) { rerrno = errno; goto err; } ps->state = PSS_INIT; if ( pipe(retpipe) < 0 ) { rerrno = errno; goto err; } if ( create_pipes(ps) < 0 ) { rerrno = ps->error; goto err; } if ( open_stdio_files(ps) < 0 ) { rerrno = ps->error; goto err; } pid = fork(); if ( pid < 0 ) { rerrno = errno; goto err; } else if ( pid == 0 ) { ps_launch_child(ps, retpipe, argv, envp); /* does not return */ } else { ps->cpid = pid; close(retpipe[1]); retpipe[1] = -1; if ( ps_launch_parent(ps, retpipe) < 0 ) { rerrno = ps->error; goto err; } close(retpipe[0]); } ps->state = PSS_LAUNCHED; return ps; err: if ( retpipe[0] >= 0 ) close(retpipe[0]); if ( retpipe[1] >= 0 ) close(retpipe[1]); ps_spec_cleanup(&ps->spec); free(ps); errno = rerrno; return NULL; } static int spec_ok(struct ps_spec *spec) { struct list *t, *t2; struct ps_fd_entry *psfde; DECLARE_BITSET(mapped, CAT_PS_MAXFDS); bset_zero(mapped, CAT_PS_MAXFDS); l_for_each(t, &spec->fdelist) { psfde = ln_to_fde(t); if ( !ps_fds_type_ok(psfde->type) ) goto fail; if ( l_isempty(&psfde->remfds) ) goto fail; l_for_each(t2, &psfde->remfds) { int fd = ln_to_fd(t2); if ( (fd < 0) || (fd >= CAT_PS_MAXFDS) ) goto fail; if ( bset_test(mapped, fd) ) goto fail; bset_set(mapped, fd); } } return 1; fail: return 0; } static int create_pipes(struct pspawn *ps) { struct list *t; struct ps_fd_entry *psfde; int pipefds[2]; l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if ( psfde->type == PSFD_REMAP ) continue; if ( (psfde->type & PSFD_FSRDR) != 0 ) continue; if ( (psfde->type & PSFD_DMASK) == 0 ) { ps->error = EINVAL; return -1; } if ( (psfde->type & PSFD_DMASK) == PSFD_INOUT ) { if ( socketpair(AF_UNIX,SOCK_STREAM,0,pipefds) < 0 ) { ps->error = errno; return -1; } } else { if ( pipe(pipefds) < 0 ) { ps->error = errno; return -1; } } if ( (psfde->type & PSFD_DMASK) == PSFD_IN ) { psfde->locfd = pipefds[1]; psfde->pipefd = pipefds[0]; } else { psfde->locfd = pipefds[0]; psfde->pipefd = pipefds[1]; } } return 0; } static int open_stdio_files(struct pspawn *ps) { struct list *t; struct ps_fd_entry *psfde; const char *omode = NULL; int bmode; FILE *fp; l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if ( (psfde->type & PSFD_STDIO) == 0 ) continue; switch (psfde->type & PSFD_DMASK) { case PSFD_IN: omode = "w"; break; case PSFD_OUT: omode = "r"; break; case PSFD_INOUT: omode = "r+"; break; default: abort_unless(0); } switch (psfde->type & PSFD_BMASK) { case PSFD_FULLBUF: bmode = _IOFBF; break; case PSFD_NOBUF: bmode = _IOLBF; break; case PSFD_LINEBUF: bmode = _IONBF; break; default: ps->error = EINVAL; return -1; } if ( (fp = fdopen(psfde->locfd, omode)) == NULL ) { ps->error = errno; return -1; } if ( bmode != _IOFBF ) { if ( setvbuf(fp, NULL, bmode, 0) < 0 ) { fclose(fp); close(psfde->pipefd); psfde->locfd = psfde->pipefd = -1; } } psfde->file = fp; } return 0; } static void ps_launch_child(struct pspawn *ps, int retpipe[2], char * const argv[], char * const envp[]) { int rerrno = 0; int flags; char * const tenv[] = { NULL }; if ( envp == NULL ) envp = tenv; close(retpipe[0]); if ( open_rdr_files(ps) < 0 ) { rerrno = ps->error; goto err; } if ( (flags = fcntl(retpipe[1], F_GETFD)) < 0 ) { rerrno = errno; goto err; } flags |= FD_CLOEXEC; if ( fcntl(retpipe[1], F_SETFD, flags) < 0 ) { rerrno = errno; goto err; } if ( set_up_fds(ps, &retpipe[1]) < 0 ) { rerrno = ps->error; goto err; } execve(argv[0], argv, envp); rerrno = errno; err: io_write(retpipe[1], &rerrno, sizeof(int)); exit(129); } static int open_rdr_files(struct pspawn *ps) { struct list *t; struct ps_fd_entry *psfde; int fd; int flags; l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if ( (psfde->type & PSFD_FSRDR) == 0 ) continue; if ( (psfde->type & PSFD_DMASK) == PSFD_IN ) { flags = O_RDONLY; } else if ( (psfde->type & PSFD_DMASK) == PSFD_OUT ) { flags = O_WRONLY|O_CREAT; if ( (psfde->type & PSFD_APPEND) != 0 ) flags |= O_APPEND; else flags |= O_TRUNC; } else { flags = O_RDWR|O_CREAT; } if ( (psfde->type & PSFD_DMASK) == PSFD_IN ) fd = open(psfde->path, flags); else fd = open(psfde->path, flags, psfde->mode); if ( fd < 0 ) { ps->error = errno; return -1; } psfde->pipefd = fd; } return 0; } static int set_up_fds(struct pspawn *ps, int *retfd) { int i, rv, nomap; struct list *t, *t2; struct ps_fd_entry *psfde; DECLARE_BITSET(pipefds, CAT_PS_MAXFDS); bset_zero(pipefds, CAT_PS_MAXFDS); bset_set(pipefds, *retfd); /* populate the set of file descriptors we need to map */ l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if ( psfde->locfd >= 0 ) close(psfde->locfd); bset_set(pipefds, psfde->pipefd); } /* close all descriptors except the remaining pipes */ for ( i = 0 ; i < CAT_PS_MAXFDS ; i++ ) if ( !bset_test(pipefds, i) ) close(i); l_for_each(t, &ps->spec.fdelist) { nomap = 0; psfde = ln_to_fde(t); l_for_each(t2, &psfde->remfds) { rv = set_up_fd(ps, pipefds, ln_to_fd(t2), psfde->pipefd, retfd, &nomap); if ( rv < 0 ) { ps->error = errno; goto err; } } if (!nomap) { close(psfde->pipefd); psfde->pipefd = -1; } } return 0; err: return -1; } static int set_up_fd(struct pspawn *ps, bitset_t *pipefds, int tfd, int sfd, int *retfd, int *nomap) { struct list *t; struct ps_fd_entry *psfde = NULL; int dfd = -1; if ( tfd == sfd ) { *nomap = 1; return 0; } if ( bset_test(pipefds, tfd) ) { /* duplicate the blocking fd */ if ( (dfd = dup(tfd)) < 0 ) return -1; } if ( dup2(sfd, tfd) < 0 ) { if ( dfd >= 0 ) close(dfd); return -1; } if ( dfd >= 0 ) { /* find the entry that was blocking us to update later */ l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if ( psfde->pipefd == tfd ) break; } if (psfde == NULL) { abort_unless(tfd == *retfd); *retfd = dfd; } else { psfde->pipefd = dfd; } } bset_clr(pipefds, sfd); return 0; } static int ps_launch_parent(struct pspawn *ps, int retpipe[2]) { int rlen, rval; struct list *t; struct ps_fd_entry *psfde; l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); if (psfde->type == PSFD_REMAP) continue; if (psfde->pipefd >= 0) { close(psfde->pipefd); psfde->pipefd = -1; } } if ( (rlen = io_read(retpipe[0], &rval, sizeof(int))) < 0 ) { ps->error = errno; return -1; } abort_unless(rlen <= sizeof(int)); if ( rlen > 0 && rlen < sizeof(int) ) { ps->error = EIO; return -1; } if ( rlen == sizeof(int) ) { ps->error = rval; return -1; } return 0; } static struct ps_fd_entry *ps_fde_find(struct pspawn *ps, int remfd) { struct list *t, *t2; struct ps_fd_entry *psfde; if ( ps == NULL ) return NULL; l_for_each(t, &ps->spec.fdelist) { psfde = ln_to_fde(t); l_for_each(t2, &psfde->remfds) { if ( ln_to_fd(t2) == remfd ) return psfde; } } return NULL; } int ps_get_locfd(struct pspawn *ps, int remfd) { struct ps_fd_entry *psfde = ps_fde_find(ps, remfd); return (psfde == NULL) ? -1 : psfde->locfd; } FILE *ps_get_locfile(struct pspawn *ps, int remfd) { struct ps_fd_entry *psfde = ps_fde_find(ps, remfd); return (psfde == NULL) ? NULL : psfde->file; } void ps_closeio(struct pspawn *ps, int remfd) { struct ps_fd_entry *psfde = ps_fde_find(ps, remfd); if ( psfde == NULL ) return; if ( psfde->file ) { fclose(psfde->file); psfde->file = NULL; } else if ( psfde->locfd >= 0 ) { close(psfde->locfd); } psfde->locfd = -1; } int ps_running(struct pspawn *ps) { pid_t pid; int status; abort_unless(ps != NULL); if ( ps->state != PSS_LAUNCHED ) return 0; pid = waitpid(ps->cpid, &status, WNOHANG); if ( pid < 0 ) { abort_unless(errno == ECHILD); pid = 0; } if ( pid != 0 ) { abort_unless(pid == ps->cpid); abort_unless(WIFEXITED(status)); ps->state = PSS_FINISHED; ps->exit_status = WEXITSTATUS(status); } return ps->state == PSS_LAUNCHED; } int ps_cleanup(struct pspawn *ps, int wait) { pid_t pid; int status; abort_unless(ps != NULL); if ( wait && (ps->state == PSS_LAUNCHED) ) { do { pid = waitpid(ps->cpid, &status, 0); if ( pid > 0 ) ps->exit_status = WEXITSTATUS(status); } while ( (pid < 0) && (errno == EINTR) ); } status = ps->exit_status; ps->state = PSS_FINISHED; ps_spec_cleanup(&ps->spec); free(ps); return status; } static int modech_ok(int ch) { return (ch >= '0' && ch <= '2') || (ch == '+'); } #define PS_ARGARR_SIZE 16 struct pspawn *ps_spawn(const char *mode, ...) { va_list ap; uint i, narg = 1; char **args = NULL; char * const * envp = NULL; struct pspawn *ps = NULL; int esave; if ( mode == NULL ) mode = ""; /* count arguments */ va_start(ap, mode); while ( va_arg(ap, const char *) != NULL ) ++narg; va_end(ap); /* decrement by 1 if the environment is the first argument */ if ( *mode == 'e' ) --narg; /* ensure that we have at least 2 arguments (command and NULL) */ if ( narg < 2 ) { errno = EINVAL; return NULL; } /* allocate fresh array for arguments */ if ( UINT_MAX / sizeof(char *) < narg ) { errno = EINVAL; return NULL; } if ( (args = malloc(sizeof(char *) * narg)) == NULL ) return NULL; /* copy arguments to local array */ va_start(ap, mode); if ( *mode == 'e' ) { /* Grab environment array if present */ envp = va_arg(ap, char **); ++mode; } for ( i = 0; i < narg; i++ ) args[i] = va_arg(ap, char *); va_end(ap); ps = ps_spawn_x(mode, args, envp); esave = errno; free(args); errno = esave; return ps; } struct pspawn *ps_spawn_x(const char *mode, char * const *args, char * const *envp) { uint i, type, bmode; int minfd = -1, fd; int rerrno = 0; int keepfds[3] = { 1, 1, 1 }; struct ps_spec spec; struct ps_fd_entry *psfde = NULL; struct pspawn *ps = NULL; if ( mode == NULL ) mode = ""; ps_spec_init(&spec); while ( *mode != '\0' ) { bmode = PSFD_FULLBUF; if ( *mode == 'n' ) { bmode = PSFD_NOBUF; mode++; } else if ( *mode == 'l' ) { bmode = PSFD_LINEBUF; mode++; } if ( !modech_ok(*mode) ) { rerrno = EINVAL; goto out; } if ( *mode == '+' ) { if ( bmode != PSFD_FULLBUF || minfd != 1 || *++mode != '2' ) { rerrno = EINVAL; goto out; } fd = 2; if ( ps_fde_addfd(psfde, 2) < 0 ) { rerrno = errno; goto out; } } else { fd = *mode - '0'; if ( fd <= minfd ) { rerrno = EINVAL; goto out; } type = PSFD_STDIO | bmode; type |= (fd == 0 ? PSFD_IN : PSFD_OUT); if ( (psfde = ps_spec_add_pipe(&spec, type)) == NULL ) { rerrno = errno; goto out; } if ( ps_fde_addfd(psfde, fd) < 0 ) { rerrno = errno; goto out; } minfd = fd; } keepfds[fd] = 0; ++mode; } for ( i = 0 ; i < 3 ; i++ ) { if ( keepfds[i] ) { if ( ps_spec_keepfd(&spec, i) == NULL ) { rerrno = errno; goto out; } } } ps = ps_launch(args, envp, &spec); if ( ps == NULL ) rerrno = errno; out: ps_spec_cleanup(&spec); if ( rerrno != 0 ) errno = rerrno; return ps; } #endif /* CAT_HAS_POSIX */
github188/catlib
include/cat/dlist.h
<reponame>github188/catlib<gh_stars>1-10 /* * cat/dlist.h -- Delta list header file for catlib2 * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __CAT_DLIST_H #define __CAT_DLIST_H #include <cat/cat.h> #include <cat/list.h> #include <cat/time.h> #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_DLIST_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #endif /* CAT_USE_INLINE */ struct dlist { struct list entry; cat_time_t ttl; }; DECL void dl_init(struct dlist *node, cat_time_t ttl); DECL void dl_ins(struct dlist *list, struct dlist *node); DECL void dl_first(struct dlist *list, cat_time_t *next); DECL struct dlist * dl_deq(struct dlist *list); DECL void dl_adv(struct dlist *list, cat_time_t amt, struct list *out); DECL void dl_rem(struct dlist *elem); DECL void dl_update(struct dlist *list, struct dlist *elem, cat_time_t ttl); #define l_to_dl(le) container(le, struct dlist, entry) #define dl_head(list) l_to_dl(((list)->entry.next)) #define dl_end(list) l_to_dl((&(list)->entry)) #define dl_next(node) l_to_dl(((struct dlist *)(list)->entry.next)) #define dl_isempty(node) l_isempty(&(node)->entry) #if defined(CAT_DLIST_DO_DECL) && CAT_DLIST_DO_DECL DECL void dl_init(struct dlist *node, cat_time_t ttl) { abort_unless(node); l_init(&node->entry); node->ttl = ttl; if ( tm_ltz(node->ttl) ) node->ttl = tm_zero; } DECL void dl_ins(struct dlist *dlist, struct dlist *node) { cat_time_t ttl; struct list *t, *list; struct dlist *dl; abort_unless(dlist); abort_unless(node); list = &dlist->entry; ttl = node->ttl; for ( t = l_head(list) ; t != l_end(list) ; t = t->next ) { dl = container(t, struct dlist, entry); if ( tm_cmp(ttl, dl->ttl) < 0 ) break; else ttl = tm_sub(ttl, dl->ttl); } if ( t != l_end(list) ) dl->ttl = tm_sub(dl->ttl, ttl); l_ins(t->prev, &node->entry); node->ttl = ttl; } DECL void dl_first(struct dlist *dlist, cat_time_t *tm) { abort_unless(dlist); abort_unless(tm); if ( l_isempty(&dlist->entry) ) *tm = tm_lset(-1, -1); else *tm = container(l_head(&dlist->entry), struct dlist, entry)->ttl; } DECL struct dlist * dl_deq(struct dlist *dlist) { struct list *list, *node; abort_unless(dlist); list = &dlist->entry; if ( l_isempty(list) ) return NULL; else { node = l_head(list); l_rem(node); return container(node, struct dlist, entry); } } DECL void dl_adv(struct dlist *dlist, cat_time_t delta, struct list *out) { struct dlist *dl; struct list *t, *head, *list; abort_unless(dlist); abort_unless(out); l_init(out); list = &dlist->entry; if ( l_isempty(list) ) return; for ( t = l_head(list) ; t != l_end(list) ; t = t->next ) { dl = container(t, struct dlist, entry); if ( tm_cmp(dl->ttl, delta) > 0 ) break; else delta = tm_sub(delta, dl->ttl); } if ( t != l_end(list) ) dl->ttl = tm_sub(dl->ttl, delta); head = l_head(list); t = t->prev; if ( t->next == head ) return; list->next = t->next; t->next->prev = list; head->prev = out; out->next = head; t->next = out; out->prev = t; } DECL void dl_rem(struct dlist *elem) { struct dlist *next; if ( l_onlist(&elem->entry) ) { next = container(elem->entry.next, struct dlist, entry); next->ttl = tm_add(next->ttl, elem->ttl); l_rem(&elem->entry); } } DECL void dl_update(struct dlist *list, struct dlist *elem, cat_time_t ttl) { dl_rem(elem); elem->ttl = ttl; if ( tm_ltz(elem->ttl) ) elem->ttl = tm_zero; dl_ins(list, elem); } #endif /* CAT_DLIST_DO_DECL */ #undef DECL #undef CAT_DLIST_DO_DECL #endif /* __CAT_DLIST_H */
github188/catlib
test/testpack.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <string.h> #include <assert.h> #include <cat/pack.h> #include <cat/raw.h> int main(int argc, char *argv[]) { unsigned char buffer[5000]; struct raw r1, r2; char c = -1; unsigned char uc = 1; short s = -20; unsigned short us = 20; long l = -400000; unsigned long ul = 400000; #if CAT_HAS_LONGLONG long long ll = -8000000000ll; unsigned long long ull = 8000000000ll; #endif /* CAT_HAS_LONGLONG */ char *string1 = "Hello world!", strbuf1[50], *string2 = "Hi again!", strbuf2[50]; #if CAT_HAS_LONGLONG char *bfmt = "rbHBwJWh%dbj"; #else /* CAT_HAS_LONG_LONG */ char *bfmt = "rbHBwWh%db"; #endif /* CAT_HAS_LONGLONG */ char fmt[50]; int len, i; printf("Original data:\n"); printf("Bytes are %d (%02x) and %u (%02x)\n", c, c & 0xFF, uc, uc); printf("Halves are %d (%04x) and %u (%04x)\n", s, s & 0xFFFF, us, us); printf("Words are %ld (%08lx) and %lu (%08lx)\n", l, l, ul, ul); #if CAT_HAS_LONGLONG printf("Jumbos are %lld (%016llx) and %llu (%016llx)\n", ll, ll, ull, ull); #endif /* CAT_HAS_LONGLONG */ printf("String1 = %s\n", string1); printf("String2 = %s\n", string2); sprintf(fmt, bfmt, strlen(string2)+1); printf("Format string = %s\n", fmt); len = packlen(fmt, str_to_raw(&r1, string1, 1)); printf("Packing will contain %d bytes (raw contains %d)\n", len, (int)r1.len); assert(len > 0); #if CAT_HAS_LONGLONG len = pack(buffer, sizeof(buffer), fmt, &r1, uc, s, c, ul, ll, l, us, string2, ull); #else /* CAT_HAS_LONGLONG */ len = pack(buffer, sizeof(buffer), fmt, &r1, uc, s, c, ul, l, us, string2); #endif /* CAT_HAS_LONGLONG */ assert(len > 0); printf("Packed %d bytes\n", len); printf("bytes : "); for ( i = 0 ; i < len ; ++i ) printf("%02x ", buffer[i]); printf("\n\n"); printf("clearing values!\n"); c = uc = 0; s = us = 0; l = ul = 0; #if CAT_HAS_LONGLONG ll = ull = 0; #endif /* CAT_HAS_LONGLONG */ strbuf2[0] = '\0'; #if CAT_HAS_LONGLONG len = unpack(buffer + r1.len, sizeof(buffer)-r1.len, fmt+1, &uc, &s, &c, &ul, &ll, &l, &us, strbuf2, &ull); #else /* CAT_HAS_LONGLONG */ len = unpack(buffer + r1.len, sizeof(buffer)-r1.len, fmt+1, &uc, &s, &c, &ul, &l, &us, strbuf2); #endif /* CAT_HAS_LONGLONG */ printf("Unpacked %d bytes: \n", len); assert(len > 0); printf("Bytes are %d (%02x) and %u (%02x)\n", c, c & 0xff, uc, uc & 0xff); printf("Halves are %d (%04x) and %u (%04x)\n",s, s & 0xffff, us, us & 0xffff); printf("Words are %ld (%08lx) and %lu (%08lx)\n", l, l, ul, ul); #if CAT_HAS_LONGLONG printf("Jumbos are %lld (%016llx) and %llu (%016llx)\n", ll, ll, ull, ull); #endif /* CAT_HAS_LONGLONG */ printf("String1 = %s\n", buffer); printf("String2 = %s\n", strbuf2); printf("\n\n"); printf("hton16(0x2211) = %x\n", hton16(0x2211)); printf("ntoh16(0x1122) = %x\n", ntoh16(0x1122)); printf("hton32(0x44332211) = %x\n", hton32(0x44332211)); printf("ntoh32(0x11223344) = %x\n", ntoh32(0x11223344)); #if CAT_HAS_LONGLONG printf("ntoh64(0x1122334455667788) = %llx\n", (ullong)ntoh64(0x1122334455667788ll)); printf("hton64(0x8877665544332211) = %llx\n", (ullong)ntoh64(0x8877665544332211ll)); #endif /* CAT_HAS_LONGLONG */ return 0; }
github188/catlib
include/cat/uevent.h
/* * uevent.h -- UNIX event dispatch routines. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __cat_uevent_h #define __cat_uevent_h #include <cat/cat.h> #if CAT_HAS_POSIX #include <cat/mem.h> #include <cat/list.h> #include <cat/dlist.h> #include <cat/avl.h> #include <cat/cb.h> #include <sys/select.h> struct ue_ioevent { struct callback cb; struct list fdlist; int fd; int type; struct uemux * mux; struct memmgr * mm; }; #define UE_RD 1 #define UE_WR 2 #define UE_EX 3 struct ue_timer { struct dlist entry; int flags; ulong orig; struct callback cb; struct memmgr * mm; }; #define UE_TIMEOUT 0 #define UE_PERIODIC 1 #define UE_TREG 0x80 struct ue_sigevent { struct callback cb; int signum; struct uemux * mux; struct memmgr * mm; }; struct uemux { struct memmgr * mm; struct dlist timers; int maxfd; struct cavltree * fdtab; struct list iolist; fd_set rset; fd_set wset; fd_set eset; struct cavltree * sigtab; int done; }; /* mux initialization, finalization and execution */ void ue_init(struct uemux *mux, struct memmgr *mm); void ue_fini(struct uemux *mux); void ue_stop(struct uemux *mux); void ue_next(struct uemux *mux); void ue_run(struct uemux *mux); void ue_runfor(struct uemux *mux, ulong msec); /* timer events */ void ue_tm_init(struct ue_timer *t, int type, ulong ttl, callback_f tof, void *arg); int ue_tm_reg(struct uemux *mux, struct ue_timer *t); void ue_tm_cancel(struct ue_timer *t); /* i/o events */ void ue_io_init(struct ue_ioevent *io, int type, int fd, callback_f f, void *x); int ue_io_reg(struct uemux *mux, struct ue_ioevent *io); void ue_io_cancel(struct ue_ioevent *io); /* Signal events */ void ue_sig_init(struct ue_sigevent *io, int signum, callback_f f, void *x); int ue_sig_reg(struct uemux *mux, struct ue_sigevent *se); void ue_sig_cancel(struct ue_sigevent *se); void ue_sig_clear(void); /* dynamic memory allocation versions */ struct ue_ioevent * ue_io_new(struct uemux *m, int type, int fd, callback_f f, void *ctx); struct ue_timer * ue_tm_new(struct uemux *m, int type, ulong ttl, callback_f f, void *ctx); struct ue_sigevent * ue_sig_new(struct uemux *m, int signum, callback_f f, void *ctx); void ue_tm_del(struct ue_timer *); void ue_io_del(struct ue_ioevent *); void ue_sig_del(struct ue_sigevent *); #endif /* CAT_HAS_POSIX */ #endif /* __cat_uevent_h */
github188/catlib
test/teststr.c
<filename>test/teststr.c<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/str.h> #include <cat/err.h> #include <cat/stduse.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int allrandom = 0; void print_raw_hex(void *dprm, size_t len) { size_t i; unsigned char *d = dprm; for ( i = 0 ; i < len ; ++i,++d ) printf("%02x", *d); printf("\n"); } void test_regular_str() { char buf1[8], *cp; const char *path = "/usr:/usr/bin:/usr/local/bin"; const char *state; char pbuf[64]; byte_t set[32]; size_t ret; int irv; struct path_walker pw; cp = "Hello World"; ret = str_copy(buf1, cp, sizeof(buf1)); printf("str_copy -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); cp = " World"; str_copy(buf1, "Hello", sizeof(buf1)); ret = str_cat(buf1, cp, sizeof(buf1)); printf("str_copy -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); cp = "Hello World"; cset_init_accept(set, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); ret = str_copy_spn(buf1, cp, sizeof(buf1), set); printf("str_copy_spn (alpha) -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); cp = "Hello World"; cset_init_accept(set, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); ret = str_copy_spn(buf1, cp, sizeof(buf1), set); printf("str_copy_spn (upper) -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); cp = "Hello World"; cset_init_reject(set, " \t\n"); ret = str_copy_spn(buf1, cp, sizeof(buf1), set); printf("str_copy_spn (!ws) -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); cp = "Hello World"; str_copy(buf1, "pre: ", sizeof(buf1)); ret = str_cat_spn(buf1, cp, sizeof(buf1), set); printf("str_cat_spn (!ws) -- src:/%s/, dst:/%s/, rv = %u\n", cp, buf1, (uint)ret); irv = str_fmt(buf1, sizeof(buf1), "Hi! %d: %s\n", (int)ret, cp); printf("formatted: /%s/ ret: /%d/\n", buf1, irv); printf("Filename = 'teststr', Path = '%s', sep = ':'\n", path); pwalk_init(&pw, path, ":", '/'); cp = pwalk_next(&pw, "teststr", pbuf, sizeof(pbuf)); while ( cp != NULL ) { printf("Next path = '%s', state = '%s'\n", cp, pw.next); cp = pwalk_next(&pw, "teststr", pbuf, sizeof(pbuf)); } } unsigned long bytemasks[6] = { 0x0000007f, /* 7 */ 0x000007ff, /* 11 */ 0x0000ffff, /* 16 */ 0x001fffff, /* 21 */ 0x03ffffff, /* 26 */ 0x7fffffff, /* 31 */ }; int nbpermute[6] = { 4, 0, 3, 2, 1, 5 }; #define BLEN 10 void test_utf8_codec() { unsigned long longs[BLEN], olongs[BLEN]; char buf[BLEN * 6]; char *cp; const char *errp; unsigned short shorts[BLEN], oshorts[BLEN]; size_t i, nch, clen; int nb, elen, maxclen; cp = " Hello World"; printf("space span of /%s/ = %d\n", cp, (int)utf8_span(cp, " ")); cp = "Hello World"; printf("non-space span of /%s/ = %d\n", cp, (int)utf8_cspan(cp, " ")); cp = "Hello World"; printf("first instance of /%s/ in /%s/ is at offset /%u/\n", "o", cp, (uint)(utf8_findc(cp, "o") - cp)); for ( i = 0; i < BLEN-1 ; ++i ) { if ( allrandom ) nb = (unsigned long)random() % 6L; else nb = nbpermute[i % 6]; olongs[i] = (unsigned long)random() & bytemasks[nb]; nb %= 3; oshorts[i] = (unsigned long)random() & bytemasks[nb]; } olongs[BLEN-1] = 0; oshorts[BLEN-1] = 0; printf("\n---Longs---\n"); printf("utf32 before encode:\n"); print_raw_hex(olongs, sizeof(olongs)); if ( (elen = utf32_to_utf8(buf, sizeof(buf), olongs, BLEN)) < 0 ) err("Error in utf32_to_utf8() encoding\n"); if ( elen != strlen(buf) + 1 ) err("Returned encoded length does not match strlen()\n"); printf("utf8 after encode:\n"); print_raw_hex(buf, elen); printf("Validating encoded form ..."); if ( utf8_validate(buf, elen, &errp, 0) < 0 ) err("encoded utf8 string not valid at pos: %u!\n", (uint)(errp - buf)); printf("valid!\n"); clen = utf8_nchars(buf, elen, &maxclen); if ( clen != BLEN ) err("Encoded length doesn't seem to match original: %u vs %u\n", BLEN, (uint)clen); printf("Character lengths match (%u). Max char len = %d\n", (uint)clen, maxclen); printf("re-decoding to utf32\n"); if ( utf8_to_utf32(longs, BLEN, buf, elen) < 0 ) err("Error decoding back to utf32"); printf("utf8 after decode:\n"); print_raw_hex(longs, sizeof(longs)); for ( i = 0 ; i < BLEN ; ++i ) if ( longs[i] != olongs[i] ) err("Long # %d differs\n", i); printf("Decoded correctly!\n"); printf("\n---Shorts---\n"); printf("utf16 before encode:\n"); print_raw_hex(oshorts, sizeof(oshorts)); if ( (elen = utf16_to_utf8(buf, sizeof(buf), oshorts, BLEN)) < 0 ) err("Error in utf26_to_utf8() encoding\n"); if ( elen != strlen(buf) + 1 ) err("Returned encoded length does not match strlen()\n"); printf("utf8 after encode:\n"); print_raw_hex(buf, elen); printf("Validating encoded form ..."); if ( utf8_validate(buf, elen, &errp, 0) < 0 ) err("encoded utf8 string not valid at pos: %u\n", (uint)(errp - buf)); printf("valid!\n"); clen = utf8_nchars(buf, elen, &maxclen); if ( clen != BLEN ) err("Encoded length doesn't seem to match original: %u vs %u\n", BLEN, (uint)clen); printf("Character lengths match (%u). Max char len = %d\n", (uint)clen, maxclen); printf("re-decoding to utf16\n"); if ( utf8_to_utf16(shorts, BLEN, buf, strlen(buf) + 1) < 0 ) err("Error decoding back to utf16"); printf("utf8 after decode:\n"); print_raw_hex(shorts, sizeof(shorts)); for ( i = 0 ; i < BLEN ; ++i ) if ( shorts[i] != oshorts[i] ) err("Short # %d differs\n", i); printf("Decoded correctly!\n"); } void test_stduse_str() { } int main(int argc, char *argv[]) { if ( argc > 1 && strcmp(argv[1], "-r") == 0) { allrandom = 1; srandom(time(NULL)); } else srandom(0); test_regular_str(); test_utf8_codec(); test_stduse_str(); return 0; }
github188/catlib
include/cat/net.h
/* * cat/net.h -- Network functions * * <NAME> * * Copyright 1999-2012 -- see accompanying license * */ #ifndef __cat_net_h #define __cat_net_h #include <cat/cat.h> #if CAT_HAS_POSIX #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SA struct sockaddr #define SAS struct sockaddr_storage /* * Open a TCP socket and bind it on addr 'host' port 'serv'. * This function tries binding sockets that fit the 'host'/'serv' * pairing until the first one succeeds. It also sets the socket in a * listening state with CAT_LISTENQ queue length. Returns the file * descriptor or -1 on an error. */ int tcp_srv(const char *host, const char *serv); /* * Opens a client connection to address 'host' and port 'serv' on a new socket. * This API will attempt to connection on every possible address for the given * pair until one succeeds. This will include IPv4 and IPv6 addresses with * preference given according to the resolver. This function returns the * socket file descriptor on success and -1 on failure. */ int tcp_cli(const char *host, const char *serv); /* * Opens a UDP socket bound on address 'lhost' and port 'lserv'. If neither * 'lhost' or 'lserv' is specified, then the socket is not bound at all. This * function returns the file descriptor on success and -1 on failure. */ int udp_sock(char *lhost, char *lserv); /* * Attempts to populate a socket address using an address, port and protocol. * The address and port must be specified at a minimum, but the port can be * NULL. In this case, the protocol will be set to whatever protocol is * first associated with "port" in the /etc/services file. Protocols "tcp" * and "udp" are supported values for this field. This function returns 0 * on success and -1 on a resolution failure. If the addr/port/proto * yields multiple socket addresses, this operation returns the first one * that the resolver returns. */ int net_resolv(const char *addr, const char *port, const char *proto, struct sockaddr_storage *sas); /* * Formats a socket address in a human readable null-terminated ASCII string * in 'buffer'. The 'len' parameter is the maximum length of buffer including * the terminator. This function returns the string on success or NULL if there * is an error with formatting. */ char * net_tostr(struct sockaddr *sa, char *buffer, size_t len); /* * Opens a client connection to address 'host' and port 'serv' on a new socket. * This API will attempt to connection on the first address found for a given * 'host', 'serv' pair. It opens the connection in non-blocking mode. The * caller should wait for the file descriptor to become writeable. Then the * caller should invoke tcp_cli_nb_complete() to determine if the connection * completed successfully. This function returns the socket file descriptor * on success and -1 on failure. aborts on a NULL host or serv. */ int tcp_cli_nb(const char *host, const char *serv); /* * Test whether a TCP client connection attempted with a non-blocking socket * completed. Aborts on a negative file descriptor. Returns the error flag * on the socket. Returns -1 on an error. */ int tcp_cli_nb_completion(int fd); #ifndef CAT_LISTENQ #define CAT_LISTENQ 50 #endif #endif /* CAT_HAS_POSIX */ #endif /* __cat_net_h */
github188/catlib
include/cat/bitset.h
/* * bitset.h -- Bitmap routines * * by <NAME> * * Copyright 2003-2017 -- See accompanying license * */ #ifndef __bitset_h #define __bitset_h #include <cat/cat.h> #if defined(CAT_USE_INLINE) && CAT_USE_INLINE #define DECL static inline #define CAT_BITSET_DO_DECL 1 #else /* CAT_USE_INLINE */ #define DECL #endif /* CAT_USE_INLINE */ #ifndef CAT_CHAR_BIT #define CAT_CHAR_BIT 8 #else #define CAT_CHAR_BIT CHAR_BIT #endif /* CHAR_BIT */ typedef uint bitset_t; #define CAT_UINT_BIT (sizeof(bitset_t) * CAT_CHAR_BIT) /* Calculate the number of elements in the bitset array */ #define BITSET_LEN(nbits) (((nbits) + (CAT_UINT_BIT-1)) / CAT_UINT_BIT) /* Declare a bit set named 'name' with 'nbits' bits */ #define DECLARE_BITSET(name, nbits) bitset_t name[BITSET_LEN(nbits)] /* Clear all entries in a bitset of length 'nbits' */ DECL void bset_zero(bitset_t *set, unsigned nbits); /* Set all entries in a bitset of length 'nbits' */ DECL void bset_fill(bitset_t *set, unsigned nbits); /* Copy 'src' to 'dst'. These two bitsets should have the same size: 'nbits' */ DECL void bset_copy(bitset_t *dst, bitset_t *src, unsigned nbits); /* Return non-zero if bit 'index' is set in 'set' or zero otherwise */ DECL int bset_test(bitset_t *set, unsigned index); /* Set bit 'index' in 'set' */ DECL void bset_set(bitset_t *set, unsigned index); /* Clear bit 'index' in 'set' */ DECL void bset_clr(bitset_t *set, unsigned index); /* Invert bit 'index' in 'set' */ DECL void bset_flip(bitset_t *set, unsigned index); /* Set bit 'index' in 'set' to 0 if 'val' is 0 or 1 otherwise */ DECL void bset_set_to(bitset_t *set, unsigned index, int val); /* ----- Implementation ----- */ #if defined(CAT_BITSET_DO_DECL) && CAT_BITSET_DO_DECL DECL void bset_zero(bitset_t *set, unsigned nbits) { unsigned i, len = BITSET_LEN(nbits); for ( i = 0 ; i < len ; ++i ) set[i] = 0; } DECL void bset_fill(bitset_t *set, unsigned nbits) { unsigned i, len = BITSET_LEN(nbits); for ( i = 0 ; i < len ; ++i ) set[i] = (uint)~0; } DECL void bset_copy(bitset_t *dst, bitset_t *src, unsigned nbits) { unsigned i, len = BITSET_LEN(nbits); if ( !len ) return; for ( i = 0 ; i < len - 1 ; ++i ) dst[i] = src[i]; i *= CAT_UINT_BIT; for ( ; i < nbits ; ++i ) bset_set_to(dst, i, bset_test(src, i)); } DECL int bset_test(bitset_t *set, unsigned index) { return (set[index / CAT_UINT_BIT] & (1 << (index % CAT_UINT_BIT))) != 0; } DECL void bset_set(bitset_t *set, unsigned index) { set[index / CAT_UINT_BIT] |= (1 << (index % CAT_UINT_BIT)); } DECL void bset_clr(bitset_t *set, unsigned index) { set[index / CAT_UINT_BIT] &= ~(1 << (index % CAT_UINT_BIT)); } DECL void bset_flip(bitset_t *set, unsigned index) { set[index / CAT_UINT_BIT] ^= (1 << (index % CAT_UINT_BIT)); } DECL void bset_set_to(bitset_t *set, unsigned index, int val) { if ( val ) bset_set(set, index); else bset_clr(set, index); } #endif /* defined(CAT_BITSET_DO_DECL) && CAT_BITSET_DO_DECL */ #undef DECL #undef CAT_LIST_DO_DECL #endif /* __bitset_h */
github188/catlib
src/stdcsv.c
/* * stdcsv.c -- nicer way to interface with CSV files built on csv.c * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #if CAT_HAS_POSIX #include <cat/stdcsv.h> #include <cat/stduse.h> #include <cat/grow.h> #include <string.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> static int local_getchar(void *fp) { int c; FILE *f = fp; errno = 0; c = fgetc(f); if ( c == EOF ) { if ( ferror(f) ) return CSV_GETC_ERR; else return CSV_GETC_EOF; } return c; } int csv_fopen(struct csv_state *csv, const char *filename) { FILE *f; if ( (f = fopen(filename, "r")) == NULL ) return CSV_ERR; csv_init(csv, local_getchar, f); return CSV_OK; } int csv_fclose(struct csv_state *csv) { if ( fclose(csv->csv_gcctx) < 0 ) return CSV_ERR; return CSV_OK; } int csv_read_field(struct csv_state *csv, char **res) { char *s = NULL; size_t slen = 32, soff = 0, t; int code; if ( (s = mem_get(&stdmm, slen)) == NULL ) return CSV_ERR; do { abort_unless(slen + 2 > slen); if ( soff > slen - 2 ) { byte_t *bp = (byte_t*)s; if ( mm_grow(&stdmm, &bp, &slen, slen + 2) < 0) { code = CSV_ERR; break; } s = (char *)bp; } code = csv_next(csv, &s[soff], slen - soff, &t); soff += t; } while ( code == CSV_CNT ); if ( code != CSV_ERR ) *res = s; else free(s); return code; } int csv_read_rec(struct csv_state *csv, struct csv_record *cr) { ulong nf, i; ulong rsz = 8; size_t size; int code = CSV_OK; char *field, **fields; byte_t *bp; abort_unless(csv != NULL); abort_unless(cr != NULL); fields = mem_get(&stdmm, sizeof(char *) * rsz); if ( fields == NULL ) return CSV_ERR; for ( nf = 0 ; (code != CSV_REC) && (code != CSV_EOF) ; ++nf ) { abort_unless(nf <= (ulong)~0); code = csv_read_field(csv, &field); if ( code == CSV_ERR ) goto err; else if ( code != CSV_EOF ) break; if ( nf == rsz ) { bp = (byte_t *)fields; size = rsz * sizeof(char *); if ( mm_grow(&stdmm, &bp, &size, size + sizeof(char *)) < 0) { code = CSV_ERR; goto err; } rsz = size / sizeof(char *); fields = (char **)bp; } fields[nf++] = field; } if ( code == CSV_EOF ) { abort_unless(nf == 0); return CSV_EOF; } cr->cr_nfields = nf; cr->cr_fields = fields; return CSV_REC; err: for ( i = 0; i < nf; ++i ) free(fields[i]); free(fields); return CSV_ERR; } void csv_free_rec(struct csv_record *cr) { int i; for ( i = 0 ; i < cr->cr_nfields ; ++i ) free(cr->cr_fields[i]); free(cr->cr_fields); memset(cr, 0, sizeof(*cr)); } #endif /* CAT_HAS_POSIX */
github188/catlib
attic/mem2.c
<gh_stars>1-10 /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> #include <cat/mem2.h> #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <string.h> #else #include <cat/catstdlib.h> #endif static struct hnode *nf_htnew(void *key, void *data, unsigned int hash, void *ctx); static void nf_htfree(struct hnode *, void *ctx); static struct anode *nf_avlnew(void *key, void *data, void *ctx); static void nf_avlfree(struct anode *, void *ctx); static struct rbnode *nf_rbnew(void *key, void *data, void *ctx); static void nf_rbfree(struct rbnode *, void *ctx); static void *plms_alloc(struct memsys *m, unsigned size) { struct pool *p; Assert(m); p = m->ms_ctx; Assert(p); return pl_alloc(p); } static void plms_free(struct memsys *m, void *mem) { Assert(m); if ( ! mem ) return; pl_free(m->ms_ctx, mem); } void pl_memsys(struct pool *p, struct memsys *m) { Assert(p); Assert(m); m->ms_ctx = p; m->ms_alloc = plms_alloc; m->ms_resize = NULL; m->ms_free = plms_free; } static void *pcms_alloc(struct memsys *m, unsigned size) { struct pcache *pc; Assert(m); pc = m->ms_ctx; Assert(pc); Assert(pc->asiz >= size); return pc_alloc(pc); } static void pcms_free(struct memsys *m, void *mem) { Assert(m); if ( ! mem ) return; pc_free(mem); } void pc_memsys(struct pcache *pc, struct memsys *m) { Assert(pc); Assert(m); m->ms_ctx = pc; m->ms_alloc = pcms_alloc; m->ms_resize = NULL; m->ms_free = pcms_free; } static struct hnode *nf_htnew(void *key, void *data, unsigned int hash, void *ctx) { struct nfactory *nf; struct hnode *hn; Assert(ctx); nf = ctx; hn = mem_get(nf->nf_msys, sizeof(struct hnode) + nf->nf_klen); if ( ! hn ) return NULL; ht_ninit(hn, (hn + 1), data, hash); memcpy(hn->key, key, nf->nf_klen); return hn; } static void nf_htfree(struct hnode *node, void *ctx) { struct nfactory *nf; Assert(ctx); Assert(node); nf = ctx; mem_free(nf->nf_msys, node); } void nf_initht(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp, hash_f hash, void *hctx) { Assert(nf); nf->nf_msys = m; nf->nf_klen = klen; nf->nf_hsys.cmp = cmp; nf->nf_hsys.hash = hash; nf->nf_hsys.hctx = hctx; nf->nf_hsys.hnnew = nf_htnew; nf->nf_hsys.hnfree = nf_htfree; nf->nf_hsys.nctx = nf; } static struct anode *nf_avlnew(void *key, void *data, void *ctx) { struct nfactory *nf; struct anode *an; Assert(ctx); nf = ctx; an = mem_get(nf->nf_msys, sizeof(struct anode) + nf->nf_klen); if ( ! an ) return NULL; avl_ninit(an, (an + 1), data); memcpy(an->key, key, nf->nf_klen); return an; } static void nf_avlfree(struct anode *node, void *ctx) { struct nfactory *nf; Assert(ctx); Assert(node); nf = ctx; mem_free(nf->nf_msys, node); } void nf_initavl(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp) { Assert(nf); nf->nf_msys = m; nf->nf_klen = klen; nf->nf_asys.cmp = cmp; nf->nf_asys.annew = nf_avlnew; nf->nf_asys.anfree = nf_avlfree; nf->nf_asys.actx = nf; } static struct rbnode *nf_rbnew(void *key, void *data, void *ctx) { struct nfactory *nf; struct rbnode *node; Assert(ctx); nf = ctx; node = mem_get(nf->nf_msys, sizeof(struct rbnode) + nf->nf_klen); if ( ! node ) return NULL; rb_ninit(node, (node + 1), data); memcpy(node->key, key, nf->nf_klen); return node; } static void nf_rbfree(struct rbnode *node, void *ctx) { struct nfactory *nf; Assert(ctx); Assert(node); nf = ctx; mem_free(nf->nf_msys, node); } void nf_initrb(struct nfactory *nf, int klen, struct memsys *m, cmp_f cmp) { Assert(nf); nf->nf_msys = m; nf->nf_klen = klen; nf->nf_rbsys.cmp = cmp; nf->nf_rbsys.rbnew = nf_rbnew; nf->nf_rbsys.rbfree = nf_rbfree; nf->nf_rbsys.ctx = nf; }
github188/catlib
test/testudpc.c
<reponame>github188/catlib<filename>test/testudpc.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <cat/err.h> #include <cat/net.h> int main(int argc, char *argv[]) { int fd, n; struct sockaddr_storage sas; socklen_t remlen; char buf[256], abuf[256]; ERRCK(fd = udp_sock(NULL, "0")); ERRCK(net_resolv("localhost", "10000", NULL, &sas)); for ( ; ; ) { if (fgets(buf, 255, stdin) == NULL ) { close(fd); return 1; } n = strlen(buf)+1; remlen = sizeof(sas); if ( sendto(fd, buf, n, 0, (SA *)&sas, remlen) < 0 ) errsys("sendto:\n\t"); ERRCK(n = recvfrom(fd, buf, 255, 0, (SA *)&sas, &remlen)); fprintf(stdout,"Received reply from %s\n", net_tostr((SA *)&sas, abuf, 256)); fprintf(stdout, "Got back %d bytes : %s", n, buf); } return 0; }
github188/catlib
attic/testreplace.c
<filename>attic/testreplace.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <cat/regex.h> void hurl() { printf("usage: testreplace search pattern replace\n"); exit(-1); } int main(int argc, char *argv[]) { char *new; if ( argc != 4 ) hurl(); new = re_sr(argv[1], argv[2], argv[3]); if ( ! new ) printf("Nothing returned!\n"); else printf("--\n%s\n--\n", new); free(new); return 0 ; }
github188/catlib
include/cat/grow.h
/* * grow.h -- Routines to grow dynamically allocated memory sensibly. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __grow_h #define __grow_h #include <cat/cat.h> #include <cat/mem.h> #ifndef CAT_MAXGROW #define CAT_MAXGROW ((size_t)~0) #endif #ifndef CAT_MINGROW #define CAT_MINGROW 32 #endif int grow(byte_t **ptr, size_t *len, size_t min); int agrow(void **ptr, size_t isiz, size_t *lenp, size_t min); int mm_grow(struct memmgr *mm, byte_t **ptr, size_t *len, size_t min); int mm_agrow(struct memmgr *mm, void **ptr, size_t isiz, size_t *lenp, size_t min); #endif /* __grow_h */
github188/catlib
test/testoptparse.c
<reponame>github188/catlib<filename>test/testoptparse.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/optparse.h> #include <cat/err.h> #include <stdio.h> #include <ctype.h> struct clopt g_optarr[] = { CLOPT_INIT(CLOPT_NOARG, 'a', "--opt-a", "option A (no arg)"), CLOPT_INIT(CLOPT_STRING, 'b', "--opt-b", "option B (string)"), CLOPT_INIT(CLOPT_INT, 'c', "--opt-c", "option C (int)"), CLOPT_INIT(CLOPT_UINT, 'd', "--opt-d", "option D (unsigned int)"), CLOPT_INIT(CLOPT_DOUBLE, 'e', "--opt-e", "option E (double)"), CLOPT_INIT(CLOPT_NOARG, 0, "--opt-f", "option F (no arg, no char)"), CLOPT_INIT(CLOPT_INT, 'g', NULL, "option G (int, no string)"), CLOPT_INIT(CLOPT_NOARG, 'h', "--help", "print help") }; struct clopt_parser g_options = CLOPTPARSER_INIT(g_optarr, array_length(g_optarr)); static void print_option(struct clopt *opt) { char ons[64]; const char *optname = clopt_name(opt, ons, sizeof(ons)); switch(opt->type) { case CLOPT_NOARG: printf("Option %s is set\n", optname); break; case CLOPT_STRING: printf("Option %s is set to '%s'\n", optname, opt->val.str_val); break; case CLOPT_INT: printf("Option %s is set to '%d'\n", optname, opt->val.int_val); break; case CLOPT_UINT: printf("Option %s is set to '%u'\n", optname,opt->val.uint_val); break; case CLOPT_DOUBLE: printf("Option %s is set to '%f'\n",optname,opt->val.dbl_val); break; default: err("Corrupted option %s", optname); } } int main(int argc, char *argv[]) { int argi; char buf[4096]; struct clopt *opt; optparse_print(&g_options, buf, sizeof(buf)); printf("usage: %s [options] [args]\n%s\n", argv[0], buf); optparse_reset(&g_options, argc, argv); while ( !(argi = optparse_next(&g_options, &opt)) ) { print_option(opt); } if ( argi < 0 ) { err("Error -- %s\n", g_options.errbuf); return -1; } for ( ; argi < argc ; ++argi ) printf("Argument: '%s'\n", argv[argi]); return 0; }
github188/catlib
include/cat/catstr.h
/* * catstr.h -- application level strings * * by <NAME> * * Copyright 2007-2012 -- See accompanying license * */ #ifndef __cat_catstr_h #define __cat_catstr_h #include <cat/cat.h> #include <cat/mem.h> #include <stdio.h> struct catstr { size_t cs_size; size_t cs_dlen; char cs_dynamic; char * cs_data; }; #define cs_alloc_size(dsiz) ((dsiz) + 1) #define cs_to_cstr(cs) ((cs)->cs_data) #define cs_isfull(cs) ((cs)->cs_dlen == (cs)->cs_size) #define CS_MAXLEN (((size_t)~0) - 3) #define CS_ERROR (CS_MAXLEN + 1) #define CS_NOTFOUND (CS_MAXLEN + 2) #define CS_DECLARE(name, len) CS_DECLARE_Q(, name, len) #define CS_DECLARE_Q(qual, name, len) \ qual char __csbuf__##name[cs_alloc_size(len)+sizeof(struct catstr)]={0};\ qual struct catstr name = { (len), 0, 0, __csbuf__##name } void cs_init(struct catstr *cs, char *data, size_t size, int data_is_str); void cs_clear(struct catstr *cs); size_t cs_set_cstr(struct catstr *cs, const char *cstr); size_t cs_trunc_d(struct catstr *cs, size_t len); size_t cs_concat_d(struct catstr *toappend, const struct catstr *scnd); size_t cs_copy_d(struct catstr *dst, struct catstr *src); size_t cs_format_d(struct catstr *dst, const char *fmt, ...); size_t cs_find_cc(const struct catstr *cs, char ch); size_t cs_span_cc(const struct catstr *cs, const char *accept); size_t cs_cspan_cc(const struct catstr *cs, const char *reject); size_t cs_find_uc(const struct catstr *cs, const char *utf8ch); size_t cs_span_uc(const struct catstr *cs, const char *utf8accept, int nc); size_t cs_cspan_uc(const struct catstr *cs, const char *utf8reject, int nc); struct catstr *cs_alloc(size_t len); void cs_free(struct catstr *cs); size_t cs_find(const struct catstr *findin, const struct catstr *find); size_t cs_find_str(const struct catstr *findin, const char *s); size_t cs_find_raw(const struct catstr *findin, const struct raw *r); struct catstr *cs_copy_from_chars(const char *s); struct catstr *cs_format(const char *fmt, ...); struct catstr *cs_copy(struct catstr *src); int cs_concat(struct catstr *dst, struct catstr *src); int cs_grow(struct catstr *cs, size_t maxlen); int cs_addch(struct catstr *cs, char ch); struct catstr *cs_substr(const struct catstr *cs, size_t off, size_t len); size_t cs_rev_off(const struct catstr *cs, size_t roff); #if CAT_HAS_POSIX int cs_fd_readline(int fd, struct catstr **csp); /* TODO: move out of here once we have input in the nolibc version*/ int cs_file_readline(FILE *file, struct catstr **csp); #endif /* CAT_HAS_POSIX */ /* returns -1 if there are outstanding dynamic strings with the current mm */ void cs_setmm(struct memmgr *mm); #endif /* __cat_catstr_h */
github188/catlib
src/catlibc.c
/* * catlibc.c -- local implementation of standard libc functions. * * by <NAME> * * Copyright 2003-2014 See accompanying license * */ #include <cat/cat.h> #include <cat/catlibc.h> /* We use several functions even if we don't use the standard library */ #if !CAT_USE_STDLIB #include <stdarg.h> #include <limits.h> #include <stdlib.h> /* should be my copy */ #include <string.h> /* should be my copy */ #include <ctype.h> /* should be my copy */ #include <limits.h> /* should be my copy */ #include <stdio.h> /* should be my copy */ #include <cat/emit.h> #include <cat/emit_format.h> STATIC_BUG_ON(strspn_bad_size_char, CHAR_BIT != 8); int memcmp(const void *b1p, const void *b2p, size_t len) { const uchar *b1 = b1p, *b2 = b2p; abort_unless(b1 && b2); while ( len > 0 && (*b1 == *b2) ) { b1++; b2++; len--; } if ( len ) return (int)*b1 - (int)*b2; else return 0; } void *memcpy(void *dst, const void *src, size_t len) { return memmove(dst, src, len); } void *memmove(void *dst, const void *src, size_t len) { const uchar *s; uchar *d; abort_unless(dst && src); if ( src < dst ) { s = src; d = dst; while (len--) *d++ = *s++; } else if ( src > dst ) { s = (const uchar *)src + len; d = (uchar *)dst + len; while (len--) *--d = *--s; } return dst; } void *memset(void *dst, int c, size_t len) { uchar *p = dst; while ( len-- ) *p = c; return dst; } size_t strlen(const char *s) { int n = 0; abort_unless(s); while (*s++) ++n; return n; } int strcmp(const char *c1, const char *c2) { abort_unless(c1 && c2); while ( *c1 == *c2 && *c1 != '\0' && *c2 != '\0' ) { c1++; c2++; } if ( *c1 == *c2 ) return 0; else if ( *c1 == '\0' ) return -1; else if ( *c2 == '\0' ) return 1; else return (int)*(uchar *)c1 - (int)*(uchar *)c2; } int strncmp(const char *c1, const char *c2, size_t n) { abort_unless(c1 && c2); while ( n > 0 && *c1 == *c2 && *c1 != '\0' && *c2 != '\0' ) { c1++; c2++; --n; } if ( n == 0 || *c1 == *c2 ) return 0; else if ( *c1 == '\0' ) return -1; else if ( *c2 == '\0' ) return 1; else return (int)*(uchar *)c1 - (int)*(uchar *)c2; } char *strchr(const char *s, int ch) { while ( *s != '\0' ) { if ( *s == ch ) return (char *)s; ++s; } return NULL; } char *strrchr(const char *s, int ch) { const char *last = NULL; while ( *s != '\0' ) if ( *s == ch ) last = s; return (char *)last; } char *strcpy(char *dst, const char *src) { char *dsave = dst; do { *dst++ = *src; } while ( *src++ != '\0' ); return dsave; } size_t strspn(const char *s, const char *accept) { uchar map[32] = { 0 }; const uchar *p = (const uchar *)accept; size_t spn = 0; while ( *p != '\0' ) { map[*p >> 3] |= 1 << (*p & 0x7); ++p; } p = (const char *)s; while ( (map[*p >> 3] & (1 << (*p & 0x7))) != 0 ) { p++; ++spn; } return spn; } size_t strcspn(const char *s, const char *reject) { uchar map[32] = { 0 }; const uchar *p = (const uchar *)reject; size_t spn = 0; /* we want to include the '\0' in the reject set */ do { map[*p >> 3] |= 1 << (*p & 0x7); } while ( *p++ != '\0' ); p = (const char *)s; while ( (map[*p >> 3] & (1 << (*p & 0x7))) == 0 ) { p++; ++spn; } return spn; } char *strdup(const char *s) { size_t slen = strlen(s) + 1; char *ns = malloc(slen); if (ns != NULL) memcpy(ns, s, slen); return ns; } int isalnum(int c) { return isalpha(c) || isdigit(c); } int isdigit(int c) { return c >= '0' && c <= '9'; } int isxdigit(int c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' || c <= 'F'); } int isspace(int c) { return c == ' ' || c == '\t'; } int isprint(int c) { return (c >= ' ' && c <= '~'); } int isalpha(int c) { int uc = toupper(c); return (uc >= 'A' && uc <= 'Z'); } int islower(int c) { return (c >= 'a' && c <= 'z'); } int isupper(int c) { return (c >= 'A' && c <= 'Z'); } int toupper(int c) { return (c >= 'a' && c <= 'z') ? c - ('a' - 'A') : c; } int tolower(int c) { return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; } long strtol(const char *start, char **cpp, int base) { long l; int minc, maxc, maxn, negate = 0, adigit = 0; char c; abort_unless(base >= 0 && base != 1 && base <= 36); if ( cpp ) *cpp = (char *)start; while ( *start == ' ' || *start == '\t' || *start == '\n' ) ++start; if ( *start == '+' ) ++start; else if ( *start == '-' ) { ++start; negate = 1; } if ( !base ) { if (*start == '0') { if ( *(start + 1) == 'x' ) base = 16; else base = 8; } else base = 10; } else { if ( (base == 8) && (*start == '0') ) start += 1; if ( (base == 16) && (*start == '0') && (*(start+1) == 'x') ) start += 2; } if ( base <= 10 ) { maxn = '0' + base - 1; minc = maxc = 0; } else { maxn = '9'; minc = 'a'; maxc = 'a' + base - 1; } l = 0; while (1) { c = *start; if ( c >= 'A' && c <= 'Z' ) c -= 'a' - 'A'; if ( ((c < '0') || (c > maxn)) && ((c < minc) || (c > maxc)) ) { if (cpp && adigit) *cpp = (char *)start; break; } adigit = 1; l *= base; if ( c >= '0' && c <= maxn ) l += c - '0'; else l += c - 'a'; start++; } if ( negate ) l = -l; return l; } ulong strtoul(const char *start, char **cpp, int base) { ulong l; int minc, maxc, maxn, negate = 0, adigit = 0; char c; abort_unless(base >= 0 && base != 1 && base <= 36); if ( cpp ) *cpp = (char *)start; while ( *start == ' ' || *start == '\t' || *start == '\n' ) ++start; if ( *start == '+' ) ++start; else if ( *start == '-' ) { ++start; negate = 1; } if ( !base ) { if ( *start == '0' ) { if ( *(start + 1) == 'x' ) base = 16; else base = 8; } else base = 10; } else { if ( (base == 8) && (*start == '0') ) start += 1; if ( (base == 16) && (*start == '0') && (*(start+1) == 'x') ) start += 2; } if ( base <= 10 ) { maxn = '0' + base - 1; minc = maxc = 0; } else { maxn = '9'; minc = 'a'; maxc = 'a' + base - 1; } l = 0; while (1) { c = *start; if ( c >= 'A' && c <= 'Z' ) c -= 'a' - 'A'; if ( ((c < '0') || (c > maxn)) && ((minc == 0) || (c < minc) || (c > maxc)) ) { if (cpp && adigit) *cpp = (char *)start; break; } adigit = 1; l *= base; if ( c >= '0' && c <= maxn ) l += c - '0'; else l += c - 'a'; start++; } if ( negate ) l = -l; return l; } /* TODO Range checking */ double strtod(const char *start, char **cpp) { #if CAT_HAS_FLOAT double v = 0.0, e; int negate = 0; char *cp; int exp; int adigit = 0; if ( cpp ) *cpp = (char *)start; while ( isspace(*start) || *start == '\r' || *start == '\n' ) ++start; if ( *start == '+' ) ++start; else if ( *start == '-' ) { ++start; negate = 1; } while (1) { /* TODO: range checking */ if ( *start < '0' || *start > '9' ) break; adigit = 1; v = v * 10 + *start - '0'; } if ( !adigit ) return 0.0; if ( negate ) v = -v; if ( *start == '.' ) { ++start; e = 0.1; while (1) { /* TODO: range checking */ if ( *start < '0' || *start > '9' ) break; v += (*start - '0') * e; e *= 0.1; } } if ( *start == 'e' || *start == 'E' ) { ++start; exp = strtol(start, &cp, 10); /* TODO: decide what to do about these min and max values */ if ( start == cp || exp < -64 || exp > 64 ) { if ( cpp ) *cpp = (char *)start - 1; return v; } if ( exp < 0 ) { while ( exp++ < 0 ) v /= 10.0; } else { while ( exp-- < 0 ) v *= 10.0; } start = cp; } if ( cpp ) { if ( *(start - 1) == '.' ) *cpp = (char *)start - 1; else *cpp = (char *)start; } return v; #else /* CAT_HAS_FLOAT */ return 0.0; #endif /* CAT_HAS_FLOAT */ } /* stdlib.c -- malloc(), free(), realloc(), calloc() ... */ #include <cat/dynmem.h> static struct dynmem dmheap; void *malloc(size_t amt) { return dynmem_malloc(&dmheap, amt); } void free(void *mem) { dynmem_free(&dmheap, mem); } void *calloc(size_t nmem, size_t osiz) { size_t len; void *m; if ( nmem == 0 ) return NULL; #if CAT_HAS_DIV if ( osiz > (size_t)~0 / nmem ) return NULL; #else if ( osiz > uldivmod((size_t)~0, nmem, 1) ) return NULL; #endif len = osiz * nmem; m = malloc(len); if ( m ) memset(m, 0, len); return m; } void *realloc(void *omem, size_t newamt) { return dynmem_realloc(&dmheap, omem, newamt); } /* TODO: replace this with something more reliable */ static int exit_status = 0; /* For debuggers to be able to inspect */ void exit(int status) { exit_status = status; abort(); } /* TODO: replace this with something more reliable */ void abort(void) { int a; /* Actions that tend to cause aborts in compiler implementations */ a = *(char *)0; /* Null pointer dereference */ #if CAT_HAS_DIV /* Divide by 0: convludted to shut up compiler */ a = 1; while ( a > 0 ) --a; a = 100 / a; #endif /* CAT_HAS_DIV */ /* worst case scenario: endless loop */ for (;;) ; } #define MAXFILES 32 #define CAT_STDIN_FILENO 0 #define CAT_STDOUT_FILENO 1 #define CAT_STDERR_FILENO 2 static char Stdin_buf[BUFSIZ]; static char Stdout_buf[BUFSIZ]; static char Stderr_buf[BUFSIZ]; static FILE File_table[MAXFILES] = { { Stdin_buf, sizeof(Stdin_buf), 0, _IOFBF|CAT_SIO_READ|CAT_SIO_BUFGIVEN, CAT_STDIN_FILENO, 0 }, { Stdout_buf, sizeof(Stdout_buf), 0, _IOFBF|CAT_SIO_WRITE|CAT_SIO_BUFGIVEN, CAT_STDOUT_FILENO, 0 }, { Stderr_buf, sizeof(Stderr_buf), 0, _IONBF|CAT_SIO_WRITE|CAT_SIO_BUFGIVEN, CAT_STDERR_FILENO, 0 }, { 0 } }; FILE *stdin = &File_table[0]; FILE *stdout = &File_table[1]; FILE *stderr = &File_table[2]; FILE *fopen(const char *path, const char *mode) { return NULL; } FILE *freopen(const char *path, const char *mode, FILE *file) { if ( fflush(file) < 0 ) return NULL; fclose(file); return NULL; } static size_t do_fput_bytes(FILE* file, const char *buf, size_t len) { if ( file == NULL || (len > 0 && (buf == NULL || file->f_buffer == NULL)) ) { if ( file != NULL ) file->f_flags |= CAT_SIO_ERR; return 0; } abort_unless(file->f_fill <= file->f_buflen); if ( len > file->f_buflen - file->f_fill ) len = file->f_buflen - file->f_fill; memcpy(&file->f_buffer[file->f_fill], buf, len); file->f_fill += len; file->f_lastop = CAT_SIO_WRITE; return len; } static int flush_all() { FILE *fp, *end = File_table + MAXFILES; for ( fp = File_table ; fp < end ; ++fp ) if ( fflush(fp) < 0 ) return -1; return 0; } int fflush(FILE *file) { size_t rv; if ( file == NULL ) return flush_all(); if ( file->f_lastop == CAT_SIO_WRITE ) { if ( file->f_fill > 0 ) { rv = do_fput_bytes(file, file->f_buffer, file->f_fill); if ( rv < file->f_fill ) return -1; file->f_fill = 0; } } else { /* TODO: once we get read operations */ } return 0; } int fclose(FILE *file) { if ( fflush(file) < 0 ) return -1; #if CAT_HAS_POSIX if ( close(file->f_fd) < 0 ) return -1; #endif /* CAT_HAS_POSIX */ if ( file->f_buffer != NULL && (file->f_flags & CAT_SIO_BUFGIVEN) == 0 ) { free(file->f_buffer); } file->f_buffer = NULL; file->f_buflen = 0; file->f_flags = _IOUNUSED; return 0; } void clearerr(FILE *file) { if ( file == NULL ) return; file->f_flags &= ~CAT_SIO_ERR; } int feof(FILE *file) { if ( file == NULL ) return -1; return (file->f_flags & CAT_SIO_EOF) != 0; } int ferror(FILE *file) { if ( file == NULL ) return -1; return (file->f_flags & CAT_SIO_ERR) != 0; } int fileno(FILE *file) { if ( file == NULL ) return -1; return file->f_fd; } size_t fwrite(const void *ptr, size_t msiz, size_t nmem, FILE *file) { size_t i, rv; const char *buf = ptr; if ( msiz == 0 || nmem == 0 ) return 0; if ( ptr == NULL || file == NULL ) return 0; for ( i = 0 ; i < nmem ; ++i ) { rv = do_fput_bytes(file, buf, msiz); if ( rv == 0 ) return i; buf += msiz; } return i; } int fputc(int c, FILE *file) { char ch = c; int rv; rv = do_fput_bytes(file, &ch, sizeof(ch)); if ( rv < 0 ) return EOF; return c; } int fputs(const char *s, FILE *file) { size_t rv; rv = do_fput_bytes(file, s, strlen(s)); return (rv == 0) ? -1 : 0; } int putc(int c, FILE *file) { return fputc(c, file); } int putchar(int c) { return fputc(c, stdout); } int puts(const char *s) { return fputs(s, stdout); } size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file) { /* TODO */ if ( file != NULL ) { if ( file->f_flags & CAT_SIO_READ ) file->f_flags |= CAT_SIO_EOF; else file->f_flags |= CAT_SIO_ERR; } return 0; } void setbuf(FILE *file, char *buf) { setvbuf(file, buf, buf ? _IOFBF : _IONBF, BUFSIZ); } void setbuffer(FILE *file, char *buf, size_t size) { setvbuf(file, buf, buf ? _IOFBF : _IONBF, size); } void setlinebuf(FILE *file) { setvbuf(file, NULL, _IOLBF, 0); } int setvbuf(FILE *file, char *buf, int mode, size_t bsiz) { if ( file == NULL ) return -1; if ( mode != _IONBF && mode != _IOLBF && mode != _IOFBF ) return -1; /* enforce the rule that buffering must be performed between initial */ /* open and any subsequent operations */ if ( file->f_lastop ) return -1; if ( file->f_fill > 0 && fflush(file) < 0 ) return -1; if ( bsiz > INT_MAX ) return -1; file->f_flags &= _IOBFMASK; file->f_flags |= mode; if ( buf != NULL ) { abort_unless(bsiz > 0); file->f_flags = CAT_SIO_BUFGIVEN; file->f_buffer = buf; file->f_buflen = bsiz; } return 0; } int printf(const char *fmt, ...) { va_list ap; int rv; va_start(ap, fmt); rv = vfprintf(stdout, fmt, ap); va_end(ap); return rv; } int fprintf(FILE *file, const char *fmt, ...) { va_list ap; int rv; va_start(ap, fmt); rv = vfprintf(file, fmt, ap); va_end(ap); return rv; } int vprintf(const char *fmt, va_list ap) { return vfprintf(stdout, fmt, ap); } struct file_emitter { struct emitter emitter; FILE * file; }; int file_emit_func(struct emitter *e, const void *buf, size_t len) { size_t rv; struct file_emitter *fe = (struct file_emitter *)e; abort_unless(e && buf); if ( (rv = do_fput_bytes(fe->file, buf, len)) == 0 ) { e->emit_state = EMIT_ERR; return -1; } return rv; } int vfprintf(FILE *file, const char *fmt, va_list ap) { struct file_emitter e = { {EMIT_OK, file_emit_func}, NULL }; abort_unless(file && fmt); e.file = file; return emit_vformat(&e.emitter, fmt, ap); } int vsnprintf(char *buf, size_t len, const char *fmt, va_list ap) { int rlen; struct string_emitter se; char tbuf[1] = { '\0' }; abort_unless(buf && fmt); if ( len <= 1 ) return 0; 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 vsprintf(char *buf, const char *fmt, va_list ap) { return vsnprintf(buf, (size_t)~0, fmt, ap); } int snprintf(char *buf, size_t len, const char *fmt, ...) { struct string_emitter se; va_list ap; int rlen; abort_unless(buf && fmt); if ( len <= 1 ) return 0; va_start(ap, fmt); string_emitter_init(&se, buf, len); rlen = emit_vformat(&se.se_emitter, fmt, ap); string_emitter_terminate(&se); va_end(ap); return rlen; } int sprintf(char *buf, const char *fmt, ...) { int rlen; va_list ap; va_start(ap, fmt); rlen = vsprintf(buf, fmt, ap); va_end(ap); return rlen; } int fgetc(FILE *file) { /* TODO: not yet implemented */ return EOF; } /* --------- initialize all cat standard library manually -------- */ void catlibc_reset(struct catlibc_cfg *cprm) { if ( cprm->heap_base != NULL && cprm->heap_sz > 0 ) { dynmem_init(&dmheap); dynmem_add_pool(&dmheap, cprm->heap_base, cprm->heap_sz); } else { dmheap.dm_init = 0; } exit_status = 0; stdin = &File_table[0]; stdin->f_buffer = cprm->stdin_buf; stdin->f_buflen = cprm->stdin_bufsz; stdin->f_fill = 0; stdin->f_flags = _IOFBF|CAT_SIO_READ|CAT_SIO_BUFGIVEN; stdin->f_fd = CAT_STDIN_FILENO; stdin->f_lastop = 0; stdout = &File_table[1]; stdout->f_buffer = cprm->stdout_buf; stdout->f_buflen = cprm->stdout_bufsz; stdout->f_fill = 0; stdout->f_flags =_IOFBF|CAT_SIO_WRITE|CAT_SIO_BUFGIVEN; stdout->f_fd = CAT_STDOUT_FILENO; stdout->f_lastop = 0; stderr = &File_table[2]; stderr->f_buffer = cprm->stderr_buf; stderr->f_buflen = cprm->stderr_bufsz; stderr->f_fill = 0; stderr->f_flags =_IONBF|CAT_SIO_WRITE|CAT_SIO_BUFGIVEN; stderr->f_fd = CAT_STDERR_FILENO; stderr->f_lastop = 0; if ( MAXFILES > 3 ) memset(&File_table[3], 0, sizeof(FILE) * (MAXFILES - 3)); } #endif /* !CAT_USE_STDLIB */
github188/catlib
src/graph.c
/* * graph.c -- generic graph data structure representation. * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/graph.h> #define CAT_GRAPH_INIT_EDGE_LEN 16 static void del_edge_help(struct gr_edge *edge, struct gr_node *node, int fromout); static int add_edge_help(struct gr_edge *edge, struct gr_edge_arr *ea, struct gr_edge_arr *ea2); struct graph *gr_new(struct memmgr *mm, int isbi, uint nxsize, uint exsize) { struct graph *g; if ( !mm ) return NULL; nxsize = attrib_csize(struct gr_node, grn_u, nxsize); exsize = attrib_csize(struct gr_edge, gre_u, exsize); if ( nxsize < sizeof(struct gr_node) || exsize < sizeof(struct gr_edge) ) return NULL; g = mem_get(mm, sizeof(*g)); if ( !g ) return NULL; l_init(&g->nodes); l_init(&g->edges); g->isbi = isbi; g->mm = mm; g->nsize = nxsize; g->esize = exsize; return g; } struct gr_node * gr_add_node(struct graph *g) { struct gr_node *n; abort_unless(g && g->mm); n = mem_get(g->mm, g->nsize); if ( !n ) return NULL; n->graph = g; n->out.fill = n->in.fill = 0; n->out.len = n->in.len = CAT_GRAPH_INIT_EDGE_LEN; n->out.arr = mem_get(g->mm, sizeof(struct gr_edge*) * CAT_GRAPH_INIT_EDGE_LEN); if ( !n->out.arr ) { mem_free(g->mm, n); return NULL; } if ( !g->isbi ) { n->in.arr = mem_get(g->mm, sizeof(struct gr_edge*) * CAT_GRAPH_INIT_EDGE_LEN); if ( !n->in.arr ) { mem_free(g->mm, n->out.arr); mem_free(g->mm, n); return NULL; } } else { n->in.arr = n->out.arr; } l_ins(&g->nodes, &n->entry); return n; } static int add_edge_help(struct gr_edge *edge, struct gr_edge_arr *ea, struct gr_edge_arr *ea2) { uint i; struct graph *g; g = edge->n1->graph; for ( i = 0 ; i < ea->fill ; ++i ) { if ( !ea->arr[i] ) { ea->arr[i] = edge; return 0; } } if ( ea->fill == ea->len ) { struct gr_edge **newarr; size_t newlen; /* need to grow the array */ abort_unless(ea->len <= ((size_t)~0) >> 1); newlen = ea->len << 1; abort_unless(newlen <= ((size_t)~0) / sizeof(struct gr_edge*)); newarr = mem_resize(g->mm, ea->arr, newlen * sizeof(struct gr_edge*)); if ( !newarr ) return -1; ea->arr = newarr; ea->len = newlen; } ea->arr[ea->fill++] = edge; if ( ea2 ) *ea2 = *ea; return 0; } struct gr_edge * gr_add_edge(struct gr_node *from, struct gr_node *to) { struct graph *g; struct gr_edge *edge; abort_unless(from && to); g = from->graph; abort_unless(g && g == to->graph && g->mm); edge = mem_get(g->mm, g->esize); if ( !edge ) return NULL; l_ins(&g->edges, &edge->entry); edge->n1 = from; edge->n2 = to; /* insert into arrays: grow if necessary */ if ( add_edge_help(edge, &from->out, g->isbi ? &from->in : NULL) < 0 ) { mem_free(g->mm, edge); return NULL; } if ( from != to || !g->isbi ) { if ( add_edge_help(edge, &to->in, g->isbi ? &to->out : NULL ) < 0 ) { /* XXX double check that this is ok */ del_edge_help(edge, edge->n1, 1); mem_free(g->mm, edge); return NULL; } } return edge; } struct gr_edge * gr_find_edge(struct gr_node *from, struct gr_node *to) { struct graph *g; uint i, isbi; struct gr_edge **epp; abort_unless(from); abort_unless(to); g = from->graph; abort_unless(g); abort_unless(g == to->graph); isbi = g->isbi; for ( i = 0, epp = from->out.arr ; i < from->out.fill ; ++i, ++epp ) if ( *epp && (((*epp)->n2 == to) || (isbi && (*epp)->n1 == to)) ) return *epp; return NULL; } void gr_del_node(struct gr_node *node) { struct gr_edge **edge; struct graph *g; uint i; abort_unless(node); g = node->graph; abort_unless(g && g->mm); for ( i = 0, edge = node->out.arr ; i < node->out.fill ; ++i, ++edge ) if ( *edge ) gr_del_edge(*edge); mem_free(g->mm, node->out.arr); if ( !g->isbi ) { for ( i = 0, edge = node->in.arr ; i < node->in.fill ; ++i, ++edge ) if ( *edge ) gr_del_edge(*edge); mem_free(g->mm, node->in.arr); } l_rem(&node->entry); node->graph = NULL; mem_free(g->mm, node); } static void del_edge_help(struct gr_edge *edge, struct gr_node *node, int fromout) { struct gr_edge **epp; uint i, fill; struct graph *g; g = node->graph; abort_unless(g && g->mm); if ( fromout ) { epp = node->out.arr; fill = node->out.fill; } else { epp = node->in.arr; fill = node->in.fill; } for ( i = 0 ; i < fill ; ++i, ++epp ) { if ( *epp == edge ) { *epp = NULL; break; } } abort_unless(i < fill); if ( i == fill - 1 ) { struct gr_edge_arr *ea = fromout ? &node->out : &node->in; while ( ea->fill > 0 && !ea->arr[ea->fill - 1] ) --ea->fill; if ( node->graph->isbi ) { if ( fromout ) node->in.fill = node->out.fill; else node->out.fill = node->in.fill; } } l_rem(&edge->entry); } void gr_del_edge(struct gr_edge *edge) { struct graph *g; abort_unless(edge && edge->n1 && edge->n2); g = edge->n1->graph; abort_unless(g && g->mm); del_edge_help(edge, edge->n1, 1); if ( (edge->n1 != edge->n2) || !g->isbi ) del_edge_help(edge, edge->n2, 0); mem_free(g->mm, edge); } void gr_free(struct graph *g) { struct gr_node *node; abort_unless(g && g->mm); while ( !l_isempty(&g->nodes) ) { node = container(l_head(&g->nodes), struct gr_node, entry); gr_del_node(node); } mem_free(g->mm, g); } struct gr_node * gr_edge_dst(const struct gr_node *node, const struct gr_edge *edge) { abort_unless(node && node->graph); abort_unless(edge); if ( node->graph->isbi && edge->n2 == node ) return edge->n1; else return edge->n2; }
github188/catlib
src/stdclio.c
/* * stdclio.c -- standard IO implementation of emtter API. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/stdclio.h> #include <stdio.h> int file_emit_func(struct emitter *em, const void *buf, size_t len) { struct file_emitter *fe = (struct file_emitter *)em; if ( len == 0 ) return 0; fwrite(buf, 1, len, fe->fe_file); if ( ferror(fe->fe_file) ) { fe->fe_emitter.emit_state = EMIT_ERR; return -1; } return 0; } void file_emitter_init(struct file_emitter *fe, FILE *file) { struct emitter *e; abort_unless(fe && file); e = &fe->fe_emitter; e->emit_state = EMIT_OK; e->emit_func = file_emit_func; fe->fe_file = file; } int file_emitter_open(struct file_emitter *fe, const char *fname, int append) { FILE *fp; abort_unless(fe); if ( (fp = fopen(fname, (append ? "a" : "r"))) == NULL ) return -1; file_emitter_init(fe, fp); return 0; } int file_emitter_close(struct file_emitter *fe) { abort_unless(fe && fe->fe_file); return fclose(fe->fe_file); } static int finp_read(struct inport *in, void *buf, int len) { struct file_inport *fin = (struct file_inport *)in; size_t nr; abort_unless(fin->file); if ( ferror(fin->file) ) return -1; if ( feof(fin->file) ) return 0; nr = fread(buf, len, 1, fin->file); if ( nr < len ) { if ( ferror(fin->file) ) return -1; len = nr; } return nr; } static int finp_close(struct inport *in) { struct file_inport *fin = (struct file_inport *)in; int rv; if ( fin->file == NULL ) return 0; rv = fclose(fin->file); if ( rv == 0 ) fin->file = NULL; return rv; } void finp_init(struct file_inport *fin, FILE *fp) { abort_unless(fin && fp); fin->in.read = &finp_read; fin->in.close = &finp_close; fin->file = fp; } #if CAT_HAS_POSIX #include <sys/types.h> #include <unistd.h> #include <errno.h> static int fd_emit_func(struct emitter *ectx, const void *buf, size_t len) { size_t nwritten = 0; ssize_t rv; int fd = ((struct fd_emitter *)ectx)->fde_fd; const uchar *data = buf; while ( nwritten < len ) { rv = write(fd, data + nwritten, len - nwritten); if ( rv == -1 ) { if ( errno == EINTR ) continue; ectx->emit_state = EMIT_ERR; return -1; } else { nwritten += (size_t)rv; } } return 0; } void fd_emitter_init(struct fd_emitter *fde, int fd) { struct emitter *e; abort_unless(fde); abort_unless(fd >= 0); e = &fde->fde_emitter; e->emit_state = EMIT_OK; e->emit_func = fd_emit_func; fde->fde_fd = fd; } static int fdinp_read(struct inport *in, void *buf, int len) { struct fd_inport *fdin = (struct fd_inport *)in; abort_unless(fdin->fd >= 0); return read(fdin->fd, buf, len); } static int fdinp_close(struct inport *in) { struct fd_inport *fdin = (struct fd_inport *)in; int rv; if ( fdin->fd < 0 ) return 0; rv = close(fdin->fd); if ( rv == 0 ) fdin->fd = -1; return rv; } void fd_inport_init(struct fd_inport *fdin, int fd) { abort_unless(fdin && fd >= 0); fdin->in.read = &fdinp_read; fdin->in.close = &fdinp_close; fdin->fd = fd; } #endif /* CAT_HAS_POSIX */
github188/catlib
src/peg.c
<filename>src/peg.c #include <cat/cat.h> #include <cat/aux.h> #include <cat/str.h> #include <cat/peg.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <ctype.h> /* * This is the PEG grammar format in PEG format: * * # Hierarchical syntax * Grammar <- Spacing Definition+ EndOfFile * Definition <- Identifier LEFTARROW Expression * Expression <- Sequence (SLASH Sequence)* * Sequence <- Prefix* * Prefix <- (AND / NOT)? Suffix * # XXX Codeblock? added: see below XXX * Suffix <- Primary (QUESTION / STAR / PLUS)? (Codeblock / ActionLabel)? * Primary <- Identifier !LEFTARROW * / OPEN Expression CLOSE * / Literal / Class / DOT * * # XXX * # Added for parser generation: contains the C code to run on match * # * Codeblock <- '{' (Codenonstring / Literal / CComment)* '}' * Codenonstring <- !["'] . * CComment <- "/ *" (!"* /" .)* "* /" * # No spaces-^----------^------^ * # Added to embed in C comments * ActionLabel <- ':' Identifier * # XXX * * # Lexical syntax * Identifier <- IdentStart IdentCont* Spacing * IdentStart <- [a-zA-Z_] * IdentCont <- IdentStart / [0-9] * Literal <- [’] (![’] Char)* [’] Spacing * / ["] (!["] Char)* ["] Spacing * Class <- ’[’ (!’]’ Range)* ’]’ Spacing * Range <- Char ’-’ Char / Char * Char <- ’\\’ [nrt’"\[\]\\] * / ’\\’ [0-2][0-7][0-7] * / ’\\’ [0-7][0-7]? * / !’\\’ . * * LEFTARROW <- ’<-’ Spacing * SLASH <- ’/’ Spacing * AND <- ’&’ Spacing * NOT <- ’!’ Spacing * QUESTION <- ’?’ Spacing * STAR <- ’*’ Spacing * PLUS <- ’+’ Spacing * OPEN <- ’(’ Spacing * CLOSE <- ’)’ Spacing * DOT <- ’.’ Spacing * Spacing <- (Space / Comment)* * Comment <- ’#’ (!EndOfLine .)* EndOfLine * Space <- ’ ’ / ’\t’ / EndOfLine * EndOfLine <- ’\r\n’ / ’\n’ / ’\r’ * EndOfFile <- !. */ #define STR(_pgp, _cursor) ((_pgp)->input + (_cursor)->pos) #define CHAR(_pgp, _cursor) ((_pgp)->input[(_cursor)->pos]) #define CHARI(_pgp, _cursor, _off) ((_pgp)->input[(_cursor)->pos + (_off)]) #define node2idx(_peg, _node) ((_node) - (_peg)->nodes) #define NODE(_peg, _i) (&(_peg)->nodes[(_i)]) static int initialized = 0; static byte_t cs_space[32]; static byte_t cs_eol[32]; static byte_t cs_id_start[32]; static byte_t cs_id_cont[32]; static byte_t cs_special[32]; static byte_t cs_digit0to2[32]; static byte_t cs_digit0to7[32]; static byte_t cs_ccode[32]; static struct peg_node *find_id(struct peg_grammar *peg, struct raw *r) { int i; for ( i = 0; i < peg->max_nodes; ++i ) if ( pn_is_type(peg, i, PEG_IDENTIFIER) && !cmp_raw(r, &NODE(peg, i)->pi_name) ) return NODE(peg, i); return NULL; } static void free_str(struct raw *r) { free(r->data); r->data = NULL; r->len = 0; } static void peg_node_free(struct peg_grammar *peg, int nn) { struct peg_node *pn; if ( nn < 0 || nn >= peg->max_nodes ) return; pn = NODE(peg, nn); switch ( pn->pn_type ) { case PEG_DEFINITION: peg_node_free(peg, pn->pd_id); peg_node_free(peg, pn->pd_expr); break; case PEG_SEQUENCE: peg_node_free(peg, pn->ps_pri); peg_node_free(peg, pn->pn_next); break; case PEG_PRIMARY: peg_node_free(peg, pn->pp_match); peg_node_free(peg, pn->pn_next); if ( pn->pp_action != PEG_ACT_NONE ) free_str(&pn->pp_label); break; case PEG_IDENTIFIER: --pn->pi_refcnt; if ( pn->pi_refcnt > 0 ) return; free_str(&pn->pi_name); break; case PEG_LITERAL: free_str(&pn->pl_value); break; case PEG_CLASS: free_str(&pn->pc_cset_raw); break; default: return; } abort_unless(peg->num_nodes > 0); --peg->num_nodes; pn->pn_type = PEG_NONE; } static int peg_node_new(struct peg_grammar *peg, int type, uint line) { struct peg_node *new_nodes; struct peg_node *pn; size_t osize, nsize; uint i; uint start; if ( peg->num_nodes == peg->max_nodes ) { if ( !peg->dynamic ) return -1; start = peg->max_nodes; if ( peg->max_nodes == 0 ) { peg->max_nodes = 8; nsize = 16 * sizeof(struct peg_node); } else { osize = peg->max_nodes * sizeof(struct peg_node); nsize = osize * 2; if ( nsize < osize || peg->max_nodes > INT_MAX / 2 ) return -1; } new_nodes = realloc(peg->nodes, nsize); if ( new_nodes == NULL ) return -1; peg->nodes = new_nodes; peg->max_nodes *= 2; for ( i = start; i < peg->max_nodes; ++i ) NODE(peg, i)->pn_type = PEG_NONE; } abort_unless(pn_is_type(peg, peg->num_nodes, PEG_NONE)); i = peg->num_nodes++; pn = NODE(peg, i); pn->pn_type = type; pn->pn_line = line; pn->pn_next = -1; pn->pn_subnode = -1; pn->pn_status = 0; pn->pn_action_cb = NULL; return i; } static void skip_space(struct peg_grammar_parser *pgp, struct peg_cursor *pc) { int in_comment = 0; while ( in_comment || CHAR(pgp, pc) == '#' || cset_contains(cs_space, CHAR(pgp, pc)) ) { if ( CHAR(pgp, pc) == '#' ) { in_comment = 1; } else if ( cset_contains(cs_eol, CHAR(pgp, pc)) ) { pc->line += 1; if ( CHAR(pgp, pc) == '\r' && CHARI(pgp, pc, 1) == '\n' ) pc->pos += 1; in_comment = 0; } pc->pos += 1; } } static int string_match(struct peg_grammar_parser *pgp, const char *pat, struct peg_cursor *pc) { uint plen; plen = strlen(pat); abort_unless(pgp->input_len >= pc->pos); if ( plen > pgp->input_len - pc->pos ) return 0; if ( strncmp(STR(pgp, pc), pat, plen) == 0 ) { pc->pos += plen; skip_space(pgp, pc); return 1; } else { return 0; } } static int copy_str(struct peg_grammar_parser *pgp, struct peg_cursor *pc, size_t len, struct raw *r) { r->data = malloc(len + 1); if ( r->data == NULL ) { pgp->err = PEG_ERR_NOMEM; return -1; } r->len = len; memcpy(r->data, STR(pgp, pc), len); r->data[len] = '\0'; return 0; } static int parse_id(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *idp) { int id; struct peg_node *pn; struct peg_grammar *peg = pgp->peg; struct raw name; if ( !cset_contains(cs_id_start, CHAR(pgp, pc)) ) return 0; name.data = (char *)STR(pgp, pc); name.len = 1 + str_spn(name.data + 1, cs_id_cont); pn = find_id(peg, &name); if ( pn != NULL ) { ++pn->pi_refcnt; } else { id = peg_node_new(peg, PEG_IDENTIFIER, pc->line); if ( id < 0 ) { pgp->err = PEG_ERR_NOMEM; return -1; } pn = NODE(peg, id); if ( copy_str(pgp, pc, name.len, &pn->pi_name) < 0 ) { pgp->err = PEG_ERR_NOMEM; peg_node_free(peg, id); return -1; } pn->pi_def = -1; pn->pi_refcnt = 1; } *idp = node2idx(peg, pn); pc->pos += name.len; skip_space(pgp, pc); return 1; } static int parse_id_and_not_arrow(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *idp) { int rv; struct peg_cursor npc1 = *pc; struct peg_cursor npc2; int id; rv = parse_id(pgp, &npc1, &id); if ( rv <= 0 ) return rv; npc2 = npc1; if ( string_match(pgp, "<-", &npc2) ) { peg_node_free(pgp->peg, id); return 0; } *pc = npc1; *idp = id; return 1; } static int parse_expr(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *seqp); static int parse_paren_expr(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *exprp) { int rv; struct peg_cursor npc = *pc; int expr = -1; if ( !string_match(pgp, "(", &npc) ) return 0; rv = parse_expr(pgp, &npc, &expr); if ( rv < 0 ) return -1; if ( rv == 0 ) goto err; if ( !string_match(pgp, ")", &npc) ) goto err; *pc = npc; *exprp = expr; return 1; err: peg_node_free(pgp->peg, expr); pgp->err = PEG_ERR_BAD_PAREXPR; pgp->eloc = npc; return -1; } static int parse_char(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *cp) { int c; struct peg_cursor npc = *pc; c = CHAR(pgp, &npc); if ( c == '\0' ) return 0; if ( c != '\\' ) { pc->pos += 1; if ( cset_contains(cs_eol, c) ) { pc->line += 1; if ( c == '\r' && CHAR(pgp, pc) == '\n' ) pc->pos += 1; } *cp = c; return 1; } npc.pos += 1; c = CHAR(pgp, &npc); if ( c == '\0' ) { pgp->err = PEG_ERR_BAD_CHAR; pgp->eloc = npc; return -1; } if ( cset_contains(cs_special, c) ) { switch (c) { case 'n': *cp = '\n'; break; case 'r': *cp = '\r'; break; case 't': *cp = '\t'; break; case '\'': *cp = '\''; break; case '"': *cp = '"'; break; case '[': *cp = '['; break; case ']': *cp = ']'; break; case '\\': *cp = '\\'; break; } npc.pos += 1; *pc = npc; return 1; } if ( !cset_contains(cs_digit0to7, c) ) { pgp->err = PEG_ERR_BAD_CHAR; pgp->eloc = *pc; return -1; } if ( cset_contains(cs_digit0to2, c) && cset_contains(cs_digit0to7, CHARI(pgp, &npc, 1)) && cset_contains(cs_digit0to7, CHARI(pgp, &npc, 2)) ) { c = ((c - '0') << 6) | ((CHARI(pgp, &npc, 1) - '0') << 3) | (CHARI(pgp, &npc, 2) - '0'); npc.pos += 3; } else { c = c - '0'; npc.pos += 1; if ( cset_contains(cs_digit0to7, CHAR(pgp, &npc)) ) { c = (c << 3) | (CHAR(pgp, &npc) - '0'); npc.pos += 1; } } *pc = npc; *cp = c; return 1; } static int parse_literal(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *litp) { struct peg_grammar *peg = pgp->peg; struct peg_cursor npc = *pc; int nn; struct peg_node *pn; int c; int rv; uint i; char quote; struct raw value; quote = CHAR(pgp, &npc); if ( quote != '"' && quote != '\'' ) return 0; npc.pos += 1; value.len = 0; do { rv = parse_char(pgp, &npc, &c); if ( rv < 0 ) goto err; if ( rv == 0 ) { pgp->err = PEG_ERR_BAD_LITERAL; goto err; } value.len += 1; } while ( c != quote ); nn = peg_node_new(peg, PEG_LITERAL, pc->line); if ( nn < 0 ) { pgp->err = PEG_ERR_NOMEM; return -1; } value.data = malloc(value.len); if ( value.data == NULL ) { pgp->err = PEG_ERR_NOMEM; peg_node_free(peg, nn); return -1; } /* now copy/translate the string for real since we know */ /* its true length and that it decodes correctly. */ npc.pos = pc->pos + 1; npc.line = pc->line; for ( i = 0; i < value.len - 1; ++i ) { rv = parse_char(pgp, &npc, &c); abort_unless(rv > 0); /* tested above */ value.data[i] = c; } value.data[i] = '\0'; pn = NODE(peg, nn); pn->pl_value = value; pn->pl_value.len -= 1; pc->pos = npc.pos + 1; /* skip last quote */ pc->line = npc.line; *litp = nn; skip_space(pgp, pc); return 1; err: pgp->eloc = npc; return -1; } static int class_add_char(struct peg_grammar_parser *pgp, struct peg_cursor *pc, byte_t *cset) { struct peg_cursor npc = *pc; int c1; int c2; int rv; rv = parse_char(pgp, &npc, &c1); if ( rv < 0 ) return -1; if ( rv == 0 ) { pgp->err = PEG_ERR_BAD_CLASS; goto err; } if ( CHAR(pgp, &npc) != '-' ) { cset_add(cset, c1); } else { npc.pos += 1; rv = parse_char(pgp, &npc, &c2); if ( rv < 0 ) return -1; if ( rv == 0 ) { pgp->err = PEG_ERR_BAD_RANGE; goto err; } while ( c1 <= c2 ) { cset_add(cset, c1); ++c1; } } *pc = npc; return 1; err: pgp->eloc = *pc; return -1; } static int parse_class(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *clsp) { struct peg_grammar *peg = pgp->peg; struct peg_cursor npc = *pc; char c; int nn; struct peg_node *cls; uchar *cset; if ( CHAR(pgp, &npc) != '[' && CHAR(pgp, &npc) != '.' ) return 0; nn = peg_node_new(peg, PEG_CLASS, pc->line); if ( nn < 0 ) { pgp->err = PEG_ERR_NOMEM; return -1; } cset = malloc(32); if ( cset == NULL ) { peg_node_free(peg, nn); pgp->err = PEG_ERR_NOMEM; return -1; } /* treat . as a special class that matches almost everying */ if ( CHAR(pgp, &npc) == '.' ) { cset_fill(cset); cset_rem(cset, '\0'); goto match; } else { cset_clear(cset); npc.pos += 1; } while ( (c = CHAR(pgp, &npc)) != ']' && c != '\0' ) if ( class_add_char(pgp, &npc, cset) < 0 ) return -1; if ( c == '\0' ) { pgp->err = PEG_ERR_BAD_CLASS; pgp->eloc = npc; free(cset); peg_node_free(peg, nn); return -1; } match: cls = NODE(peg, nn); cls->pc_cset = cset; cls->pc_cset_size = 32; npc.pos += 1; *pc = npc; *clsp = nn; skip_space(pgp, pc); return 1; } static int parse_slash_char(struct peg_grammar_parser *pgp, struct peg_cursor *pc) { int c = CHAR(pgp, pc); if ( !cset_contains(cs_digit0to7, c) ) { if ( c == '\0' ) return -1; pc->pos += 1; } else { if ( cset_contains(cs_digit0to2, c) && cset_contains(cs_digit0to7, CHARI(pgp, pc, 1)) && cset_contains(cs_digit0to7, CHARI(pgp, pc, 2)) ) { pc->pos += 3; } else if ( cset_contains(cs_digit0to7, CHARI(pgp, pc, 1)) ) { pc->pos += 2; } else { pc->pos += 1; } } return 0; } static int parse_code(struct peg_grammar_parser *pgp, struct peg_cursor *pc, struct raw *r) { struct peg_cursor npc = *pc; uint n; uint brace_depth; size_t len; if ( CHAR(pgp, &npc) != '{' ) return 0; npc.pos += 1; brace_depth = 1; do { n = str_spn(STR(pgp, &npc), cs_ccode); npc.pos += n; if ( CHAR(pgp, &npc) == '"' ) { /* parse double quote */ npc.pos += 1; while ( CHAR(pgp, &npc) != '"' ) { if ( CHAR(pgp, &npc) == '\r' ) { npc.pos += 1; npc.line += 1; if ( CHAR(pgp, &npc) == '\n' ) npc.pos += 1; } else if ( CHAR(pgp, &npc) == '\n' ) { npc.pos += 1; npc.line += 1; } else if ( CHAR(pgp, &npc) == '\\' ) { npc.pos += 1; if ( parse_slash_char(pgp, &npc) < 0 ) goto err; } else if ( CHAR(pgp, &npc) == '\0' ) { goto err; } else { npc.pos += 1; } } npc.pos += 1; } else if ( CHAR(pgp, &npc) == '\'' ) { /* parse single quote char */ npc.pos += 1; if ( CHAR(pgp, &npc) == '\\' ) { npc.pos += 1; if ( parse_slash_char(pgp, &npc) < 0 ) goto err; } else { npc.pos += 1; } if ( CHAR(pgp, &npc) != '\'' ) goto err; npc.pos += 1; } else if ( CHAR(pgp, &npc) == '/' ) { if ( CHARI(pgp, &npc, 1) != '*' ) { npc.pos += 1; continue; } /* parse comment */ npc.pos += 2; while ( CHAR(pgp, &npc) != '*' || CHARI(pgp, &npc, 1) != '/' ) { if ( CHAR(pgp, &npc) == '\r' ) { npc.pos += 1; npc.line += 1; if ( CHAR(pgp, &npc) == '\n' ) npc.pos += 1; } else if ( CHAR(pgp, &npc) == '\n' ) { npc.pos += 1; npc.line += 1; } else if ( CHAR(pgp, &npc) == '\0' ) { goto err; } else { npc.pos += 1; } } npc.pos += 2; } else if ( CHAR(pgp, &npc) == '\r' ) { npc.pos += 1; npc.line += 1; if ( CHAR(pgp, &npc) == '\n' ) npc.pos += 1; } else if ( CHAR(pgp, &npc) == '\n' ) { npc.pos += 1; npc.line += 1; } else if ( CHAR(pgp, &npc) == '\0' ) { goto err; } else if ( CHAR(pgp, &npc) == '{' ) { brace_depth += 1; npc.pos += 1; } else if ( CHAR(pgp, &npc) == '}' ) { brace_depth -= 1; npc.pos += 1; } else { abort_unless(0); /* should never happen! */ } } while ( brace_depth > 0 ); len = npc.pos - pc->pos; if ( copy_str(pgp, pc, len, r) < 0 ) return -1; *pc = npc; skip_space(pgp, pc); return 1; err: pgp->err = PEG_ERR_BAD_CODE; pgp->eloc = npc; return -1; } static int parse_action_label(struct peg_grammar_parser *pgp, struct peg_cursor *pc, struct raw *r) { struct peg_cursor npc = *pc; size_t len; if ( !string_match(pgp, ":", &npc) ) return 0; if ( !cset_contains(cs_id_start, CHAR(pgp, &npc)) ) return 0; len = 1 + str_spn(STR(pgp, &npc) + 1, cs_id_cont); if ( copy_str(pgp, &npc, len, r) < 0 ) return -1; npc.pos += len; *pc = npc; skip_space(pgp, pc); return 1; } static int parse_primary(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *prip) { struct peg_grammar *peg = pgp->peg; int pri; int rv; int match = -1; struct peg_cursor npc = *pc; int prefix = PEG_ATTR_NONE; int suffix = PEG_ATTR_NONE; int action = PEG_ACT_NONE; struct raw r = { 0, NULL }; struct peg_node *pn; if ( string_match(pgp, "&", &npc) ) prefix = PEG_ATTR_AND; else if ( string_match(pgp, "!", &npc) ) prefix = PEG_ATTR_NOT; if ( (rv = parse_id_and_not_arrow(pgp, &npc, &match)) != 0 ) { if ( rv < 0 ) goto err; } else if ( (rv = parse_paren_expr(pgp, &npc, &match)) != 0 ) { if ( rv < 0 ) goto err; } else if ( (rv = parse_literal(pgp, &npc, &match)) != 0 ) { if ( rv < 0 ) goto err; } else if ( (rv = parse_class(pgp, &npc, &match)) != 0 ) { if ( rv < 0 ) goto err; } else { if ( prefix == PEG_ATTR_NONE ) return 0; pgp->err = PEG_ERR_BAD_PRIMARY; pgp->eloc = *pc; return -1; } pri = peg_node_new(peg, PEG_PRIMARY, pc->line); if ( pri < 0 ) { pgp->err = PEG_ERR_NOMEM; goto err; } if ( string_match(pgp, "?", &npc) ) suffix = PEG_ATTR_QUESTION; else if ( string_match(pgp, "*", &npc) ) suffix = PEG_ATTR_STAR; else if ( string_match(pgp, "+", &npc) ) suffix = PEG_ATTR_PLUS; else suffix = PEG_ATTR_NONE; rv = parse_code(pgp, &npc, &r); if ( rv < 0 ) goto err; if ( rv > 0 ) { action = PEG_ACT_CODE; } else { rv = parse_action_label(pgp, &npc, &r); if ( rv < 0 ) goto err; if ( rv > 0 ) action = PEG_ACT_LABEL; } pn = NODE(peg, pri); pn->pn_next = -1; pn->pp_match = match; pn->pp_prefix = prefix; pn->pp_suffix = suffix; pn->pp_action = action; pn->pn_action_cb = NULL; pn->pp_code = r; *pc = npc; *prip = pri; return 1; err: peg_node_free(peg, match); return -1; } static int parse_seq(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *seqp) { struct peg_grammar *peg = pgp->peg; int seq; int pri; int nn; struct peg_cursor npc = *pc; int rv; seq = peg_node_new(peg, PEG_SEQUENCE, pc->line); if ( seq < 0 ) { pgp->err = PEG_ERR_NOMEM; return -1; } rv = parse_primary(pgp, &npc, &pri); if ( rv < 0 ) goto err; NODE(peg, seq)->ps_pri = pri; while ( rv != 0 ) { if ( (rv = parse_primary(pgp, &npc, &nn)) < 0 ) goto err; if ( rv != 0 ) { NODE(peg, pri)->pn_next = nn; pri = nn; } } *pc = npc; *seqp = seq; return 1; err: peg_node_free(peg, seq); return -1; } static int parse_expr(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *exprp) { struct peg_grammar *peg = pgp->peg; struct peg_cursor npc = *pc; int expr = -1; int snn; int nn; int rv; rv = parse_seq(pgp, &npc, &expr); if ( rv <= 0 ) return rv; snn = expr; while ( string_match(pgp, "/", &npc) ) { rv = parse_seq(pgp, &npc, &nn); if ( rv < 0 ) goto err; if ( rv == 0 ) { pgp->err = PEG_ERR_BAD_EXPR; goto err; } NODE(peg, snn)->pn_next = nn; snn = nn; } *pc = npc; *exprp = expr; return 1; err: pgp->eloc = npc; peg_node_free(peg, expr); return -1; } static int parse_def(struct peg_grammar_parser *pgp, struct peg_cursor *pc, int *idp) { struct peg_grammar *peg = pgp->peg; struct peg_cursor npc = *pc; int id = -1; int expr = -1; int def = -1; struct peg_node *pn; int rv; rv = parse_id(pgp, &npc, &id); if ( rv <= 0 ) return rv; if ( NODE(peg, id)->pi_def >= 0 ) { pgp->err = PEG_ERR_DUP_DEF; pgp->eloc = *pc; return -1; } if ( !string_match(pgp, "<-", &npc) ) { peg_node_free(peg, id); return 0; } if ( (rv = parse_expr(pgp, &npc, &expr)) <= 0 ) { if ( rv == 0 ) pgp->err = PEG_ERR_BAD_DEF; pgp->eloc = npc; peg_node_free(peg, id); return -1; } def = peg_node_new(peg, PEG_DEFINITION, pc->line); if ( def < 0 ) { peg_node_free(peg, id); peg_node_free(peg, expr); pgp->err = PEG_ERR_NOMEM; return -1; } pn = NODE(peg, def); pn->pd_id = id; pn->pd_expr = expr; pn = NODE(peg, id); pn->pi_def = def; *pc = npc; if ( idp != NULL ) *idp = id; return 1; } static int add_undef_token(struct peg_grammar_parser *pgp, int id) { struct peg_grammar *peg = pgp->peg; struct peg_node *pi = NODE(peg, id); char *name = pi->pi_name.data; int i; if ( !(pgp->flags & PEG_GEN_TOKENS) ) return -1; if ( peg->num_tokens >= PEG_TOK_MAX ) { pgp->err = PEG_ERR_TOO_MANY_TOKENS; return -1; } /* idenfitier must be all caps and start with a letter */ if ( !isalpha(name[0]) ) return -1; for ( i = 0; i < pi->pi_name.len; ++i ) if ( isalpha(name[i]) && !isupper(name[i]) ) return -1; pi->pi_def = PEG_TOKEN_IDX(peg->num_tokens++); return 0; } static int check_unresolved_ids(struct peg_grammar_parser *pgp) { struct peg_grammar *peg = pgp->peg; int i; for ( i = 0; i < peg->max_nodes; ++i ) { if ( pn_is_type(peg, i, PEG_IDENTIFIER) && NODE(peg, i)->pi_def < 0 ) { if ( !add_undef_token(pgp, i) ) continue; if ( pgp->err ) return -1; pgp->err = PEG_ERR_UNDEF_ID; pgp->eloc.pos = i; snprintf(pgp->unknown_id, sizeof(pgp->unknown_id), "%s", NODE(peg, pgp->eloc.pos)->pi_name.data); return -1; } } return 0; } /* TODO: boundary check str_spn() calls to check against overflows. */ int peg_parse(struct peg_grammar_parser *pgp, struct peg_grammar *peg, const char *string, uint len, int flags) { struct peg_cursor pc = { 0, 1 }; int start; int rv; if ( !initialized ) { cset_init_accept(cs_space, " \t\r\n"); cset_init_accept(cs_eol, "\r\n"); cset_init_accept(cs_id_start, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ_"); cset_init_accept(cs_id_cont, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "_0123456789"); cset_init_accept(cs_special, "nrt'\"[]\\"); cset_init_accept(cs_digit0to2, "012"); cset_init_accept(cs_digit0to7, "01234567"); cset_init_reject(cs_ccode, "\"\'/{}\r\n"); cset_rem(cs_ccode, '\0'); initialized = 1; } peg->nodes = NULL; peg->max_nodes = 0; peg->num_nodes = 0; peg->num_tokens = 0; peg->start_node = -1; peg->dynamic = 1; pgp->input = string; pgp->input_len = len; pgp->len = 0; pgp->nlines = 1; pgp->flags = flags; pgp->peg = peg; pgp->err = 0; pgp->eloc = pc; skip_space(pgp, &pc); rv = parse_def(pgp, &pc, &start); if ( rv <= 0 ) { peg_free_nodes(peg); return rv; } peg->start_node = start; while ( pc.pos < len ) { rv = parse_def(pgp, &pc, NULL); if ( rv < 0 ) { peg_free_nodes(peg); return -1; } if ( rv == 0 ) break; } if ( check_unresolved_ids(pgp) < 0 ) { peg_free_nodes(peg); return -1; } pgp->len = pc.pos; pgp->nlines = pc.line; return 1; } void peg_free_nodes(struct peg_grammar *peg) { int i; for ( i = 0; i < peg->max_nodes; ++i ) peg_node_free(peg, i); if ( peg->dynamic ) { free(peg->nodes); peg->nodes = NULL; peg->max_nodes = 0; peg->num_nodes = 0; peg->start_node = 0; peg->dynamic = 0; } } char *peg_err_string(struct peg_grammar_parser *pgp, char *buf, size_t blen) { static const char *peg_error_strings[] = { "No error", "Ran out of memory during parsing", "Erroneous non-terminal definition", "Duplicate definition of a non-terminal", "Erroneous expression", "Erroneous primary match", "Erroneous parenthesized expression", "Erroneous literal", "Undefined identifier", "Erroneous class", "Erroneous character", "Erroneous character range", "Erroneous code block", "Too many tokens", }; if ( pgp->err < PEG_ERR_NONE || pgp->err > PEG_ERR_LAST ) { str_copy(buf, "Unknown PEG error", blen); } else if ( pgp->err == PEG_ERR_UNDEF_ID ) { snprintf(buf, blen, "Undefined identifier %s", pgp->unknown_id); } else { snprintf(buf, blen, "%s on line %u / position %u", peg_error_strings[pgp->err], pgp->eloc.line, pgp->eloc.pos); } return buf; } static char *indent(char *buf, uint bsize, uint depth) { uint i; buf[0] = '\0'; bsize /= 2; for ( i = 0; i < depth; ++i ) { if ( i >= bsize - 1 ) break; buf[2*i] = ' '; buf[2*i + 1] = ' '; } buf[2*i] = '\0'; return buf; } void printchar(FILE *out, int i) { if ( isprint(i) && !isspace(i) ) fprintf(out, "%c", i); else if ( i == '\n' ) fprintf(out, "\\n"); else if ( i == '\r' ) fprintf(out, "\\r"); else if ( i == '\t' ) fprintf(out, "\\t"); else if ( i == ' ' ) fprintf(out, " "); else fprintf(out, "\\%03o", i); } static void print_class(FILE *out, struct peg_node *cls) { int i; int l; fprintf(out, "["); for ( l = -1, i = 0; i < 256; ++i ) { if ( cset_contains(cls->pc_cset, i) ) { if ( l == -1 ) { printchar(out, i); l = i; } } else { if ( l >= 0 && i > l + 1 ) { if ( i > l + 2 ) fprintf(out, "-"); printchar(out, i - 1); } l = -1; } } fprintf(out, "] "); } static void print_node(struct peg_grammar *peg, int i, int seq, int depth, FILE *out) { int j; int aggregate; char sbuf[256]; struct peg_node *pn; if ( i < 0 || i >= peg->max_nodes ) return; pn = NODE(peg, i); switch ( pn->pn_type ) { case PEG_DEFINITION: fprintf(out, "%s <-\n", NODE(peg, pn->pd_id)->pi_name.data); fprintf(out, "%s", indent(sbuf, sizeof(sbuf), 1)); print_node(peg, pn->pd_expr, 0, 1, out); fprintf(out, "\n"); break; case PEG_SEQUENCE: if ( seq > 0 ) { fprintf(out, "\n"); fprintf(out, "%s", indent(sbuf, sizeof(sbuf), depth)); fprintf(out, "/ "); } print_node(peg, pn->ps_pri, seq, depth + 1, out); print_node(peg, pn->pn_next, seq + 1, depth, out); break; case PEG_PRIMARY: aggregate = 0; if ( seq == 0 && (NODE(peg, pn->pp_match)->pn_type == PEG_SEQUENCE) ) aggregate = 1; fprintf(out, "%s", (pn->pp_prefix == PEG_ATTR_NONE) ? "" : (pn->pp_prefix == PEG_ATTR_AND) ? "&" : (pn->pp_prefix == PEG_ATTR_NOT) ? "!" : "BAD_PREFIX!"); if ( aggregate ) fprintf(out, "( "); print_node(peg, pn->pp_match, seq, depth, out); if ( aggregate ) fprintf(out, " )"); fprintf(out, "%s", (pn->pp_suffix == PEG_ATTR_NONE) ? " " : (pn->pp_suffix== PEG_ATTR_QUESTION) ? "? " : (pn->pp_suffix == PEG_ATTR_STAR) ? "* " : (pn->pp_suffix == PEG_ATTR_PLUS) ? "+ " : "BAD_SUFFIX!"); if ( pn->pp_action != PEG_ACT_NONE ) { if ( pn->pp_action == PEG_ACT_CODE ) { fprintf(out, "\n"); fprintf(out, "%s", indent(sbuf, sizeof(sbuf), depth)); fprintf(out, "CODE BLOCK:\n"); fprintf(out, "%s", indent(sbuf, sizeof(sbuf), depth)); fprintf(out, "%s", pn->pp_code.data); } else { fprintf(out, "(action_id: %s) ", pn->pp_label.data); } } print_node(peg, pn->pn_next, seq, depth, out); break; case PEG_IDENTIFIER: fprintf(out, "%s ", pn->pi_name.data); break; case PEG_LITERAL: fprintf(out, "'"); for ( j = 0; j < pn->pl_value.len; ++j ) printchar(out, pn->pl_value.data[j]); fprintf(out, "' "); break; case PEG_CLASS: print_class(out, pn); break; } } void peg_print(struct peg_grammar *peg, FILE *out) { int i; for ( i = 0; i < peg->max_nodes; ++i ) if ( pn_is_type(peg, i, PEG_DEFINITION) ) print_node(peg, i, 0, 0, out); fprintf(out, "\n"); } int peg_action_set(struct peg_grammar *peg, char *label, peg_action_f cb) { int n = 0; int i; struct peg_node *pn; for ( i = 0; i < peg->max_nodes; ++i ) { if ( !pn_is_type(peg, i, PEG_PRIMARY) ) continue; pn = NODE(peg, i); if ( pn->pp_action == PEG_ACT_LABEL && !strcmp(label, pn->pp_label.data) ) { pn->pp_action = PEG_ACT_CALLBACK; pn->pn_action_cb = cb; ++n; } } return n; }
github188/catlib
src/splay.c
<filename>src/splay.c /* * splay.c -- Splay tree implementation * * by <NAME> * * Copyright 2006-2012 See accompanying license * */ #undef CAT_USE_INLINE #undef CAT_SPLAY_DO_DECL #define CAT_USE_INLINE 0 #define CAT_SP_DO_DECL 1 #include <cat/splay.h>
github188/catlib
attic/lcut.h
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ void l_cut(struct list *first, struct list *last, struct list *out) { struct list *before, *after; Assert(first); Assert(last); Assert(out); before = first->prev; after = last->next; out->next = first; out->prev = last; before->next = after; after->prev = before; first->prev = out; last->next = out; }
github188/catlib
include/cat/peg.h
#ifndef __peg_h #define __peg_h #include <cat/cat.h> #include <stdio.h> struct peg_node; struct peg_grammar; typedef int (*peg_action_f)(int, struct raw *, void *); struct peg_node { int pn_type; struct raw pn_str; int pn_next; int pn_subnode; uint pn_line; ushort pn_status; uchar pn_flag1; uchar pn_flag2; peg_action_f pn_action_cb; }; #define pn_is_type(_peg, _idx, _type) \ ((_idx) >= 0 && (_idx < (_peg)->max_nodes) && \ (_peg)->nodes[(_idx)].pn_type == (_type)) #define pd_id pn_subnode #define pd_expr pn_next /* defs aren't in lists */ #define ps_pri pn_subnode #define pp_match pn_subnode #define pp_action pn_status #define pp_label pn_str #define pp_code pn_str #define pp_prefix pn_flag1 #define pp_suffix pn_flag2 #define pi_name pn_str #define pi_refcnt pn_status #define pi_def pn_subnode #define pl_value pn_str #define pc_cset_raw pn_str #define pc_cset pn_str.data #define pc_cset_size pn_str.len struct peg_grammar { struct peg_node *nodes; uint max_nodes; uint num_nodes; uint num_tokens; uint start_node; int dynamic; }; enum { PEG_ERR_NONE = 0, PEG_ERR_NOMEM = 1, PEG_ERR_BAD_DEF = 2, PEG_ERR_DUP_DEF = 3, PEG_ERR_BAD_EXPR = 4, PEG_ERR_BAD_PRIMARY = 5, PEG_ERR_BAD_PAREXPR = 6, PEG_ERR_BAD_LITERAL = 7, PEG_ERR_UNDEF_ID = 8, PEG_ERR_BAD_CLASS = 9, PEG_ERR_BAD_CHAR = 10, PEG_ERR_BAD_RANGE = 11, PEG_ERR_BAD_CODE = 12, PEG_ERR_TOO_MANY_TOKENS = 13, PEG_ERR_LAST = PEG_ERR_TOO_MANY_TOKENS }; struct peg_cursor { uint pos; uint line; }; struct peg_grammar_parser { const char *input; uint input_len; uint len; uint nlines; int flags; struct peg_grammar *peg; int err; struct peg_cursor eloc; char unknown_id[256]; }; enum { PEG_GEN_TOKENS = (1 << 0) }; enum { PEG_NONE, PEG_DEFINITION, PEG_SEQUENCE, PEG_PRIMARY, PEG_IDENTIFIER, PEG_LITERAL, PEG_CLASS }; enum { PEG_ATTR_NONE = 0, PEG_ATTR_AND, PEG_ATTR_NOT, PEG_ATTR_QUESTION, PEG_ATTR_STAR, PEG_ATTR_PLUS }; enum { PEG_ACT_NONE = 0, PEG_ACT_CODE, PEG_ACT_LABEL, PEG_ACT_CALLBACK }; enum { PEG_TOK_FIRST = 128, PEG_TOK_LAST = 254, PEG_TOK_MAX = PEG_TOK_LAST - PEG_TOK_FIRST + 1, }; #define PEG_TOKEN_IDX(_id) (-((_id) + PEG_TOK_FIRST)) #define PEG_TOKEN_ID(_idx) (-(_idx)) #define PEG_IDX_IS_TOKEN(_peg, _idx) \ (PEG_TOKEN_ID(_idx) >= PEG_TOK_FIRST && \ PEG_TOKEN_ID(_idx) < PEG_TOK_FIRST + (_peg)->num_tokens) int peg_parse(struct peg_grammar_parser *pgp, struct peg_grammar *peg, const char *string, uint len, int flags); void peg_free_nodes(struct peg_grammar *peg); char *peg_err_string(struct peg_grammar_parser *pgp, char *buf, size_t blen); void peg_print(struct peg_grammar *peg, FILE *out); int peg_action_set(struct peg_grammar *peg, char *label, peg_action_f cb); #endif /* __peg_h */
github188/catlib
src/emit_format.c
<gh_stars>1-10 /* * emit_format.c -- formatted output through emit API. * * by <NAME> * * Copyright 2003-2014 See accompanying license * */ #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdarg.h> #include <limits.h> #include <cat/cat.h> #include <cat/aux.h> #include <cat/emit.h> #include <cat/emit_format.h> enum { ARG_REG, ARG_HALF, ARG_LONG, ARG_LONGLONG, ARG_LONGDBL }; struct format_params { int fmtchar; int precision; int minwidth; int alternate; int posspace; int rightjust; int alwayssign; int zerofill; int argsize; int capver; }; struct va_list_s { va_list ap; }; #ifndef va_copy #ifndef __va_copy #error "Neither va_copy, nor __va_copy are defined!" #else #define va_copy(d,s) __va_copy(d,s) #endif #endif typedef int (*format_f)(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen); #define EMIT_CHAR(em, ch) \ do { \ if ( ((em)->emit_state != EMIT_EOS) && \ (emit_char((em), (ch)) < 0) ) \ return -1; \ } while(0) #define EMIT_STRING(em, ch) \ do { \ if ( ((em)->emit_state != EMIT_EOS) && \ (emit_string((em), (ch)) < 0) ) \ return -1; \ } while(0) static int Emit_n_char(struct emitter *em, uchar ch, int times) { while ( times > 0 ) { if ( ((em)->emit_state != EMIT_EOS) && (emit_char((em), (ch)) < 0) ) return -1; --times; } return 0; } static void init_format_params(struct format_params *fp) { abort_unless(fp); fp->fmtchar = ' '; fp->precision = -1; fp->minwidth = -1; fp->alternate = 0; fp->posspace = 0; fp->rightjust = 1; fp->alwayssign = 0; fp->zerofill = 0; fp->argsize = ARG_REG; fp->capver = 0; } static int is_fmt_char(char ch) { return (isalpha(ch) || (ch == '%')) && (ch != 'h') && (ch != 'l') && (ch != 'L'); } static int get_format_flags(const char **fmtp, struct format_params *fp, struct va_list_s *app) { const char *fmt; char *fp2; int pastperiod = 0; int pastprec = 0; int nextc; int argval; long val; abort_unless(fmtp && *fmtp && fp); fmt = *fmtp; while ( !is_fmt_char(nextc = *fmt) ) { /* handle precision or width case */ if ( isdigit(nextc) && (nextc != '0' || pastperiod) ) { if ( pastprec ) return -1; val = strtol(fmt, &fp2, 10); fmt = (const char *)fp2; if ( val > INT_MAX ) return -1; if ( pastperiod ) { if ( fp->precision > 0 ) return -1; fp->precision = val; } else { if ( fp->minwidth > 0 ) return -1; fp->minwidth = val; } continue; } /* handle remaining format modifiers */ switch ( nextc ) { case '\0': return -1; case '-': fp->rightjust = 0; break; case '+': fp->alwayssign = 1; break; case ' ': fp->posspace = 1; break; case '0': fp->zerofill = 1; break; case '#': fp->alternate = 1; break; case '*': if ( (app == NULL) || ((argval = va_arg(app->ap, int)) < 0) ) return -1; if ( pastperiod ) { if ( fp->precision > 0 ) return -1; fp->precision = argval; } else { if ( fp->minwidth > 0 ) return -1; fp->minwidth = argval; } break; case '.': if ( pastperiod ) return -1; pastperiod = 1; break; case 'h': if ( fp->argsize != ARG_REG ) return -1; fp->argsize = ARG_HALF; break; case 'l': if ( fp->argsize != ARG_REG ) return -1; #if CAT_HAS_LONGLONG if ( *(fmt+1) == 'l' ) { ++fmt; fp->argsize = ARG_LONGLONG; } else { fp->argsize = ARG_LONG; } #else fp->argsize = ARG_LONG; #endif /* CAT_HAS_LONGLONG */ break; case 'L': if ( fp->argsize != ARG_REG ) return -1; fp->argsize = ARG_LONGDBL; break; default: return -1; } fmt++; } fp->fmtchar = nextc; *fmtp = fmt + 1; return 0; } static void reverse_string(char *s, size_t len) { char *e, c; abort_unless(s); if ( len == 0 ) return; e = s + len - 1; while ( s < e ) { c = *s; *s = *e; *e = c; ++s; --e; } } static int fmt_char(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { char ch; abort_unless(em && fp && app && flen); if ( fp->argsize != ARG_REG ) return -1; ch = va_arg(app->ap, int); if ( fp->minwidth > 0 && fp->rightjust ) { if ( Emit_n_char(em, ' ', fp->minwidth - 1) < 0 ) return -1; } EMIT_CHAR(em, ch); if ( fp->minwidth > 0 && !fp->rightjust ) { if ( Emit_n_char(em, ' ', fp->minwidth - 1) < 0 ) return -1; } if ( fp->minwidth > 0 ) *flen = fp->minwidth; else *flen = 1; return 0; } static int fmt_str_help(char *s, struct emitter *em, struct format_params *fp, int *flen) { size_t slen; slen = strlen(s); abort_unless(slen <= INT_MAX); if ( fp->precision > 0 && fp->precision < slen ) slen = fp->precision; if ( fp->minwidth > 0 && fp->rightjust && fp->minwidth > slen ) { if ( Emit_n_char(em, ' ', fp->minwidth - slen) < 0 ) return -1; } EMIT_STRING(em, s); if ( fp->minwidth > 0 && !fp->rightjust && fp->minwidth > slen ) { if ( Emit_n_char(em, ' ', fp->minwidth - slen) < 0 ) return -1; } if ( fp->minwidth > 0 && fp->minwidth > slen ) *flen = fp->minwidth; else *flen = slen; return 0; } static int fmt_str(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { char *s; abort_unless(em && fp && app && flen); if ( fp->argsize != ARG_REG ) return -1; s = va_arg(app->ap, char *); return fmt_str_help(s, em, fp, flen); } #if CAT_HAS_LONGLONG #define CAT_MAXUTYPE ullong #define CAT_MAXSTYPE long long #else /* CAT_HAS_LONGLONG */ #define CAT_MAXUTYPE ulong #define CAT_MAXSTYPE long #endif /* CAT_HAS_LONGLONG */ static CAT_MAXUTYPE get_u_arg(struct format_params *fp, struct va_list_s *app) { CAT_MAXUTYPE v = 0; abort_unless(fp && app); if ( fp->argsize == ARG_LONGDBL ) return -1; else if ( fp->argsize == ARG_REG ) v = va_arg(app->ap, uint); else if ( fp->argsize == ARG_LONG ) v = va_arg(app->ap, ulong); else if ( fp->argsize == ARG_HALF ) v = va_arg(app->ap, uint); #if CAT_HAS_LONGLONG else if ( fp->argsize == ARG_LONGLONG ) v = va_arg(app->ap, ullong); #endif /* CAT_HAS_LONGLONG */ else abort_unless(0); return v; } static CAT_MAXSTYPE get_s_arg(struct format_params *fp, struct va_list_s *app) { CAT_MAXSTYPE v = 0; abort_unless(fp && app); if ( fp->argsize == ARG_LONGDBL ) return -1; else if ( fp->argsize == ARG_REG ) v = va_arg(app->ap, int); else if ( fp->argsize == ARG_LONG ) v = va_arg(app->ap, long); else if ( fp->argsize == ARG_HALF ) v = va_arg(app->ap, int); #if CAT_HAS_LONGLONG else if ( fp->argsize == ARG_LONGLONG ) v = va_arg(app->ap, long long); #endif /* CAT_HAS_LONGLONG */ else abort_unless(0); return v; } static int fmt_int(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { CAT_MAXSTYPE v; char buf[sizeof(v) * 3 + 1] = { 0 }; int i, ndigits, tnlen, plen = 0, neg = 0; abort_unless(em && fp && app && flen); v = get_s_arg(fp, app); if ( v < 0 || fp->posspace || fp->alwayssign ) plen = 1; if ( v < 0 ) neg = 1; /* Pull off the first digit and divide by 10 so we don't have to */ /* worry about how -INT_MIN == INTMIN in 2s compliment */ if ( v == 0 ) { buf[0] = '0'; } else { int firstd = v % 10; if ( firstd < 0 ) firstd = -firstd; buf[0] = '0' + firstd; } v /= 10; /* convert to a positive number */ if ( v < 0 ) v = -v; /* pull off the remaining digits (in reverse order) */ i = 1; while ( v > 0 ) { int xd = v % 10; buf[i++] = xd + '0'; v /= 10; } /* flip it back to the correct order */ reverse_string(buf, i); ndigits = i; if ( fp->precision >= 0 && fp->precision > ndigits ) ndigits = fp->precision; if ( fp->minwidth >= 0 && fp->minwidth > ndigits + plen && fp->zerofill ) ndigits = fp->minwidth - plen; tnlen = ndigits + plen; if ( fp->minwidth >= 0 && fp->minwidth > tnlen && fp->rightjust ) if ( Emit_n_char(em, ' ', fp->minwidth - tnlen) < 0 ) return -1; if ( neg ) { EMIT_CHAR(em, '-'); } else if ( fp->alwayssign ) { EMIT_CHAR(em, '+'); } else if ( fp->posspace ) { EMIT_CHAR(em, ' '); } if ( ndigits > i ) { if ( Emit_n_char(em, '0', ndigits - i) < 0 ) return -1; } EMIT_STRING(em, buf); if ( fp->minwidth >= 0 && fp->minwidth > tnlen && !fp->rightjust ) if ( Emit_n_char(em, ' ', fp->minwidth - tnlen) < 0 ) return -1; if ( fp->minwidth >= 0 && fp->minwidth > tnlen ) *flen = fp->minwidth; else *flen = tnlen; return 0; } static void divmod(CAT_MAXUTYPE v, uint radix, CAT_MAXUTYPE *q, uint *r) { #if CAT_HAS_DIV *q = v / radix; *r = v % radix; #else /* CAT_HAS_DIV */ switch (radix) { case 2: *q = v >> 1; *r = v & 1; break; case 8: *q = v >> 3; *r = v & 7; break; case 10: /* Multiply v by 8/10 = .11001100... */ *q = (v >> 1) + (v >> 2); *q = *q + (*q >> 4); *q = *q + (*q >> 8); *q = *q + (*q >> 16); if ( sizeof(v) > 4 ) *q = *q + (*q >> 32); /* Divide by 8 to get 1/10 */ *q >>= 3; /* compute the remainder, may have an error of up to 10 */ *r = v - *q * 10; *q = *q + ((*r + 6) >> 4); /* compute the remainder */ *r = v - *q * 10; break; case 16: *q = v >> 4; *r = v & 0xF; break; default: #if CAT_HAS_LONGLONG *q = ulldivmod(v, radix, 1); *r = ulldivmod(v, radix, 0); #else *q = uldivmod(v, radix, 1); *r = uldivmod(v, radix, 0); #endif break; } #endif /* CAT_HAS_DIV */ } static int fmt_u(struct emitter *em, struct format_params *fp, int *flen, int radix, char *apfx, CAT_MAXUTYPE v) { char buf[sizeof(v) * 8 + 1] = { 0 }; int i, ndigits, tnlen, plen = 0; uint xd; CAT_MAXUTYPE q; abort_unless(em && fp && flen && apfx); abort_unless(radix >= 2 && radix <= 36); /* compute the alternate prefix length */ if ( fp->alternate && (fp->fmtchar != 'p' || v != 0) ) plen = strlen(apfx); if ( v == 0 ) buf[0] = '0'; i = 0; while ( v > 0 ) { divmod(v, radix, &q, &xd); if ( xd < 10 ) buf[i++] = xd + '0'; else if ( fp->capver ) buf[i++] = xd - 10 + 'A'; else buf[i++] = xd - 10 + 'a'; v = q; } if ( i == 0 ) i = 1; reverse_string(buf, i); ndigits = i; if ( fp->precision >= 0 && fp->precision > ndigits ) ndigits = fp->precision; if ( fp->minwidth >= 0 && fp->minwidth > ndigits + (fp->alternate ? plen : 0) && fp->zerofill ) ndigits = fp->minwidth - (fp->alternate ? plen : 0); tnlen = ndigits + (fp->alternate ? plen : 0); if ( fp->minwidth >= 0 && fp->minwidth > tnlen && fp->rightjust ) if ( Emit_n_char(em, ' ', fp->minwidth - tnlen) < 0 ) return -1; if ( fp->alternate ) { int i, ch; for ( i = 0 ; i < plen ; ++i ) { ch = fp->capver ? toupper(apfx[i]) : apfx[i]; EMIT_CHAR(em, ch); } } if ( ndigits > i ) if ( Emit_n_char(em, '0', ndigits - i) < 0 ) return -1; EMIT_STRING(em, buf); if ( fp->minwidth >= 0 && fp->minwidth > tnlen && !fp->rightjust ) if ( Emit_n_char(em, '0', fp->minwidth - tnlen) < 0 ) return -1; if ( fp->minwidth >= 0 && fp->minwidth > tnlen ) *flen = fp->minwidth; else *flen = tnlen; return 0; } static int fmt_hex(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { abort_unless(em && fp && app && flen); return fmt_u(em, fp, flen, 16, "0x", get_u_arg(fp, app)); } static int fmt_oct(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { abort_unless(em && fp && app && flen); return fmt_u(em, fp, flen, 8, "0", get_u_arg(fp, app)); } static int fmt_uint(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { abort_unless(em && fp && app && flen); return fmt_u(em, fp, flen, 10, "", get_u_arg(fp, app)); } static int fmt_binary(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { abort_unless(em && fp && app && flen); return fmt_u(em, fp, flen, 2, "0b", get_u_arg(fp, app)); } #if CAT_HAS_FLOAT static int get_double_arg(struct format_params *fp, struct va_list_s *app, long double *rv) { long double v; abort_unless(fp && app && rv); if ( fp->argsize == ARG_LONGDBL ) v = va_arg(app->ap, long double); else if ( fp->argsize == ARG_REG ) v = va_arg(app->ap, double); else return -1; *rv = v; return 0; } #define isNaN(d) ((d) != (d)) #define isinf(d) ((FLOAT_MIN / (d)) == 0.0) #define MAX_POWER 8192 #define INF (MAX_POWER + 1) #define NEGINF (-MAX_POWER - 1) /* We can improve on this by using precomputed tables of exponentially */ /* increasing value and then locate where the value falls in the table */ /* The divide out the lower bound for the value, keep the exponent and repeat */ static int find_power(long double d) { int e = 0; int neg = 0; if ( d == 0.0 ) return 0; if ( d < 0 ) { d = 0.0 - d; neg = 1; } if ( d >= 10.0 ) { while ( d >= 10.0 ) { d /= 10.0; e++; /* XXX calculate this constant or do a better test */ /* for infinity (e.g. float_min / e == 0) */ if ( e > MAX_POWER ) return (neg ? NEGINF : INF); } } else if ( d < 1.0 ) { while ( d < 1.0 ) { d *= 10.0; e--; abort_unless(e >= -MAX_POWER); } } return e; } static long double p10(int power) { long double val = 1.0; long double mul = 10.0; abort_unless(power >= 0); while ( power > 0 ) { if ( (power & 1) == 1 ) val *= mul; mul *= mul; power >>= 1; } return val; } #define STRIP_ALT 1 #define STRIP_FFMT 2 static int adjust_precision(long double v, int power, int prec, int flags) { int i; int zlen = 0; uchar digit; abort_unless(prec >= 0); if ( v < 0 ) v = 0.0 - v; if ( prec == 0 ) return 0; if ( flags & STRIP_FFMT ) { if ( power < 0 ) { prec += -power - 1; } else { if ( prec <= power + 1 ) return 0; prec -= power + 1; } } else { if ( power < 0 ) v *= p10(-power); else if ( power > 0 ) v /= p10(power); --prec; } if ( flags & STRIP_ALT ) return prec; digit = 0; for ( i = 0; i < prec; ++i ) { v *= 10.0; v -= digit * 10.0; digit = (uchar)v % 10; if ( digit == 0 ) zlen++; else zlen = 0; } return prec - zlen; } static int fmt_double_help(long double v, struct emitter *em, struct format_params *fp, int *flen) { int prec = 6; int signlen = 0; int periodlen = 0; int power; int spaces = 0; int tlen; uchar digit; abort_unless(em && fp && flen); if ( isNaN(v) ) return fmt_str_help("NaN", em, fp, flen); if ( fp->precision >= 0 ) prec = fp->precision; power = find_power(v); if ( power == INF ) return fmt_str_help("inf", em, fp, flen); else if ( power == NEGINF ) return fmt_str_help("-inf", em, fp, flen); if ( toupper(fp->fmtchar) == 'G' ) { int flags = STRIP_FFMT; if ( fp->alternate ) flags |= STRIP_ALT; prec = adjust_precision(v, power, prec, flags); } signlen = (fp->alwayssign || v < 0 || fp->posspace) ? 1 : 0; periodlen = (prec == 0 && !fp->alternate) ? 0 : 1; tlen = (power <= 0) ? 1 : power + 1; tlen += prec + periodlen + signlen; if ( fp->minwidth > tlen ) spaces = fp->minwidth - tlen; /* Right justification space padding */ if ( spaces > 0 && fp->rightjust && !fp->zerofill ) { if ( Emit_n_char(em, ' ', spaces) < 0 ) return -1; } /* Add sign */ if ( v < 0.0 ) { EMIT_CHAR(em, '-'); v = 0.0 - v; } else if ( fp->alwayssign ) { EMIT_CHAR(em, '+'); } else if ( fp->posspace ) { EMIT_CHAR(em, ' '); } if ( spaces > 0 && fp->rightjust && fp->zerofill ) { if ( Emit_n_char(em, '0', spaces) < 0 ) return -1; } /* integral portion */ if ( power >= 0 ) { /* Normalize to exponential form */ /* XXX This is a highly inaccurate way to generate the digits */ /* but since this library has NO knowledge of unerlying */ /* representation, this is the best I have for now */ v /= p10(power); while ( power >= 0 ) { digit = (uchar)v % 10; EMIT_CHAR(em, digit + '0'); v *= 10.0; v -= digit * 10.0; --power; } } else { EMIT_CHAR(em, '0'); v *= 10.0; } if ( prec > 0 || fp->alternate ) { EMIT_CHAR(em, '.'); } /* fractional portion */ while ( prec > 0 ) { digit = (uchar)v % 10; EMIT_CHAR(em, digit + '0'); v *= 10.0; v -= digit * 10.0; --prec; } /* left justification spaces */ if ( spaces > 0 && !fp->rightjust ) { if ( Emit_n_char(em, ' ', spaces) < 0 ) return -1; } *flen = tlen + spaces; return 0; } static int fmt_exp_double_help(long double v, struct emitter *em, struct format_params *fp, int *flen) { int prec = 6; int signlen = 0; int periodlen = 0; int explen = 4; int power, opower; int spaces = 0; int tlen; int i; uchar digit; char exp[8]; abort_unless(em && fp && flen); if ( isNaN(v) ) return fmt_str_help("NaN", em, fp, flen); if ( fp->precision >= 0 ) prec = fp->precision; opower = power = find_power(v); if ( power == INF ) return fmt_str_help("inf", em, fp, flen); else if ( power == NEGINF ) return fmt_str_help("-inf", em, fp, flen); if ( power < 0 ) power = -power; while ( power > 99 ) { explen++; power /= 10; } if ( toupper(fp->fmtchar) == 'G' ) { int flags = 0; if ( fp->alternate ) flags |= STRIP_ALT; prec = adjust_precision(v, power, prec, fp->alternate); } signlen = (fp->alwayssign || v < 0.0 || fp->posspace) ? 1 : 0; periodlen = (prec == 0 && !fp->alternate) ? 0 : 1; tlen = 1 + periodlen + prec + signlen + explen; if ( fp->minwidth > tlen ) spaces = fp->minwidth - tlen; /* Right justification space padding */ if ( spaces > 0 && fp->rightjust && !fp->zerofill ) { if ( Emit_n_char(em, ' ', spaces) < 0 ) return -1; } /* Add sign */ if ( v < 0.0 ) { EMIT_CHAR(em, '-'); v = 0.0 - v; } else if ( fp->alwayssign ) { EMIT_CHAR(em, '+'); } else if ( fp->posspace ) { EMIT_CHAR(em, ' '); } if ( spaces > 0 && fp->rightjust && fp->zerofill ) { if ( Emit_n_char(em, '0', spaces) < 0 ) return -1; } power = opower; if ( power > 0 ) v /= p10(power); else v *= p10(-power); /* print first digit */ digit = (uchar)v % 10; EMIT_CHAR(em, digit + '0'); v *= 10.0; v -= digit * 10.0; if ( prec > 0 || fp->alternate ) EMIT_CHAR(em, '.'); while ( prec > 0 ) { digit = (uchar)v % 10; EMIT_CHAR(em, digit + '0'); v *= 10.0; v -= digit * 10.0; --prec; } EMIT_CHAR(em, isupper(fp->fmtchar) ? 'E' : 'e'); power = opower; EMIT_CHAR(em, (power < 0) ? '-' : '+'); if ( power < 0 ) power = -power; if ( power < 10 ) EMIT_CHAR(em, '0'); if ( power == 0 ) { exp[0] = '0'; i = 1; } else { for ( i = 0 ; power > 0 ; ++i, power /= 10 ) exp[i] = (power % 10) + '0'; } exp[i] = '\0'; reverse_string(exp, i); EMIT_STRING(em, exp); *flen = tlen + spaces; return 0; } #endif /* CAT_HAS_FLOAT */ static int fmt_double(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { #if CAT_HAS_FLOAT long double v; abort_unless(em && fp && app && flen); if ( get_double_arg(fp, app, &v) < 0 ) return -1; return fmt_double_help(v, em, fp, flen); #else /* CAT_HAS_FLOAT */ return -1; #endif /* CAT_HAS_FLOAT */ } static int fmt_exp_double(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { #if CAT_HAS_FLOAT long double v; abort_unless(em && fp && app && flen); if ( get_double_arg(fp, app, &v) < 0 ) return -1; return fmt_exp_double_help(v, em, fp, flen); #else /* CAT_HAS_FLOAT */ return -1; #endif /* CAT_HAS_FLOAT */ } static int fmt_variable_double(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { #if CAT_HAS_FLOAT long double v; int power; int prec = 6; abort_unless(em && fp && app && flen); if ( get_double_arg(fp, app, &v) < 0 ) return -1; if ( fp->precision >= 0 ) prec = fp->precision; power = find_power(v); if ( power < -4 || power >= prec ) return fmt_exp_double_help(v, em, fp, flen); else return fmt_double_help(v, em, fp, flen); #else /* CAT_HAS_FLOAT */ return -1; #endif /* CAT_HAS_FLOAT */ } static int fmt_ptr(struct emitter *em, struct format_params *fp, struct va_list_s *app, int *flen) { CAT_MAXUTYPE v; abort_unless(em && fp && app && flen); if ( fp->argsize != ARG_REG ) return -1; v = (CAT_MAXUTYPE)va_arg(app->ap, void *); /* Adjust for size differences in case (void *) is treated as signed */ /* before promoting it to a CAT_MAXUTYPE! This assumes a flat address */ /* model which won't be correct for obscure hardware XXX */ if ( sizeof(CAT_MAXUTYPE) > sizeof(void *) ) { CAT_MAXUTYPE mask = 0; mask = ~mask; mask >>= (sizeof(CAT_MAXUTYPE) - sizeof(void *)) * CHAR_BIT; v &= mask; } if ( v == 0 ) return fmt_str_help("(nil)", em, fp, flen); fp->alternate = 1; return fmt_u(em, fp, flen, 16, "0x", v); } struct format_table_entry { char fmtchar; format_f formatter; int basetype; } format_tab[] = { { 'd', fmt_int, FMT_INTVAL }, { 'i', fmt_int, FMT_INTVAL }, { 'o', fmt_oct, FMT_INTVAL }, { 'x', fmt_hex, FMT_INTVAL }, { 'X', fmt_hex, FMT_INTVAL }, { 'u', fmt_uint, FMT_INTVAL }, { 'b', fmt_binary, FMT_INTVAL }, { 'c', fmt_char, FMT_INTVAL }, { 's', fmt_str, FMT_STRVAL }, { 'f', fmt_double, FMT_DBLVAL }, { 'e', fmt_exp_double, FMT_DBLVAL }, { 'E', fmt_exp_double, FMT_DBLVAL }, { 'g', fmt_variable_double, FMT_DBLVAL }, { 'G', fmt_variable_double, FMT_DBLVAL }, { 'p', fmt_ptr, FMT_PTRVAL }, }; static const int format_tab_len = sizeof(format_tab) / sizeof(format_tab[0]); static format_f find_formatter(struct format_params *fp) { int i; uchar fmtchar; abort_unless(fp); fmtchar = fp->fmtchar; for ( i = 0; i < format_tab_len; ++i ) { if ( fmtchar == format_tab[i].fmtchar ) { if ( isupper(fmtchar) ) fp->capver = 1; return format_tab[i].formatter; } } return NULL; } static int emit_format_help(struct emitter *em, const char **fmtp, struct va_list_s *app, int *flen) { struct format_params fp; format_f formatter; abort_unless(em && fmtp && *fmtp && flen); init_format_params(&fp); if ( get_format_flags(fmtp, &fp, app) < 0 ) return -1; /* handle the %% case */ if ( fp.fmtchar == '%' ) { EMIT_CHAR(em, '%'); *flen = 1; return 0; } else if ( fp.fmtchar == '\0' ) { return -1; } if ( (formatter = find_formatter(&fp)) == NULL ) { return -1; } return (*formatter)(em, &fp, app, flen); } int emit_vformat(struct emitter *em, const char *fmt, va_list ap) { int flen, len = 0; struct va_list_s val; const char *fs; va_copy(val.ap, ap); abort_unless(em && fmt); fs = fmt; while ( *fmt != '\0' ) { if ( *fmt == '%' ) { if ( fs != fmt ) { abort_unless(len < INT_MAX); emit_raw(em, fs, fmt - fs); } fmt++; if ( emit_format_help(em, &fmt, &val, &flen) < 0 ) return -1; abort_unless(flen <= INT_MAX - len); len += flen; fs = fmt; } else { ++fmt; ++len; } } if ( fs != fmt ) { abort_unless(len < INT_MAX); emit_raw(em, fs, fmt - fs); } return len; } int emit_format(struct emitter *em, const char *fmt, ...) { va_list ap; int rv; va_start(ap, fmt); rv = emit_vformat(em, fmt, ap); va_end(ap); return rv; } static int prm2type(struct format_table_entry *te, struct format_params *fp) { int pt = te->basetype; if ( pt == FMT_DBLVAL ) { if ( fp->argsize == ARG_LONGDBL ) pt |= FMT_LONGSIZE; else if ( fp->argsize != ARG_REG ) return -1; } else if ( pt == FMT_INTVAL ) { switch(fp->argsize) { case ARG_REG: break; case ARG_HALF: pt |= FMT_HALFSIZE; break; case ARG_LONG: pt |= FMT_LONGSIZE; break; case ARG_LONGLONG: pt |= FMT_LONGLONGSIZE; break; default: return -1; } } return pt; } static int parsefmt(const char *fmt, uchar ptypes[], int npt, int chk) { int i, pi = 0, pt; struct format_params fp; abort_unless(fmt && (npt >= 0) && ((npt == 0) || ptypes != NULL)); while ( *fmt != '\0' ) { if ( *fmt++ == '%' ) { if ( *fmt == '\0' ) break; if ( *fmt == '%' ) { ++fmt; continue; } init_format_params(&fp); if ( get_format_flags(&fmt, &fp, NULL) < 0 ) return -1; for ( i = 0; i < format_tab_len; ++i ) if ( fp.fmtchar == format_tab[i].fmtchar ) break; if ( pi == npt ) return -1; if ( i == format_tab_len ) return -1; if ( (pt = prm2type(&format_tab[i], &fp)) < 0 ) return -1; if ( chk ) { if ( ptypes[pi] != pt ) return -1; } else { ptypes[pi] = pt; } ++pi; } } if ( chk && (pi != npt) ) return -1; return pi; } int emit_format_ckprm(const char *fmt, uchar ptypes[], int npt) { int rv; rv = parsefmt(fmt, ptypes, npt, 1); return (rv < 0) ? rv : 0; } int emit_format_getprm(const char *fmt, uchar ptypes[], int maxpt) { return parsefmt(fmt, ptypes, maxpt, 0); }
github188/catlib
src/pcache.c
<filename>src/pcache.c /* * pcache.c -- Pool cache for fast allocation. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/pcache.h> void pc_init(struct pcache *pc, size_t asiz, size_t pgsiz, uint hiwat, uint maxpools, struct memmgr *mm) { abort_unless(pc); abort_unless(asiz > 0); abort_unless(pgsiz == 0 || (pgsiz >= sizeof(union pc_pool_u) + pl_isiz(asiz, -1))); if ( pgsiz == 0 ) pgsiz = PC_DEF_SIZE; if ( !maxpools ) maxpools = ~0; pc->asiz = asiz + sizeof(cat_pcpad_t); pc->mm = mm; pc->pgsiz = pgsiz; pc->hiwat = hiwat; pc->maxpools = maxpools; pc->npools = 0; l_init(&pc->avail); l_init(&pc->empty); l_init(&pc->full); } void pc_freeall(struct pcache *pc) { struct list *lp; if ( ! pc->mm ) return; while ( (lp = l_pop(&pc->avail)) ) mem_free(pc->mm, lp); while ( (lp = l_pop(&pc->empty)) ) mem_free(pc->mm, lp); } void * pc_alloc(struct pcache *pc) { struct pool *pp; struct pc_pool *pcp, **item; abort_unless(pc); if ( l_isempty(&pc->avail) ) { if ( l_isempty(&pc->full) ) { if ( ! pc->mm || (pc->npools == pc->maxpools) ) return NULL; pcp = mem_get(pc->mm, pc->pgsiz); if ( ! pcp ) return NULL; pc_addpg(pc, pcp, pc->pgsiz); } else { pcp = (struct pc_pool *)pc->full.next; l_rem(&pcp->entry); l_ins(pc->avail.prev, &pcp->entry); } } pcp = (struct pc_pool *)pc->avail.next; pp = &pcp->pool; if ( pp->fill == 1 ) { l_rem(&pcp->entry); l_ins(&pc->empty, &pcp->entry); } item = pl_alloc(pp); *item = pcp; return (char *)item + sizeof(cat_pcpad_t); } void pc_free(void *item) { struct pcache *pc; struct pc_pool *pcp; struct pool *pp; abort_unless(item); item = (char *)item - sizeof(cat_pcpad_t); pcp = *(struct pc_pool **)item; pp = &pcp->pool; if ( pp->fill == 0 ) { l_rem(&pcp->entry); l_ins(pcp->cache->avail.prev, &pcp->entry); } pl_free(pp, item); if ( pp->fill == pp->max ) { pc = pcp->cache; l_rem(&pcp->entry); if ( pc->mm && (pc->hiwat > 0) && (pc->npools > pc->hiwat) ) { mem_free(pc->mm, pcp); pc->npools -= 1; } else { l_ins(&pc->full, &pcp->entry); } } } void pc_addpg(struct pcache *pc, void *page, size_t pgsiz) { struct pc_pool *pcp; abort_unless(pc); abort_unless(page); abort_unless(pgsiz >= sizeof(union pc_pool_u) + pl_isiz(pc->asiz, -1)); pcp = page; pl_init(&pcp->pool, pc->asiz, -1, (char *)pcp + sizeof(union pc_pool_u), pgsiz - sizeof(union pc_pool_u)); pcp->cache = pc; l_ins(&pc->avail, &pcp->entry); pc->npools += 1; } void pc_delpg(void *page) { struct pc_pool *pcp; abort_unless(page); pcp = page; l_rem(&pcp->entry); pcp->cache->npools -= 1; pcp->cache = NULL; }
github188/catlib
test/testtcps.c
/* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <cat/err.h> #include <cat/net.h> #include <cat/io.h> int main(int argc, char *argv[]) { int lfd, fd, n=1; struct sockaddr_storage remaddr; socklen_t alen; char recvbuf[256], strbuf[256]; char *host = NULL; if (argc > 1) host = argv[1]; ERRCK(lfd = tcp_srv(host, "10000")); alen = sizeof(remaddr); fd = accept(lfd, (SA *)&remaddr, &alen); net_tostr((SA *)&remaddr, strbuf, 255); fprintf(stderr, "Connection from %s\n", strbuf); do { ERRCK(n = io_read_upto(fd, recvbuf, 255)); recvbuf[n] = '\0'; fprintf(stderr, "received %s", recvbuf); if ( n > 0 ) ERRCK(io_write(fd, recvbuf, n)); } while (n > 0); close(fd); close(lfd); return 0; }
github188/catlib
include/cat/pspawn.h
/* * spawn.h -- Co-process spawning and management. * * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #ifndef __spawn_h #define __spawn_h #include <cat/cat.h> #ifdef CAT_HAS_POSIX #include <stdio.h> #include <signal.h> #include <sys/types.h> #include <cat/list.h> /* rules: - if type is 'preserve' no other bits must be set - if type contains 'fsrdr' then no buffer flags, or stdio can be set - 'append' can only be set on if 'filerdr' is set and 'out' is set - direction bits must be non-zero (unless type == 'preserve') - buffer bits must be non-zero if STDIO flag is set */ enum { /* input / output flags */ PSFD_IN = 0x0001, /* input to child */ PSFD_OUT = 0x0002, /* output from child */ PSFD_INOUT = 0x0003, /* both input and output to child */ PSFD_DMASK = 0x0003, /* mask i/o bits */ /* modifier flags */ PSFD_STDIO = 0x0004, /* generate stdio FILE for file descriptor */ PSFD_APPEND = 0x0008, /* open in append-mode (output only) */ /* stdio buffering flags: set only if PSFD_STDIO is also set */ PSFD_FULLBUF = 0x0010, /* fully bufferd stdio */ PSFD_NOBUF = 0x0020, /* non-buffered stdio */ PSFD_LINEBUF = 0x0030, /* line buffered stdio */ PSFD_BMASK = 0x0030, /* stdio buffering mask */ /* internal flags, do not set */ /* if neither REMAP nor FSRDR is set, preserve the fd in the child */ PSFD_REMAP = 0x0200, /* re-map fd from parent in child process */ PSFD_FSRDR = 0x0400 /* redirect fd from file system object */ }; struct ps_fd_entry { struct list entry; int locfd; int pipefd; struct list remfds; int type; FILE * file; const char * path; uint mode; }; struct ps_spec { struct list fdelist; }; /* initilize a process spawn specification */ void ps_spec_init(struct ps_spec *spec); /* clean up a process spawn specification */ void ps_spec_cleanup(struct ps_spec *spec); /* copy a process spawn specification */ /* returns 0 on success, -1 on error (most likely lack fo memory) */ int ps_spec_copy(struct ps_spec *dst, const struct ps_spec *src); /* ------------- The steps for setting up I/O for the process are as follows 1) specify which file descriptors from the parent to keep but not remap (ps_spec_keepfd() for each) 2) specify which file descriptors from the parent to remap (ps_spec_add_remap() for each) + for the fde returned from each ps_spec_add_remap() call: - for each fd that the child should have this parent fd mapped to: * ps_fde_addfd() for that target fd 3) specify which file descriptors to have as pipes/sockets to/from/both the parent + ps_spec_add_pipe() for each specifying - whether input, output or both - whether the server side should use stdio - what buffering mode to use if using stdio + for each fde returned from ps_spec_add_pipe() - for each fd that the child should have this pipe mapped to: * ps_fde_addfd() for the target fd 4) specify which file descriptors to redirect from/to a file system object (such as a file) + ps_spec_add_fsrdr() for each specifying - whether to open for input / output or both - whether to open for appending (output-only) + for each fde returned from ps_spec_add_fsrdr() - for each fd that the child should have this file mapped to: * ps_fde_addfd() for the target fd - if the mode should be changed call ps_rdr_set_mode() ------------- */ /* specify to add a pipe to the child process (uni- or bi-directional) */ struct ps_fd_entry *ps_spec_add_pipe(struct ps_spec *spec, int type); /* specify to map fd in the current process to something else in the child */ struct ps_fd_entry *ps_spec_add_remap(struct ps_spec *spec, int fd); /* specify to preserve (not close) fd in the child process */ struct ps_fd_entry *ps_spec_keepfd(struct ps_spec *spec, int fd); /* specify to open file system object "path" in the child process */ struct ps_fd_entry *ps_spec_add_fsrdr(struct ps_spec *spec, int type, const char *path); /* set access permissions for a filesystem redirection object */ void ps_rdr_set_mode(struct ps_fd_entry *psfde, uint mode); /* delete a file descriptor entry from a specification */ void ps_spec_del_fde(struct ps_spec *spec, struct ps_fd_entry *psfde); /* add a file descriptor to a file descriptor entry. This specifies */ /* which file descriptor the child process will have for this entry */ /* returns 0 on success and -1 if out of memory */ int ps_fde_addfd(struct ps_fd_entry *psfde, int fd); /* delete a child file descriptor from a file descriptor entry */ void ps_fde_delfd(struct ps_fd_entry *psfde, int fd); /* * struct ps_spec psf; * struct ps_fd_entry *psfde; * * ps_spec_init(&psf); * ps_fde_addfd(ps_spec_add(&psf, PSFD_STDIO|PSFD_IN|PSFD_LINEBUF), 0); * ps_fde_addfd(ps_spec_add(&psf, PSFD_STDIO|PSFD_OUT|PSFD_FULLBUF), 1); * ps_fde_addfd(ps_spec_add(&psf, PSFD_STDIO|PSFD_OUT|PSFD_NOBUF), 2); */ enum { PSS_INIT, PSS_LAUNCHED, PSS_FINISHED }; struct pspawn { int state; int exit_status; void (*o_sigcld)(int sig); int error; pid_t cpid; struct ps_spec spec; }; /* ignore sigcld signals: this should be called before ps_launch or */ /* ps_run_std() unless your code handles signals itself (which is fine) */ /* this function is just for convenience: signal(SIGCLD, SIG_IGN); */ void ps_ignore_sigcld(); /* spawn co-process trapping i/o as per flags */ /* note that unless handling signals in your program yourself you should */ /* call ps_ignore_sigcld() (only once is necessary) before calling ps_launch */ struct pspawn * ps_launch(char * const argv[], char * const envp[], struct ps_spec *spec); /* get the local fd that corresponds to the remote fd specified */ /* return -1 if remfd is not specified */ int ps_get_locfd(struct pspawn *ps, int remfd); /* get the local FILE entry that corresponds to the remote fd specified */ /* this may well be NULL if that fd isn't specified or if the PSFD_USE_STDIO */ /* was not set */ FILE *ps_get_locfile(struct pspawn *ps, int remfd); /* close the local file/fd for the process: using this API for closing is */ /* CRUCIAL because there is otherwise no way to close the file safely */ /* without a ps_cleanup() */ void ps_closeio(struct pspawn *ps, int remfd); /* return true of the process is still running */ int ps_running(struct pspawn *ps); /* clean up and free data structure. optionally wait for the process to end. */ /* return the exit status. N.B. if wait == 0, then you must not have replaced*/ /* the signal handler and you must have a sigcld handler installed. Otherwise*/ /* the child exiting will kill the process */ int ps_cleanup(struct pspawn *ps, int wait); /* -- utility functions based on previous library calls -- */ /* mode format: /e?([nl]?0)?([nl]?1)?(([nl]?2)|+2)?/ */ /* ex modes: "012", "e0", "n1", "el0n1+2", "1+2", "12"... */ /* if the mode starts with 'e', then the first arg must be the */ /* environment array to use. Otherwise it wipes the current environment */ /* 'n' stands for non-buffered stdio and 'l' stands for line-buffered */ /* 1+2 means redirect stdout and stderr to the same stream */ /* note that unless handling signals in your program yourself you should */ /* call ps_ignore_sigcld() (only once is necessary) before calling ps_launch */ struct pspawn *ps_spawn(const char *mode, ...); /* Same as above but passes environment and cmd explicitly. no "e" in mode */ struct pspawn *ps_spawn_x(const char *mode, char * const *cmd, char * const *envp); #endif /* CAT_HAS_POSIX */ #endif /* __spawn_h */
github188/catlib
src/raw.c
<filename>src/raw.c /* * raw.c -- raw data blob manipulation functions * * by <NAME> * * Copyright 2004-2012 -- See accompanying license * */ #include <cat/cat.h> #include <cat/raw.h> int raw_cmp(void *r1p, void *r2p) { int rv = 0; size_t len; struct raw *r1 = r1p, *r2 = r2p; byte_t *p1, *p2; abort_unless(r1 && r1->data); abort_unless(r2 && r2->data); if ( r1 == r2 ) return 0; p1 = (byte_t *)r1->data; p2 = (byte_t *)r2->data; len = r1->len < r2->len ? r1->len : r2->len; while ( len > 0 && *p1 == *p2 ) { ++p1; ++p2; --len; } if ( len > 0 ) { rv = *p1 - *p2; if ( rv < 0 ) rv = -1; else if ( rv > 0 ) rv =1; } if ( (rv == 0) && (r1->len != r2->len) ) return r1->len < r2->len ? -1 : 1; else return rv; } struct raw *str_to_raw(struct raw *r, char *s, int terminate) { byte_t *t = (byte_t *)s; byte_t *orig = t; abort_unless(r && s); r->data = t; while ( *t != '\0' ) ++t; r->len = t - orig; if ( terminate ) r->len += 1; return r; }
github188/catlib
include/cat/catlibc.h
/* * catlibc.h -- local implementation of standard libc functions. * * by <NAME> * * Copyright 2003-2014 See accompanying license * */ #ifndef __cat_catlibc_h #define __cat_catlibc_h #include <cat/cat.h> struct catlibc_cfg { ulong *heap_base; ulong heap_sz; char *stdin_buf; ulong stdin_bufsz; char *stdout_buf; ulong stdout_bufsz; char *stderr_buf; ulong stderr_bufsz; }; void catlibc_reset(struct catlibc_cfg *cprm); #endif /* __cat_catlibc_h */
github188/catlib
test/testgraph.c
<reponame>github188/catlib /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cat/graph.h> #include <cat/str.h> #include <cat/stduse.h> #include <cat/shell.h> int gnew(struct shell_env *env, int na, char *args[], struct shell_value *rv); int gdel(struct shell_env *env, int na, char *args[], struct shell_value *rv); int add_node(struct shell_env *env, int na, char *args[], struct shell_value *rv); int del_node(struct shell_env *env, int na, char *args[], struct shell_value *rv); int edge(struct shell_env *env, int na, char *args[], struct shell_value *rv); int find(struct shell_env *env, int na, char *args[], struct shell_value *rv); int print(struct shell_env *env, int na, char *args[], struct shell_value *rv); struct shell_cmd_entry cmds[] = { {"gnew", gnew}, {"gdel", gdel}, {"node", add_node}, {"ndel", del_node}, {"edge", edge}, {"edel", edge}, {"print", print}, }; DECLARE_SHELL_ENV(env, cmds); /* Assumption: we'll never need more than INT_MAX graph nodes in the */ /* graph at a time */ struct tgraph { struct graph *graph; struct chtab *node_tab; }; #define IDKEY(_x) (int2ptr((_x) + 1)) int gnew(struct shell_env *env, int na, char *args[], struct shell_value *rv) { int isbi; struct tgraph *g; if ( na != 2 || (shell_arg2int(env, args[1], &isbi) < 0) ) { fprintf(stderr, "usage: gnew <is_bidirectional>\n"); return -1; } g = emalloc(sizeof(*g)); g->graph = gr_new(&estdmm, isbi, 0, 0); g->node_tab = cht_new(32, &cht_std_attr_pkey, NULL, 1); rv->sval_type = SVT_PTR; rv->sval_ptr = g; rv->sval_mm = NULL; rv->sval_free = NULL; return 0; } int gdel(struct shell_env *env, int na, char *args[], struct shell_value *rv) { void *p; struct tgraph *g; int i; if ( na != 2 || (shell_arg2ptr(env, args[1], &p) < 0) ) { fprintf(stderr, "usage: gdel <graph>\n"); return -1; } g = p; gr_free(g->graph); cht_free(g->node_tab); free(g); rv->sval_type = SVT_NIL; rv->sval_int = 0; rv->sval_mm = NULL; rv->sval_free = NULL; return 0; } int add_node(struct shell_env *env, int na, char *args[], struct shell_value *rv) { int id; struct gr_node *n; void *p; struct tgraph *g; if ( na != 3 || (shell_arg2ptr(env, args[1], &p) < 0) || (shell_arg2int(env, args[2], &id) < 0) ) { fprintf(stderr, "usage: node <graph> <id>\n"); return -1; } g = p; if ( cht_get(g->node_tab, IDKEY(id)) ) { fprintf(stderr, "Node %d already exists in the graph\n", id); return -1; } n = gr_add_node(g->graph); n->gr_node_val = id; cht_put(g->node_tab, IDKEY(id), n); printf("Created node %d\n", id); rv->sval_type = SVT_PTR; rv->sval_ptr = n; rv->sval_mm = NULL; rv->sval_free = NULL; return 0; } int del_node(struct shell_env *env, int na, char *args[], struct shell_value *rv) { int id; struct gr_node *n; void *p; struct tgraph *g; if ( (na != 3) || (shell_arg2ptr(env, args[1], &p) < 0) || (shell_arg2int(env, args[2], &id) < 0) ) { fprintf(stderr, "usage: ndel <graph> <nid>\n"); return -1; } g = p; n = cht_get(g->node_tab, IDKEY(id)); if ( !n ) { fprintf(stderr, "couldn't find node %d\n", id); return -1; } gr_del_node(n); cht_del(g->node_tab, IDKEY(id)); rv->sval_type = SVT_NIL; rv->sval_ptr = NULL; rv->sval_mm = NULL; rv->sval_free = NULL; return 0; } int edge(struct shell_env *env, int na, char *args[], struct shell_value *rv) { int id1, id2; struct gr_node *n1, *n2; struct gr_edge *e; struct tgraph *g; void *p; if ( (na != 4) || (shell_arg2ptr(env, args[1], &p) < 0) || (shell_arg2int(env, args[2], &id1) < 0) || (shell_arg2int(env, args[3], &id2) < 0) ) { fprintf(stderr, "usage: %s <graph> <nid> <nid>\n", args[0]); return -1; } g = p; n1 = cht_get(g->node_tab, IDKEY(id1)); if ( !n1 ) { fprintf(stderr, "couldn't find node %d\n", id1); return -1; } n2 = cht_get(g->node_tab, IDKEY(id2)); if ( !n2 ) { fprintf(stderr, "couldn't find node %d\n", id2); return -1; } if ( e = gr_find_edge(n1, n2) ) { if ( strcmp(args[0], "edge") == 0 ) { fprintf(stderr, "edge %d,%d already exists\n", id1, id2); return -1; } else { gr_del_edge(e); } } else { if ( strcmp(args[0], "edel") == 0 ) { fprintf(stderr, "couldn't find edge %d,%d\n", id1, id2); return -1; } else { e = gr_add_edge(n1, n2); e->gr_edge_val = 0; } } rv->sval_type = SVT_NIL; rv->sval_ptr = NULL; rv->sval_mm = NULL; rv->sval_free = NULL; return 0; } int print(struct shell_env *env, int na, char *args[], struct shell_value *rv) { struct list *le; struct gr_node *n; struct gr_edge **e, **eend; int first; void *p; struct tgraph *g; if ( na != 2 || (shell_arg2ptr(env, args[1], &p) < 0) ) { fprintf(stderr, "usage: print <graph>\n"); return -1; } g = p; for ( le = l_head(&g->graph->nodes); le != l_end(&g->graph->nodes); le = le->next ) { n = container(le, struct gr_node, entry); printf("Node %d: ", n->gr_node_val); e = n->out.arr; eend = e + n->out.fill; first = 1; for ( ; e < eend ; ++e ) { if ( first ) { first = 0; } else { printf(", "); } printf("%d", gr_edge_dst(n, *e)->gr_node_val); } printf("\n"); } return 0; } int main(int argc, char *argv[]) { char line[256]; printf("> "); while ( fgets(line, sizeof(line), stdin) ) { if ( line[0] != '\0' && line[strlen(line)-1] != '\n' ) { fprintf(stderr, "line too long!\n"); break; } shell_run(&env, line); printf("> "); } return 0; }
github188/catlib
test/testsort.c
<filename>test/testsort.c /* * by <NAME> * * Copyright 2003-2012 -- See accompanying license * */ #include <cat/sort.h> #include <cat/time.h> #include <cat/aux.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* #define ASIZE 256 */ #define ASIZE 10000 int arr1[ASIZE], arr2[ASIZE], all[ASIZE]; unsigned long long n_intcmps; static unsigned urand(unsigned mod) { return (unsigned)rand() % mod; } int intcmp(const void *i1, const void *i2) { ++n_intcmps; return *(int *)i1 - *(int *)i2; } void test_intarr() { int i; for ( i = 1 ; i < ASIZE ; ++i ) all[i] = i; for ( i = 0; i < ASIZE; ++i ) { #if DEBUGGING arr1[i] = all[urand(ASIZE)]; #else arr1[i] = rand(); #endif } /* insertion sort */ n_intcmps = 0; memcpy(arr2, arr1, sizeof(arr1)); isort_array(arr2, ASIZE, sizeof(int), intcmp); for ( i = 1; i < ASIZE; i++ ) { if (arr2[i-1] > arr2[i]) { printf("Error at position %d for insertion sort\n", i); break; } } if ( i == ASIZE ) printf("insertion sort succeeded with %llu comparisons\n", n_intcmps); /* selection sort */ n_intcmps = 0; memcpy(arr2, arr1, sizeof(arr1)); ssort_array(arr2, ASIZE, sizeof(int), intcmp); for ( i = 1; i < ASIZE; i++ ) { if (arr2[i-1] > arr2[i]) { printf("Error at position %d for selection sort\n", i); break; } } if ( i == ASIZE ) printf("selection sort succeeded with %llu comparisons\n", n_intcmps); /* heap sort */ n_intcmps = 0; memcpy(arr2, arr1, sizeof(arr1)); hsort_array(arr2, ASIZE, sizeof(int), intcmp); for ( i = 1; i < ASIZE; i++ ) { if (arr2[i-1] > arr2[i]) { printf("Error at position %d for heap sort\n", i); break; } } if ( i == ASIZE ) printf("heap sort succeeded with %llu comparisons \n", n_intcmps); /* quick sort */ n_intcmps = 0; memcpy(arr2, arr1, sizeof(arr1)); qsort_array(arr2, ASIZE, sizeof(int), intcmp); for ( i = 1; i < ASIZE; i++ ) { if (arr2[i-1] > arr2[i]) { printf("Error at position %d for quick sort\n", i); break; } } if ( i == ASIZE ) printf("quick sort succeeded with %llu comparisons\n", n_intcmps); /* quick sort 2: array already sorted */ n_intcmps = 0; qsort_array(arr2, ASIZE, sizeof(int), intcmp); for ( i = 1; i < ASIZE; i++ ) { if (arr2[i-1] > arr2[i]) { printf("Error at position %d for quick sort (sorted)\n", i); break; } } if ( i == ASIZE ) printf("quick sort 2 succeeded with %llu comparisons\n", n_intcmps); } unsigned long long n_scmps; int string_compare(const void *s1, const void *s2) { ++n_scmps; return strcmp(*(const char **)s1, *(const char **)s2); } int string_compare2(const void *s1, const void *s2) { ++n_scmps; return strcmp(s1, s2); } #define SARRLEN 10000 char sorig[SARRLEN][80]; char *sarr1[SARRLEN]; char sarr2[SARRLEN][80]; void test_strarr() { int i, j; unsigned long long n; for ( i = 0; i < SARRLEN; i++ ) { int slen = urand(74) + 5; for ( j = 0; j < slen; ++j ) sorig[i][j] = urand(26) + 'a'; sorig[i][j] = '\0'; } for ( i = 0; i < SARRLEN; i++ ) sarr1[i] = sorig[i]; n_scmps = 0; qsort_array(sarr1, SARRLEN, sizeof(sarr1[0]), &string_compare); n = n_scmps; for ( i = 1; i < SARRLEN; ++i ) if ( strcmp(sarr1[i-1], sarr1[i]) > 0 ) { printf("qsort1 error at position %d\n", i); printf("'%s' before '%s'\n", sarr1[i-1], sarr1[i]); break; } if ( i == SARRLEN ) printf("qsort1 for strings succeeded w/%llu comparisons\n", n); memcpy(sarr2, sorig, sizeof(sorig)); n_scmps = 0; qsort_array(sarr2, SARRLEN, sizeof(sarr2[0]), &string_compare2); n = n_scmps; for ( i = 1; i < SARRLEN; ++i ) if ( strcmp(sarr2[i-1], sarr2[i]) > 0 ) { printf("qsort2 error at position %d\n", i); printf("'%s' before '%s'\n", sarr2[i-1], sarr2[i]); break; } if ( i == SARRLEN ) printf("qsort2 for strings succeeded w/%llu comparisons\n", n); n_scmps = 0; qsort_array(sarr2, SARRLEN, sizeof(sarr2[0]), &string_compare2); n = n_scmps; for ( i = 1; i < SARRLEN; ++i ) if ( strcmp(sarr2[i-1], sarr2[i]) > 0 ) { printf("qsort3 error at position %d\n", i); printf("'%s' before '%s'\n", sarr2[i-1], sarr2[i]); break; } if ( i == SARRLEN ) printf("qsort3 for strings succeeded w/%llu comparisons\n", n); } #define SPEEDLEN 100000 #define NTRIES 100 byte_t spd_dst[SPEEDLEN]; void *spd_arr1[SPEEDLEN]; void *spd_arr2[SPEEDLEN]; unsigned long long spd_ncmps; int ptr_cmp(const void *p1, const void *p2) { ++spd_ncmps; return *(const void **)p1 - *(const void **)p2; } void test_speed() { int i, j; struct timeval start, end; for ( i = 0; i < SPEEDLEN; ++i ) spd_arr1[i] = &spd_dst[urand(SPEEDLEN)]; spd_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES ; ++j ) { memcpy(spd_arr2, spd_arr1, sizeof(spd_arr1)); qsort_array(spd_arr2, SPEEDLEN, sizeof(void *), &ptr_cmp); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for my sort: %f\n", NTRIES, SPEEDLEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("my sort used %llu comparisons\n", spd_ncmps); /* make sure spd_arr2 is sorted */ for ( i = 1; i < SPEEDLEN; ++i ) { if ( spd_arr2[i-1] > spd_arr2[i] ) { printf("speed qsort error at position %d:\n", i-1); break; } } spd_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES ; ++j ) { memcpy(spd_arr2, spd_arr1, sizeof(spd_arr1)); qsort(spd_arr2, SPEEDLEN, sizeof(void *), &ptr_cmp); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for std qsort: %f\n", NTRIES, SPEEDLEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("standard qsort used %llu comparisons\n", spd_ncmps); } #define SPEED2LEN 100000 #define NTRIES2 100 #define SPEED2PLEN 256 struct speed2_elem { int key; char pad[SPEED2PLEN]; }; struct speed2_elem spd2_arr1[SPEED2LEN]; struct speed2_elem spd2_arr2[SPEED2LEN]; unsigned long long spd2_ncmps; int spd2_cmp(const void *i1, const void *i2) { ++spd2_ncmps; return *(int *)i1 - *(int *)i2; } void test_speed2() { int i, j; struct timeval start, end; for ( i = 0; i < SPEED2LEN; ++i ) { spd2_arr1[i].key = rand(); for ( j = 0 ; j < SPEED2PLEN ; ++j ) spd2_arr1[i].pad[j] = rand(); } spd2_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES2 ; ++j ) { memcpy(spd2_arr2, spd2_arr1, sizeof(spd2_arr1)); qsort_array(spd2_arr2, SPEED2LEN, sizeof(struct speed2_elem), &spd2_cmp); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for my sort: %f\n", NTRIES2, SPEED2LEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("my sort used %llu comparisons\n", spd2_ncmps); /* make sure spd2_arr2 is sorted */ for ( i = 1; i < SPEED2LEN; ++i ) { if ( spd2_arr2[i-1].key > spd2_arr2[i].key ) { printf("speed 2 qsort error at position %d: " "%d vs %d\n", i-1, spd2_arr2[i-1].key, spd2_arr2[i].key); break; } } spd2_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES2 ; ++j ) { memcpy(spd2_arr2, spd2_arr1, sizeof(spd2_arr1)); qsort(spd2_arr2, SPEED2LEN, sizeof(struct speed2_elem), &spd2_cmp); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for std qsort: %f\n", NTRIES2, SPEED2LEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("standard qsort used %llu comparisons\n", spd2_ncmps); } void *spd3_arr[SPEED2LEN]; void *spd3_save[SPEED2LEN]; int spd3_uniq[SPEED2LEN]; unsigned long long spd3_ncmps; struct speed2_elem t3elem; int spd3_cmp(const void *i1, const void *i2) { ++spd3_ncmps; return ((struct speed2_elem *)(*(void **)i1))->key - ((struct speed2_elem *)(*(void **)i2))->key; } void test_speed3() { int i, j; size_t idx; struct timeval start, end; /* verify that array_to_voidp works */ for ( i = 0; i < SPEED2LEN; ++i ) spd2_arr1[i].key = i; array_to_voidp(spd3_save, spd2_arr1, SPEED2LEN, sizeof(struct speed2_elem)); for ( i = 0; i < SPEED2LEN; ++i ) { int k; if ( (k = ((struct speed2_elem *)spd3_save[i])->key) != i ) { printf("speed 3 qsort error in array_to_voidp at " "%d: %d\n", i, k); break; } } for ( i = 0; i < SPEED2LEN; ++i ) { spd2_arr1[i].key = rand(); for ( j = 0 ; j < SPEED2PLEN ; ++j ) spd2_arr1[i].pad[j] = rand(); } spd3_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES2 ; ++j ) { memcpy(spd2_arr2, spd2_arr1, sizeof(spd2_arr1)); array_to_voidp(spd3_arr, spd2_arr2, SPEED2LEN, sizeof(struct speed2_elem)); qsort_array(spd3_arr, SPEED2LEN, sizeof(void *), &spd3_cmp); if ( j == NTRIES2 - 1 ) memcpy(spd3_save, spd3_arr, sizeof(spd3_arr)); permute_array(spd2_arr2, &t3elem, spd3_arr, SPEED2LEN, sizeof(struct speed2_elem)); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for my sort: %f\n", NTRIES2, SPEED2LEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("my sort used %llu comparisons\n", spd3_ncmps); /* make sure spd3_arr is a true permutation */ memset(spd3_uniq, 0, sizeof(spd3_uniq)); for ( i = 0 ; i < SPEED2LEN; ++i ) { idx = (struct speed2_elem *)spd3_save[i] - spd2_arr2; spd3_uniq[idx] = 1; } for ( i = 0 ; i < SPEED2LEN; ++i ) { if ( spd3_uniq[i] == 0 ) { printf("Element %d is missing in the permuted array!\n", i); break; } } /* make sure spd2_arr2 is sorted */ for ( i = 1; i < SPEED2LEN; ++i ) { if ( spd2_arr2[i-1].key > spd2_arr2[i].key ) { printf("speed 3 qsort error at position %d: " "%d vs %d\n", i-1, spd2_arr2[i-1].key, spd2_arr2[i].key); break; } } spd2_ncmps = 0; gettimeofday(&start, NULL); for ( j = 0 ; j < NTRIES2 ; ++j ) { memcpy(spd2_arr2, spd2_arr1, sizeof(spd2_arr1)); qsort(spd2_arr2, SPEED2LEN, sizeof(struct speed2_elem), &spd2_cmp); } gettimeofday(&end, NULL); printf("Time taken for %u sorts of %u elements for std qsort: %f\n", NTRIES2, SPEED2LEN, (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0); printf("standard qsort used %llu comparisons\n", spd2_ncmps); } int main(int argc, char *argv[]) { size_t i; srand(0); printf("int sort run1\n"); test_intarr(); printf("\n\nrun2\n"); srand(10); test_intarr(); printf("\n\nstring run 1\n"); test_strarr(); printf("\n\nspeed test\n"); test_speed(); printf("\n\nspeed test 2 -- with %u byte elements\n", (unsigned)sizeof(struct speed2_elem)); test_speed2(); printf("\n\nspeed test 3 -- with %u byte elements\n", (unsigned)sizeof(struct speed2_elem)); test_speed3(); return 0; }
github188/catlib
src/cb.c
/* * cb.c -- Event dispatch * * by <NAME> * * Copyright 2003-2012 See accompanying license * */ #include <cat/cb.h> void cb_init(struct callback *cb, callback_f f, void *ctx) { abort_unless(cb); abort_unless(f); l_init(&cb->entry); cb->ctx = ctx; cb->func = f; } int cb_call(struct callback *cb, void *arg) { abort_unless(cb && cb->func); return (*cb->func)(arg, cb); } int cb_run(struct list *l, void *arg) { struct list *node; struct callback *cb; int r; abort_unless(l); node = l_head(l); while ( node != l_end(l) ) { cb = container(node, struct callback, entry); node = node->next; if ( (r = (*cb->func)(arg, cb)) ) return r; } return 0; } void cb_reg(struct list *l, struct callback *cb) { abort_unless(l); abort_unless(cb); l_ins(l, &cb->entry); } void cb_unreg(struct callback *cb) { abort_unless(cb); l_rem(&cb->entry); }