repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
kiwiroy/libtickit
t/47window-dragndrop.c
#include "tickit.h" #include "taplib.h" #include "taplib-tickit.h" #include "taplib-mockterm.h" int next_event = 0; struct SavedEvent { TickitWindow *win; int type; int line, col; } events[9]; int on_input_push(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitMouseEventInfo *info = _info; events[next_event].win = win; events[next_event].type = info->type; events[next_event].line = info->line; events[next_event].col = info->col; next_event++; return 1; } void is_event(struct SavedEvent *ev, int type, int line, int col, char *name) { if(ev->type != type) { fail(name); diag("got type=%d, expected type=%d", ev->type, type); return; } if(ev->line != line || ev->col != col) { fail(name); diag("got position=%d,%d, expected position=%d,%d", ev->col, ev->line, col, line); return; } pass(name); } void is_event_win(struct SavedEvent *ev, int type, int line, int col, TickitWindow *win, char *name) { if(ev->win != win) { fail(name); diag("got win=%p, expected win=%p", ev->win, win); return; } is_event(ev, type, line, col, name); } int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitWindow *root = tickit_window_new_root(tt); // dragging mouse within one window { int event_id = tickit_window_bind_event(root, TICKIT_WINDOW_ON_MOUSE, 0, &on_input_push, NULL); next_event = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 2, 5, 0); is_int(next_event, 1, "pushed 1 event after mouse press"); is_event(events+0, TICKIT_MOUSEEV_PRESS, 2, 5, "event[0] after mouse press"); next_event = 0; press_mouse(TICKIT_MOUSEEV_DRAG, 1, 3, 5, 0); is_int(next_event, 2, "pushed 2 events after drag"); is_event(events+0, TICKIT_MOUSEEV_DRAG_START, 2, 5, "event[0] after mouse drag"); is_event(events+1, TICKIT_MOUSEEV_DRAG, 3, 5, "event[1] after mouse drag"); next_event = 0; press_mouse(TICKIT_MOUSEEV_RELEASE, 1, 3, 5, 0); is_int(next_event, 3, "pushed 3 events after release"); is_event(events+0, TICKIT_MOUSEEV_DRAG_DROP, 3, 5, "event[0] after mouse release"); is_event(events+1, TICKIT_MOUSEEV_DRAG_STOP, 3, 5, "event[1] after mouse release"); is_event(events+2, TICKIT_MOUSEEV_RELEASE, 3, 5, "event[2] after mouse release"); tickit_window_unbind_event_id(root, event_id); } // dragging between windows { TickitWindow *winA = tickit_window_new(root, (TickitRect){ 0, 0, 10, 80}, 0); TickitWindow *winB = tickit_window_new(root, (TickitRect){15, 0, 10, 80}, 0); tickit_window_bind_event(winA, TICKIT_WINDOW_ON_MOUSE, 0, &on_input_push, NULL); tickit_window_bind_event(winB, TICKIT_WINDOW_ON_MOUSE, 0, &on_input_push, NULL); next_event = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 5, 20, 0); press_mouse(TICKIT_MOUSEEV_DRAG, 1, 8, 20, 0); press_mouse(TICKIT_MOUSEEV_DRAG, 1, 12, 20, 0); press_mouse(TICKIT_MOUSEEV_DRAG, 1, 18, 20, 0); press_mouse(TICKIT_MOUSEEV_RELEASE, 1, 18, 20, 0); is_int(next_event, 9, "pushed 9 events"); // press 5,20 is_event_win(events+0, TICKIT_MOUSEEV_PRESS, 5, 20, winA, "event[0]"); // drag 8,20 is_event_win(events+1, TICKIT_MOUSEEV_DRAG_START, 5, 20, winA, "event[1]"); is_event_win(events+2, TICKIT_MOUSEEV_DRAG, 8, 20, winA, "event[2]"); // drag 12,20 is_event_win(events+3, TICKIT_MOUSEEV_DRAG_OUTSIDE, 12, 20, winA, "event[3]"); // drag 18,20 is_event_win(events+4, TICKIT_MOUSEEV_DRAG, 3, 20, winB, "event[4]"); is_event_win(events+5, TICKIT_MOUSEEV_DRAG_OUTSIDE, 18, 20, winA, "event[5]"); // release 18,20 is_event_win(events+6, TICKIT_MOUSEEV_DRAG_DROP, 3, 20, winB, "event[6]"); is_event_win(events+7, TICKIT_MOUSEEV_DRAG_STOP, 18, 20, winA, "event[7]"); is_event_win(events+8, TICKIT_MOUSEEV_RELEASE, 3, 20, winB, "event[8]"); tickit_window_unref(winA); tickit_window_unref(winB); } tickit_window_unref(root); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/51tickit-io.c
<gh_stars>0 #include "tickit.h" #include "tickit-mockterm.h" #include "taplib.h" #include <unistd.h> static int on_call_incr(Tickit *t, TickitEventFlags flags, void *info, void *user) { if(flags & TICKIT_EV_FIRE) { int *ip = user; (*ip)++; tickit_stop(t); } return 1; } int main(int argc, char *argv[]) { Tickit *t = tickit_new_for_term(tickit_mockterm_new(25, 80)); { int fds[2]; if(pipe(fds) != 0) { perror("pipe"); exit(1); } int counter = 0; void *watch = tickit_watch_io_read(t, fds[0], 0, &on_call_incr, &counter); write(fds[1], "OUT\n", 4); tickit_run(t); is_int(counter, 1, "tickit_watch_io_read invokes callback"); tickit_watch_cancel(t, watch); tickit_tick(t, TICKIT_RUN_NOHANG); is_int(counter, 1, "tickit_cancel_watch removes iowatch"); /* TODO: fds[0] is still readready currently but lets just throw it away */ } tickit_unref(t); return exit_status(); }
kiwiroy/libtickit
t/40rootwindow.c
<gh_stars>10-100 #include "tickit.h" #include "taplib.h" #include "taplib-tickit.h" #include "taplib-mockterm.h" int on_event_incr_int(TickitWindow *window, TickitEventFlags flags, void *_info, void *data) { (*(int*)data)++; return 1; } int nextrect = 0; TickitRect rects[4]; int push_on_expose(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitExposeEventInfo *info = _info; rects[nextrect++] = info->rect; return 1; } int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitWindow *root = tickit_window_new_root(tt); // Basics { TickitRect geom = tickit_window_get_geometry(root); is_rect(&geom, "0,0+80,25", "root tickit_window_get_geometry"); is_int(tickit_window_top(root), 0, "root tickit_window_top"); is_int(tickit_window_left(root), 0, "root tickit_window_left"); geom = tickit_window_get_abs_geometry(root); is_rect(&geom, "0,0+80,25", "root tickit_window_get_abs_geometry"); is_int(tickit_window_lines(root), 25, "root tickit_window_lines"); is_int(tickit_window_cols(root), 80, "root tickit_window_cols"); is_int(tickit_window_bottom(root), 25, "root tickit_window_bottom"); is_int(tickit_window_right(root), 80, "root tickit_window_right"); ok(tickit_window_parent(root) == NULL, "root tickit_window_parent"); ok(tickit_window_root(root) == root, "root tickit_window_root"); is_int(tickit_window_children(root), 0, "root tickit_window_children"); ok(tickit_window_get_term(root) == tt, "root tickit_window_get_term"); } // Window pen { TickitPen *pen = tickit_window_get_pen(root); ok(!!pen, "window pen"); ok(!tickit_pen_is_nonempty(pen), "pen has no attrs set"); // TODO: effective pen? } // Scrolling { ok(tickit_window_scroll(root, 1, 0), "window can scroll"); tickit_window_flush(root); is_termlog("Termlog scrolled", SETPEN(), SCROLLRECT(0,0,25,80, 1,0), NULL); tickit_window_scrollrect(root, &(TickitRect){ .top = 5, .left = 0, .lines = 10, .cols = 80 }, 3, 0, NULL); tickit_window_flush(root); is_termlog("Termlog after scrollrect", SETPEN(), SCROLLRECT(5,0,10,80, 3,0), NULL); tickit_window_scrollrect(root, &(TickitRect){ .top = 20, .left = 0, .lines = 1, .cols = 80 }, 0, 1, NULL); tickit_window_flush(root); is_termlog("Termlog after scrollrect rightward", SETPEN(), SCROLLRECT(20,0,1,80, 0,1), NULL); tickit_window_scrollrect(root, &(TickitRect){ .top = 21, .left = 10, .lines = 1, .cols = 70 }, 0, -1, NULL); tickit_window_flush(root); is_termlog("Termlog after scrollrect leftward not fullwidth", SETPEN(), SCROLLRECT(21,10,1,70, 0,-1), NULL); } // Resize events { int geom_changed = 0; tickit_window_bind_event(root, TICKIT_WINDOW_ON_GEOMCHANGE, 0, &on_event_incr_int, &geom_changed); is_int(geom_changed, 0, "geometry not yet changed"); tickit_window_bind_event(root, TICKIT_WINDOW_ON_EXPOSE, 0, &push_on_expose, NULL); tickit_mockterm_resize(tt, 30, 100); tickit_window_flush(root); is_int(tickit_window_lines(root), 30, "root tickit_window_lines after term resize"); is_int(tickit_window_cols(root), 100, "root tickit_window_cols after term resize"); is_int(geom_changed, 1, "geometry changed after term resize"); is_int(nextrect, 2, "two exposed rects after term resize"); is_rect(rects+0, "80,0..100,25", "exposed rects[0]"); is_rect(rects+1, "0,25..100,30", "exposed rects[1]"); } // DESTROY { int destroyed = 0; tickit_window_bind_event(root, TICKIT_WINDOW_ON_DESTROY, 0, &on_event_incr_int, &destroyed); tickit_window_unref(root); ok(destroyed, "TICKIT_WINDOW_ON_DESTROY invoked"); } tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
src/string.c
#include "tickit.h" #include <string.h> struct TickitString { int refcount; size_t len; char str[0]; }; TickitString *tickit_string_new(const char *str, size_t len) { TickitString *s = malloc(sizeof(TickitString) + len + 1); s->refcount = 1; s->len = len; memcpy(s->str, str, len); s->str[len] = '\0'; return s; } TickitString *tickit_string_ref(TickitString *s) { s->refcount++; return s; } void tickit_string_unref(TickitString *s) { if(s->refcount > 1) { s->refcount--; return; } s->refcount = 0; s->str[0] = '\0'; free(s); } const char *tickit_string_get(const TickitString *s) { return s->str; } size_t tickit_string_len(const TickitString *s) { return s->len; }
kiwiroy/libtickit
src/tickit.c
#include "tickit.h" #include "tickit-evloop.h" #include <errno.h> #include <signal.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #define streq(a,b) (!strcmp(a,b)) /* INTERNAL */ TickitWindow* tickit_window_new_root2(Tickit *t, TickitTerm *term); struct TickitWatch { TickitWatch *next; Tickit *t; // uncounted enum { WATCH_NONE, WATCH_IO, WATCH_TIMER, WATCH_LATER, } type; TickitBindFlags flags; TickitCallbackFn *fn; void *user; union { void *ptr; int i; } evdata; union { struct { int fd; } io; struct { struct timeval at; } timer; }; }; extern TickitEventHooks tickit_evloop_default; struct Tickit { int refcount; TickitTerm *term; TickitWindow *rootwin; TickitWatch *iowatches, *timers, *laters; TickitEventHooks *evhooks; void *evdata; struct TickitTerminfoHook ti_hook; unsigned int done_setup : 1, use_altscreen : 1; }; static int on_term_timeout(Tickit *t, TickitEventFlags flags, void *info, void *user); static int on_term_timeout(Tickit *t, TickitEventFlags flags, void *info, void *user) { int timeout = tickit_term_input_check_timeout_msec(t->term); if(timeout > -1) tickit_watch_timer_after_msec(t, timeout, 0, on_term_timeout, NULL); return 0; } static int on_term_readable(Tickit *t, TickitEventFlags flags, void *info, void *user) { tickit_term_input_readable(t->term); on_term_timeout(t, TICKIT_EV_FIRE, NULL, NULL); return 0; } static void setterm(Tickit *t, TickitTerm *tt); static void setterm(Tickit *t, TickitTerm *tt) { t->term = tt; /* take ownership */ tickit_watch_io_read(t, tickit_term_get_input_fd(tt), 0, on_term_readable, NULL); } static void setupterm(Tickit *t) { TickitTerm *tt = tickit_get_term(t); tickit_term_await_started_msec(tt, 50); if(t->use_altscreen) tickit_term_setctl_int(tt, TICKIT_TERMCTL_ALTSCREEN, 1); tickit_term_setctl_int(tt, TICKIT_TERMCTL_CURSORVIS, 0); tickit_term_setctl_int(tt, TICKIT_TERMCTL_MOUSE, TICKIT_TERM_MOUSEMODE_DRAG); tickit_term_setctl_int(tt, TICKIT_TERMCTL_KEYPAD_APP, 1); tickit_term_clear(tt); tickit_term_flush(tt); t->done_setup = true; } static void teardownterm(Tickit *t) { t->done_setup = false; } Tickit *tickit_new_with_evloop(TickitTerm *tt, TickitEventHooks *evhooks, void *initdata) { Tickit *t = malloc(sizeof(Tickit)); if(!t) return NULL; t->refcount = 1; t->term = NULL; t->rootwin = NULL; t->evhooks = evhooks; t->evdata = (*t->evhooks->init)(t, initdata); if(!t->evdata) goto abort; t->iowatches = NULL; t->timers = NULL; t->laters = NULL; t->ti_hook.getstr = NULL; t->done_setup = false; t->use_altscreen = true; if(tt) setterm(t, tt); return t; abort: free(t); return NULL; } Tickit *tickit_new_for_term(TickitTerm *tt) { return tickit_new_with_evloop(tt, &tickit_evloop_default, NULL); } Tickit *tickit_new_stdio(void) { return tickit_new_for_term(NULL); } static void destroy_watchlist(Tickit *t, TickitWatch *watches, void (*cancelfunc)(void *data, TickitWatch *watch)) { TickitWatch *this, *next; for(this = watches; this; this = next) { next = this->next; if(this->flags & (TICKIT_BIND_UNBIND|TICKIT_BIND_DESTROY)) (*this->fn)(this->t, TICKIT_EV_UNBIND|TICKIT_EV_DESTROY, NULL, this->user); if(cancelfunc) (*cancelfunc)(t->evdata, this); free(this); } } static void tickit_destroy(Tickit *t) { if(t->done_setup) teardownterm(t); if(t->rootwin) tickit_window_unref(t->rootwin); if(t->term) tickit_term_unref(t->term); if(t->iowatches) destroy_watchlist(t, t->iowatches, t->evhooks->cancel_io); if(t->timers) destroy_watchlist(t, t->timers, t->evhooks->cancel_timer); if(t->laters) destroy_watchlist(t, t->laters, t->evhooks->cancel_later); (*t->evhooks->destroy)(t->evdata); free(t); } Tickit *tickit_ref(Tickit *t) { t->refcount++; return t; } void tickit_unref(Tickit *t) { t->refcount--; if(!t->refcount) tickit_destroy(t); } TickitTerm *tickit_get_term(Tickit *t) { if(!t->term) { /* Don't use tickit_term_open_stdio() because that observes SIGWINCH */ struct TickitTermBuilder builder = { 0 }; if(t->ti_hook.getstr) builder.ti_hook = &t->ti_hook; TickitTerm *tt = tickit_term_build(&builder); if(!tt) return NULL; tickit_term_set_input_fd(tt, STDIN_FILENO); tickit_term_set_output_fd(tt, STDOUT_FILENO); tickit_term_set_output_buffer(tt, 4096); setterm(t, tt); } return t->term; } TickitWindow *tickit_get_rootwin(Tickit *t) { if(!t->rootwin) { TickitTerm *tt = tickit_get_term(t); if(!tt) return NULL; t->rootwin = tickit_window_new_root2(t, tt); } return t->rootwin; } bool tickit_getctl_int(Tickit *t, TickitCtl ctl, int *value) { switch(ctl) { case TICKIT_CTL_USE_ALTSCREEN: *value = t->use_altscreen; return true; case TICKIT_N_CTLS: ; } return false; } bool tickit_setctl_int(Tickit *t, TickitCtl ctl, int value) { switch(ctl) { case TICKIT_CTL_USE_ALTSCREEN: t->use_altscreen = value; return true; case TICKIT_N_CTLS: ; } return false; } void tickit_hook_terminfo(Tickit *t, const char *(*getstr)(const char *name, const char *value, void *data), void *data) { t->ti_hook.getstr = getstr; t->ti_hook.data = data; } // TODO: copy the entire SIGWINCH-like structure from term.c // For now we only handle atmost-one running Tickit instance static Tickit *running_tickit; static void sigint(int sig) { if(running_tickit) tickit_stop(running_tickit); } void tickit_tick(Tickit *t, TickitRunFlags flags) { if(!t->done_setup && !(flags & TICKIT_RUN_NOSETUP)) setupterm(t); (*t->evhooks->run)(t->evdata, TICKIT_RUN_ONCE | flags); } void tickit_run(Tickit *t) { running_tickit = t; signal(SIGINT, sigint); if(!t->done_setup) setupterm(t); (*t->evhooks->run)(t->evdata, TICKIT_RUN_DEFAULT); running_tickit = NULL; } void tickit_stop(Tickit *t) { return (*t->evhooks->stop)(t->evdata); } void *tickit_watch_io_read(Tickit *t, int fd, TickitBindFlags flags, TickitCallbackFn *fn, void *user) { TickitWatch *watch = malloc(sizeof(TickitWatch)); if(!watch) return NULL; watch->next = NULL; watch->t = t; watch->type = WATCH_IO; watch->flags = flags & (TICKIT_BIND_UNBIND|TICKIT_BIND_UNBIND); watch->fn = fn; watch->user = user; watch->io.fd = fd; if(!(*t->evhooks->io_read)(t->evdata, fd, flags, watch)) goto fail; TickitWatch **prevp = &t->iowatches; while(*prevp) prevp = &(*prevp)->next; watch->next = *prevp; *prevp = watch; return watch; fail: free(watch); return NULL; } void *tickit_watch_timer_at_tv(Tickit *t, const struct timeval *at, TickitBindFlags flags, TickitCallbackFn *fn, void *user) { TickitWatch *watch = malloc(sizeof(TickitWatch)); if(!watch) return NULL; watch->next = NULL; watch->t = t; watch->type = WATCH_TIMER; watch->flags = flags & (TICKIT_BIND_UNBIND|TICKIT_BIND_DESTROY); watch->fn = fn; watch->user = user; watch->timer.at = *at; if(t->evhooks->timer) if(!(*t->evhooks->timer)(t->evdata, at, flags, watch)) goto fail; TickitWatch **prevp = &t->timers; /* Try to insert in-order at matching timestamp */ while(*prevp && !timercmp(&(*prevp)->timer.at, at, >)) prevp = &(*prevp)->next; watch->next = *prevp; *prevp = watch; return watch; fail: free(watch); return NULL; } void *tickit_watch_timer_at_epoch(Tickit *t, time_t at, TickitBindFlags flags, TickitCallbackFn *func, void *user) { return tickit_watch_timer_at_tv(t, &(struct timeval){ .tv_sec = at, .tv_usec = 0, }, flags, func, user); } void *tickit_watch_timer_after_tv(Tickit *t, const struct timeval *after, TickitBindFlags flags, TickitCallbackFn *fn, void *user) { struct timeval at; gettimeofday(&at, NULL); /* at + after ==> at */ timeradd(&at, after, &at); return tickit_watch_timer_at_tv(t, &at, flags, fn, user); } void *tickit_watch_timer_after_msec(Tickit *t, int msec, TickitBindFlags flags, TickitCallbackFn *fn, void *user) { return tickit_watch_timer_after_tv(t, &(struct timeval){ .tv_sec = msec / 1000, .tv_usec = (msec % 1000) * 1000, }, flags, fn, user); } void *tickit_watch_later(Tickit *t, TickitBindFlags flags, TickitCallbackFn *fn, void *user) { TickitWatch *watch = malloc(sizeof(TickitWatch)); if(!watch) return NULL; watch->next = NULL; watch->t = t; watch->type = WATCH_LATER; watch->flags = flags & (TICKIT_BIND_UNBIND|TICKIT_BIND_DESTROY); watch->fn = fn; watch->user = user; if(t->evhooks->later) if(!(*t->evhooks->later)(t->evdata, flags, watch)) goto fail; TickitWatch **prevp = &t->laters; while(*prevp) prevp = &(*prevp)->next; watch->next = *prevp; *prevp = watch; return watch; fail: free(watch); return NULL; } void tickit_watch_cancel(Tickit *t, void *_watch) { TickitWatch *watch = _watch; TickitWatch **thisp; switch(watch->type) { case WATCH_IO: thisp = &t->iowatches; break; case WATCH_TIMER: thisp = &t->timers; break; case WATCH_LATER: thisp = &t->laters; break; default: return; } while(*thisp) { TickitWatch *this = *thisp; if(this == watch) { *thisp = this->next; if(this->flags & TICKIT_BIND_UNBIND) (*this->fn)(t, TICKIT_EV_UNBIND, NULL, this->user); switch(this->type) { case WATCH_IO: (*t->evhooks->cancel_io)(t->evdata, this); break; case WATCH_TIMER: if(t->evhooks->cancel_timer) (*t->evhooks->cancel_timer)(t->evdata, this); break; case WATCH_LATER: if(t->evhooks->cancel_later) (*t->evhooks->cancel_later)(t->evdata, this); break; default: ; } free(this); } if(!thisp || !*thisp) break; thisp = &(*thisp)->next; } } int tickit_evloop_next_timer_msec(Tickit *t) { if(t->laters) return 0; if(!t->timers) return -1; struct timeval now, delay; gettimeofday(&now, NULL); /* timers->timer.at - now ==> delay */ timersub(&t->timers->timer.at, &now, &delay); int msec = (delay.tv_sec * 1000) + (delay.tv_usec / 1000); if(msec < 0) msec = 0; return msec; } void tickit_evloop_invoke_timers(Tickit *t) { /* detach the later queue before running any events */ TickitWatch *later = t->laters; t->laters = NULL; if(t->timers) { struct timeval now; gettimeofday(&now, NULL); /* timer queue is stored ordered, so we can just eat a prefix * of it */ TickitWatch *this = t->timers; while(this) { if(timercmp(&this->timer.at, &now, >)) break; /* TODO: consider what info might point at */ (*this->fn)(this->t, TICKIT_EV_FIRE|TICKIT_EV_UNBIND, NULL, this->user); TickitWatch *next = this->next; free(this); this = next; } t->timers = this; } while(later) { (*later->fn)(later->t, TICKIT_EV_FIRE|TICKIT_EV_UNBIND, NULL, later->user); TickitWatch *next = later->next; free(later); later = next; } } void *tickit_evloop_get_watch_data(TickitWatch *watch) { return watch->evdata.ptr; } void tickit_evloop_set_watch_data(TickitWatch *watch, void *data) { watch->evdata.ptr = data; } int tickit_evloop_get_watch_data_int(TickitWatch *watch) { return watch->evdata.i; } void tickit_evloop_set_watch_data_int(TickitWatch *watch, int data) { watch->evdata.i = data; } void tickit_evloop_invoke_watch(TickitWatch *watch, TickitEventFlags flags) { (*watch->fn)(watch->t, flags, NULL, watch->user); /* Remove oneshot watches from the list */ TickitWatch **prevp; switch(watch->type) { case WATCH_NONE: case WATCH_IO: return; case WATCH_TIMER: prevp = &watch->t->timers; break; case WATCH_LATER: prevp = &watch->t->laters; break; } while(*prevp) { if(*prevp == watch) { *prevp = watch->next; watch->next = NULL; watch->type = WATCH_NONE; free(watch); return; } prevp = &(*prevp)->next; } } void tickit_evloop_sigwinch(Tickit *t) { if(!t->term) return; tickit_term_refresh_size(t->term); } const char *tickit_ctlname(TickitCtl ctl) { switch(ctl) { case TICKIT_CTL_USE_ALTSCREEN: return "use-altscreen"; case TICKIT_N_CTLS: ; } return NULL; } TickitCtl tickit_lookup_ctl(const char *name) { const char *s; for(TickitCtl ctl = 1; ctl < TICKIT_N_CTLS; ctl++) if((s = tickit_ctlname(ctl)) && streq(name, s)) return ctl; return -1; } TickitType tickit_ctltype(TickitCtl ctl) { switch(ctl) { case TICKIT_CTL_USE_ALTSCREEN: return TICKIT_TYPE_BOOL; case TICKIT_N_CTLS: ; } return TICKIT_TYPE_NONE; } int tickit_version_major(void) { return TICKIT_VERSION_MAJOR; } int tickit_version_minor(void) { return TICKIT_VERSION_MINOR; } int tickit_version_patch(void) { return TICKIT_VERSION_PATCH; }
kiwiroy/libtickit
examples/evloop-libuv.c
<reponame>kiwiroy/libtickit<gh_stars>0 #ifdef __GLIBC__ # define _XOPEN_SOURCE 500 /* strdup */ #endif #include "tickit.h" #include "tickit-evloop.h" #include <errno.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <uv.h> TickitKeyEventInfo lastkey; TickitWindow *keywin; TickitMouseEventInfo lastmouse; TickitWindow *mousewin; int counter = 0; TickitWindow *timerwin; static TickitPen *mkpen_highlight(void) { static TickitPen *pen; if(!pen) pen = tickit_pen_new_attrs( TICKIT_PEN_FG, 3, TICKIT_PEN_BOLD, 1, 0); return pen; } static void render_modifier(TickitRenderBuffer *rb, int mod) { if(!mod) return; int pipe = 0; tickit_renderbuffer_text(rb, "<"); if(mod & TICKIT_MOD_SHIFT) tickit_renderbuffer_text(rb, pipe++ ? "|SHIFT" : "SHIFT"); if(mod & TICKIT_MOD_ALT) tickit_renderbuffer_text(rb, pipe++ ? "|ALT" : "ALT"); if(mod & TICKIT_MOD_CTRL) tickit_renderbuffer_text(rb, pipe++ ? "|CTRL" : "CTRL"); tickit_renderbuffer_text(rb, ">"); } static int render_key(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitExposeEventInfo *info = _info; TickitRenderBuffer *rb = info->rb; tickit_renderbuffer_eraserect(rb, &info->rect); tickit_renderbuffer_goto(rb, 0, 0); { tickit_renderbuffer_savepen(rb); tickit_renderbuffer_setpen(rb, mkpen_highlight()); tickit_renderbuffer_text(rb, "Key:"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_goto(rb, 2, 2); switch(lastkey.type) { case TICKIT_KEYEV_TEXT: tickit_renderbuffer_text(rb, "text "); break; case TICKIT_KEYEV_KEY: tickit_renderbuffer_text(rb, "key "); break; default: return 0; } tickit_renderbuffer_text(rb, lastkey.str); render_modifier(rb, lastkey.mod); return 1; } static int event_key(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitKeyEventInfo *info = _info; if(lastkey.str) free((void *)lastkey.str); lastkey = *info; lastkey.str = strdup(info->str); tickit_window_expose(keywin, NULL); return 1; } static int render_mouse(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitExposeEventInfo *info = _info; TickitRenderBuffer *rb = info->rb; tickit_renderbuffer_eraserect(rb, &info->rect); tickit_renderbuffer_goto(rb, 0, 0); { tickit_renderbuffer_savepen(rb); tickit_renderbuffer_setpen(rb, mkpen_highlight()); tickit_renderbuffer_text(rb, "Mouse:"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_goto(rb, 2, 2); switch(lastmouse.type) { case TICKIT_MOUSEEV_PRESS: tickit_renderbuffer_text(rb, "press "); break; case TICKIT_MOUSEEV_DRAG: tickit_renderbuffer_text(rb, "drag "); break; case TICKIT_MOUSEEV_RELEASE: tickit_renderbuffer_text(rb, "release "); break; case TICKIT_MOUSEEV_WHEEL: tickit_renderbuffer_text(rb, "wheel "); break; default: return 0; } if(lastmouse.type == TICKIT_MOUSEEV_WHEEL) { tickit_renderbuffer_text(rb, lastmouse.button == TICKIT_MOUSEWHEEL_DOWN ? "down" : "up"); } else { tickit_renderbuffer_textf(rb, "button %d", lastmouse.button); } tickit_renderbuffer_textf(rb, " at (%d,%d)", lastmouse.line, lastmouse.col); render_modifier(rb, lastmouse.mod); return 1; } static int event_mouse(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitMouseEventInfo *info = _info; lastmouse = *info; tickit_window_expose(mousewin, NULL); return 1; } static int render_timer(TickitWindow *win, TickitEventFlags flags, void *_info, void *user) { int *counterp = user; TickitExposeEventInfo *info = _info; TickitRenderBuffer *rb = info->rb; tickit_renderbuffer_eraserect(rb, &info->rect); tickit_renderbuffer_goto(rb, 0, 0); { tickit_renderbuffer_savepen(rb); tickit_renderbuffer_setpen(rb, mkpen_highlight()); tickit_renderbuffer_text(rb, "Counter:"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_goto(rb, 2, 2); tickit_renderbuffer_textf(rb, "%d", *counterp); return 1; } static int on_timer(Tickit *t, TickitEventFlags flags, void *_info, void *user); static int on_timer(Tickit *t, TickitEventFlags flags, void *_info, void *user) { int *counterp = user; (*counterp)++; tickit_window_expose(timerwin, NULL); tickit_watch_timer_after_msec(t, 1000, 0, &on_timer, user); return 0; } static int render_root(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitExposeEventInfo *info = _info; TickitRenderBuffer *rb = info->rb; int right = tickit_window_cols(win) - 1; int bottom = tickit_window_lines(win) - 1; tickit_renderbuffer_eraserect(rb, &(TickitRect){ .top = 0, .left = 0, .lines = bottom+1, .cols = right+1, }); static TickitPen *pen_blue; if(!pen_blue) pen_blue = tickit_pen_new_attrs( TICKIT_PEN_FG, 4+8, 0); static TickitPen *pen_white; if(!pen_white) pen_white = tickit_pen_new_attrs( TICKIT_PEN_FG, 7+8, 0); // Draw a horizontal size marker bar { tickit_renderbuffer_setpen(rb, pen_blue); tickit_renderbuffer_hline_at(rb, 1, 0, right, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 0, 2, 0, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 0, 2, right, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_setpen(rb, pen_white); tickit_renderbuffer_goto(rb, 1, (right / 2) - 2); tickit_renderbuffer_textf(rb, " %d ", right + 1); // cols } int left = right - 4; // Draw a vertical size marker bar { tickit_renderbuffer_setpen(rb, pen_blue); tickit_renderbuffer_vline_at(rb, 0, bottom, left + 2, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 0, left, right, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, bottom, left, right, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_setpen(rb, pen_white); tickit_renderbuffer_goto(rb, (bottom / 2) - 1, left); tickit_renderbuffer_textf(rb, "%d", bottom + 1); // lines } return 1; } static int event_resize(TickitWindow *root, TickitEventFlags flags, void *_info, void *data) { int cols = tickit_window_cols(root); tickit_window_set_geometry(keywin, (TickitRect){ .top = 2, .left = 2, .lines = 3, .cols = cols - 7 }); tickit_window_set_geometry(mousewin, (TickitRect){ .top = 8, .left = 2, .lines = 3, .cols = cols - 7 }); tickit_window_set_geometry(timerwin, (TickitRect){ .top = 15, .left = 2, .lines = 3, .cols = cols - 7 }); tickit_window_expose(root, NULL); return 1; } TickitEventHooks libuv_evhooks; int main(int argc, char *argv[]) { Tickit *t = tickit_new_with_evloop(NULL, &libuv_evhooks, NULL); TickitWindow *root = tickit_get_rootwin(t); if(!root) { fprintf(stderr, "Cannot create TickitTerm - %s\n", strerror(errno)); return 1; } keywin = tickit_window_new(root, (TickitRect){ .top = 2, .left = 2, .lines = 3, .cols = tickit_window_cols(root) - 7 }, 0); tickit_window_bind_event(keywin, TICKIT_WINDOW_ON_EXPOSE, 0, &render_key, NULL); tickit_window_bind_event(root, TICKIT_WINDOW_ON_KEY, 0, &event_key, NULL); mousewin = tickit_window_new(root, (TickitRect){ .top = 8, .left = 2, .lines = 3, .cols = tickit_window_cols(root) - 7 }, 0); tickit_window_bind_event(mousewin, TICKIT_WINDOW_ON_EXPOSE, 0, &render_mouse, NULL); tickit_window_bind_event(root, TICKIT_WINDOW_ON_MOUSE, 0, &event_mouse, NULL); timerwin = tickit_window_new(root, (TickitRect){ .top = 15, .left = 2, .lines = 3, .cols = tickit_window_cols(root) - 7 }, 0); tickit_window_bind_event(timerwin, TICKIT_WINDOW_ON_EXPOSE, 0, &render_timer, &counter); tickit_window_bind_event(root, TICKIT_WINDOW_ON_EXPOSE, 0, &render_root, NULL); tickit_window_bind_event(root, TICKIT_WINDOW_ON_GEOMCHANGE, 0, &event_resize, NULL); tickit_watch_timer_after_msec(t, 1000, 0, &on_timer, &counter); tickit_window_take_focus(root); tickit_window_set_cursor_visible(root, false); tickit_run(t); tickit_window_close(root); tickit_unref(t); return 0; } /* * UV event loop integration */ static void destroy_handle(uv_handle_t *handle) { free(handle); } typedef struct { uv_loop_t *loop; uv_async_t *stop; uv_signal_t *sigwinch; } EventLoopData; static void el_sigwinch(uv_signal_t *handle, int signum) { Tickit *t = handle->data; tickit_evloop_sigwinch(t); } static void *el_init(Tickit *t, void *initdata) { EventLoopData *evdata = malloc(sizeof(EventLoopData)); if(!evdata) return NULL; if(initdata) evdata->loop = initdata; else evdata->loop = uv_default_loop(); if(!evdata->loop) goto abort; // No callback; we're just using this to wake the event loop up when we want to stop // See also https://github.com/libuv/libuv/issues/2173 evdata->stop = malloc(sizeof(uv_async_t)); uv_async_init(evdata->loop, evdata->stop, NULL); evdata->sigwinch = malloc(sizeof(uv_signal_t)); uv_signal_init(evdata->loop, evdata->sigwinch); uv_signal_start(evdata->sigwinch, el_sigwinch, SIGWINCH); evdata->sigwinch->data = t; return evdata; abort: free(evdata); return NULL; } static void el_destroy(void *data) { } static void el_run(void *data, TickitRunFlags flags) { EventLoopData *evdata = data; if(flags & TICKIT_RUN_NOHANG) uv_run(evdata->loop, UV_RUN_NOWAIT); else if(flags & TICKIT_RUN_ONCE) uv_run(evdata->loop, UV_RUN_ONCE); else uv_run(evdata->loop, UV_RUN_DEFAULT); } static void el_stop(void *data) { EventLoopData *evdata = data; uv_stop(evdata->loop); uv_async_send(evdata->stop); } static void fire_io_event(uv_poll_t *handle, int status, int events) { TickitWatch *watch = handle->data; if(events & UV_READABLE) { tickit_evloop_invoke_watch(watch, TICKIT_EV_FIRE); } } static bool el_io_read(void *data, int fd, TickitBindFlags flags, TickitWatch *watch) { EventLoopData *evdata = data; uv_poll_t *handle = malloc(sizeof(uv_poll_t)); if(!handle) return false; uv_poll_init(evdata->loop, handle, fd); uv_poll_start(handle, UV_READABLE, &fire_io_event); handle->data = watch; tickit_evloop_set_watch_data(watch, handle); return true; } static void el_cancel_io(void *data, TickitWatch *watch) { uv_poll_t *handle = tickit_evloop_get_watch_data(watch); uv_poll_stop(handle); uv_close((uv_handle_t *)handle, &destroy_handle); } static void fire_timer_event(uv_timer_t *handle) { TickitWatch *watch = handle->data; tickit_evloop_invoke_watch(watch, TICKIT_EV_FIRE); uv_timer_stop(handle); uv_close((uv_handle_t *)handle, &destroy_handle); } static bool el_timer(void *data, const struct timeval *at, TickitBindFlags flags, TickitWatch *watch) { EventLoopData *evdata = data; struct timeval now; gettimeofday(&now, NULL); long msec = (at->tv_sec - now.tv_sec) * 1000 + (at->tv_usec - now.tv_usec) / 1000; uv_timer_t *handle = malloc(sizeof(uv_timer_t)); if(!handle) return false; uv_timer_init(evdata->loop, handle); uv_timer_start(handle, &fire_timer_event, msec, 0); handle->data = watch; tickit_evloop_set_watch_data(watch, handle); return true; } static void el_cancel_timer(void *data, TickitWatch *watch) { uv_timer_t *handle = tickit_evloop_get_watch_data(watch); uv_timer_stop(handle); uv_close((uv_handle_t *)handle, &destroy_handle); } static void fire_later_event(uv_idle_t *handle) { TickitWatch *watch = handle->data; tickit_evloop_invoke_watch(watch, TICKIT_EV_FIRE); uv_idle_stop(handle); uv_close((uv_handle_t *)handle, &destroy_handle); } static bool el_later(void *data, TickitBindFlags flags, TickitWatch *watch) { EventLoopData *evdata = data; uv_idle_t *handle = malloc(sizeof(uv_idle_t)); if(!handle) return false; uv_idle_init(evdata->loop, handle); uv_idle_start(handle, &fire_later_event); handle->data = watch; tickit_evloop_set_watch_data(watch, handle); return true; } static void el_cancel_later(void *data, TickitWatch *watch) { uv_idle_t *handle = tickit_evloop_get_watch_data(watch); uv_idle_stop(handle); uv_close((uv_handle_t *)handle, &destroy_handle); } TickitEventHooks libuv_evhooks = { .init = el_init, .destroy = el_destroy, .run = el_run, .stop = el_stop, .io_read = el_io_read, .cancel_io = el_cancel_io, .timer = el_timer, .cancel_timer = el_cancel_timer, .later = el_later, .cancel_later = el_cancel_later, };
kiwiroy/libtickit
t/13term-pen.c
#include "tickit.h" #include "taplib.h" #include <string.h> void output(TickitTerm *tt, const char *bytes, size_t len, void *user) { char *buffer = user; strncat(buffer, bytes, len); } int main(int argc, char *argv[]) { TickitTerm *tt; char buffer[1024] = { 0 }; tt = tickit_term_new_for_termtype("xterm"); tickit_term_set_output_func(tt, output, buffer); // setpen empty { TickitPen *pen = tickit_pen_new(); buffer[0] = 0; tickit_term_setpen(tt, pen); is_str_escape(buffer, "\e[m", "buffer after setpen empty"); tickit_pen_unref(pen); } // adjust boolean attributes { TickitPen *pen = tickit_pen_new(); tickit_pen_set_bool_attr(pen, TICKIT_PEN_BOLD, 1); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[1m", "buffer contains SGR 1 for chpen bold"); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "", "chpen again is a no-op"); tickit_pen_set_bool_attr(pen, TICKIT_PEN_BOLD, 0); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[m", "chpen disables bold"); tickit_pen_set_bool_attr(pen, TICKIT_PEN_BOLD, 1); tickit_pen_set_bool_attr(pen, TICKIT_PEN_UNDER, 1); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[1;4m", "chpen enables bold and under"); tickit_pen_set_bool_attr(pen, TICKIT_PEN_BOLD, 0); tickit_pen_clear_attr(pen, TICKIT_PEN_UNDER); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[22m", "chpen disables bold"); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "", "chpen disable bold again is no-op"); tickit_pen_clear_attr(pen, TICKIT_PEN_BOLD); tickit_pen_set_bool_attr(pen, TICKIT_PEN_UNDER, 0); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[m", "chpen disable under is reset"); tickit_pen_clear_attr(pen, TICKIT_PEN_UNDER); tickit_pen_unref(pen); } // adjust colours { TickitPen *pen = tickit_pen_new(); tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, 1); tickit_pen_set_colour_attr(pen, TICKIT_PEN_BG, 5); buffer[0] = 0; tickit_term_setpen(tt, pen); is_str_escape(buffer, "\e[31;45m", "chpen foreground+background"); tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, 9); tickit_pen_clear_attr(pen, TICKIT_PEN_BG); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[91m", "chpen foreground high"); tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, 123); buffer[0] = 0; tickit_term_chpen(tt, pen); is_str_escape(buffer, "\e[38;5;123m", "chpen foreground xterm256"); tickit_pen_clear_attr(pen, TICKIT_PEN_FG); tickit_pen_set_bool_attr(pen, TICKIT_PEN_UNDER, 1); buffer[0] = 0; tickit_term_setpen(tt, pen); is_str_escape(buffer, "\e[39;49;4m", "setpen resets colours, enables under"); tickit_pen_unref(pen); } tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/36renderbuffer-blit.c
#include "tickit.h" #include "taplib.h" #include "taplib-mockterm.h" int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitRenderBuffer *screen, *window; screen = tickit_renderbuffer_new(25, 80); window = tickit_renderbuffer_new(10, 20); // Basic blit { tickit_renderbuffer_text_at(window, 0, 0, "Hello"); tickit_renderbuffer_char_at(window, 1, 1, 'A'); tickit_renderbuffer_skip_at(window, 2, 2, 2); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer basic blitting", GOTO(0,0), SETPEN(), PRINT("Hello"), GOTO(1,1), SETPEN(), PRINT("A"), NULL); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blitting doesn't wipe src rb", GOTO(0,0), SETPEN(), PRINT("Hello"), GOTO(1,1), SETPEN(), PRINT("A"), NULL); } // Blitting an erase wipes underlying content { tickit_renderbuffer_reset(window); tickit_renderbuffer_text_at(screen, 0, 0, "Hello"); tickit_renderbuffer_erase_at(window, 0, 0, 4); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blit can erase underlying content", GOTO(0,0), SETPEN(), ERASECH(4,1), SETPEN(), PRINT("o"), NULL); } // Blitting text that spans a mask { tickit_renderbuffer_reset(window); TickitRect mask = { .top = 0, .left = 2, .lines = 1, .cols = 1 }; tickit_renderbuffer_mask(window, &mask); tickit_renderbuffer_text_at(window, 0, 0, "Hello"); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blit can have text spanning a mask", GOTO(0,0), SETPEN(), PRINT("He"), GOTO(0,3), SETPEN(), PRINT("lo"), NULL); } // Blitting merges line segments { tickit_renderbuffer_reset(window); tickit_renderbuffer_hline_at(window, 1, 0, 20, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(screen, 0, 2, 5, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blit merges line segments", GOTO(0,5), SETPEN(), PRINT("╷"), GOTO(1,0), SETPEN(), PRINT("╶────┼──────────────"), GOTO(2,5), SETPEN(), PRINT("╵"), NULL); } // Blitting obeys translation { tickit_renderbuffer_reset(window); tickit_renderbuffer_translate(window, 3, 3); tickit_renderbuffer_translate(screen, 2, 4); tickit_renderbuffer_text_at(window, 0, 1, "Hello"); tickit_renderbuffer_char_at(window, 2, 4, 'B'); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blit obeys translation", GOTO(5,8), SETPEN(), PRINT("Hello"), GOTO(7,11), SETPEN(), PRINT("B"), NULL); } // Blitting obeys clipping { tickit_renderbuffer_reset(window); TickitRect clip = { .top=2, .left=2, .lines=6, .cols=16 }; tickit_renderbuffer_clip(screen, &clip); tickit_renderbuffer_text_at(window, 1, 0, "Hello"); tickit_renderbuffer_text_at(window, 2, 0, "World"); tickit_renderbuffer_char_at(window, 2, 19, 'C'); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer blit obeys clipping", GOTO(2,2), SETPEN(), PRINT("rld"), NULL); } // Blitting overrides destination's pen { tickit_renderbuffer_reset(window); TickitPen *screen_pen = tickit_pen_new_attrs( TICKIT_PEN_FG, 4, 0); tickit_renderbuffer_setpen(screen, screen_pen); tickit_pen_unref(screen_pen); TickitPen *window_pen = tickit_pen_new_attrs( TICKIT_PEN_FG, 5, 0); tickit_renderbuffer_setpen(window, window_pen); tickit_pen_unref(window_pen); TickitPen *bg_pen = tickit_pen_new_attrs( TICKIT_PEN_BG, 6, 0); tickit_renderbuffer_text_at(window, 0, 0, "Hello"); { tickit_renderbuffer_savepen(window); tickit_renderbuffer_setpen(window, bg_pen); tickit_renderbuffer_char_at(window, 1, 1, 'A'); tickit_renderbuffer_restore(window); } tickit_renderbuffer_setpen(window, NULL); { tickit_renderbuffer_savepen(window); tickit_renderbuffer_setpen(window, bg_pen); tickit_renderbuffer_text_at(window, 2, 2, "World"); tickit_renderbuffer_restore(window); } tickit_renderbuffer_text_at(window, 3, 3, "Again"); tickit_renderbuffer_text_at(screen, 4, 4, "Preserved Pen"); tickit_renderbuffer_blit(screen, window); tickit_renderbuffer_flush_to_term(screen, tt); is_termlog("RenderBuffer basic blitting", GOTO(0,0), SETPEN(.fg=5), PRINT("Hello"), GOTO(1,1), SETPEN(.fg=5,.bg=6), PRINT("A"), GOTO(2,2), SETPEN(.fg=4,.bg=6), PRINT("World"), GOTO(3,3), SETPEN(.fg=4), PRINT("Again"), GOTO(4,4), SETPEN(.fg=4), PRINT("Preserved Pen"), NULL); tickit_pen_unref(bg_pen); } tickit_renderbuffer_unref(window); tickit_renderbuffer_unref(screen); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/16term-read.c
#ifdef __GLIBC__ # define _XOPEN_SOURCE 500 // usleep #endif #include "tickit.h" #include "taplib.h" #include <string.h> #include <unistd.h> TickitKeyEventType keytype; char keystr[16]; int on_key(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { TickitKeyEventInfo *info = _info; keytype = info->type; strncpy(keystr, info->str, sizeof(keystr)-1); keystr[sizeof(keystr)-1] = 0; return 1; } int main(int argc, char *argv[]) { TickitTerm *tt; int fd[2]; /* We'll need a real filehandle we can write/read. * pipe() can make us one */ pipe(fd); tt = tickit_term_new_for_termtype("xterm"); tickit_term_set_input_fd(tt, fd[0]); is_int(tickit_term_get_input_fd(tt), fd[0], "tickit_term_get_input_fd"); tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, on_key, NULL); write(fd[1], "A", 1); tickit_term_input_readable(tt); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after write A"); is_str(keystr, "A", "keystr after write A"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after A"); keytype = -1; keystr[0] = 0; write(fd[1], "\e", 1); tickit_term_input_readable(tt); is_int(keytype, -1, "keytype not set after write Escape"); int msec = tickit_term_input_check_timeout_msec(tt); ok(msec > 0, "term has timeout after Escape"); /* Add an extra milisecond timing grace */ usleep((msec+1) * 1000); tickit_term_input_check_timeout_msec(tt); is_int(keytype, TICKIT_KEYEV_KEY, "keytype after write completed Escape"); is_str(keystr, "Escape", "keystr after write completed Escape"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after completed Escape"); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/31renderbuffer-line.c
<filename>t/31renderbuffer-line.c #include "tickit.h" #include "taplib.h" #include "taplib-mockterm.h" int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitRenderBuffer *rb; rb = tickit_renderbuffer_new(30, 30); // Simple lines, end caps { TickitPen *fg_pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 1, 0); tickit_renderbuffer_setpen(rb, fg_pen); tickit_renderbuffer_hline_at(rb, 10, 10, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 11, 10, 14, TICKIT_LINE_SINGLE, TICKIT_LINECAP_START); tickit_renderbuffer_hline_at(rb, 12, 10, 14, TICKIT_LINE_SINGLE, TICKIT_LINECAP_END); tickit_renderbuffer_hline_at(rb, 13, 10, 14, TICKIT_LINE_SINGLE, TICKIT_LINECAP_BOTH); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer renders hline_at to terminal", GOTO(10,10), SETPEN(.fg=1), PRINT("╶───╴"), GOTO(11,10), SETPEN(.fg=1), PRINT("────╴"), GOTO(12,10), SETPEN(.fg=1), PRINT("╶────"), GOTO(13,10), SETPEN(.fg=1), PRINT("─────"), NULL); tickit_renderbuffer_setpen(rb, fg_pen); tickit_renderbuffer_vline_at(rb, 10, 13, 10, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 10, 13, 11, TICKIT_LINE_SINGLE, TICKIT_LINECAP_START); tickit_renderbuffer_vline_at(rb, 10, 13, 12, TICKIT_LINE_SINGLE, TICKIT_LINECAP_END); tickit_renderbuffer_vline_at(rb, 10, 13, 13, TICKIT_LINE_SINGLE, TICKIT_LINECAP_BOTH); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer renders vline_at to terminal", GOTO(10,10), SETPEN(.fg=1), PRINT("╷│╷│"), GOTO(11,10), SETPEN(.fg=1), PRINT("││││"), GOTO(12,10), SETPEN(.fg=1), PRINT("││││"), GOTO(13,10), SETPEN(.fg=1), PRINT("╵╵││"), NULL); tickit_pen_unref(fg_pen); } // Line merging { tickit_renderbuffer_hline_at(rb, 10, 10, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 11, 10, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 12, 10, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 10, 12, 10, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 10, 12, 12, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_vline_at(rb, 10, 12, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer renders line merging", GOTO(10,10), SETPEN(), PRINT("┌─┬─┐"), GOTO(11,10), SETPEN(), PRINT("├─┼─┤"), GOTO(12,10), SETPEN(), PRINT("└─┴─┘"), NULL); } tickit_renderbuffer_unref(rb); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/mockterm.c
<reponame>kiwiroy/libtickit #include "taplib-mockterm.h" #include "taplib.h" #include "tickit-mockterm.h" #include <string.h> #define streq(a,b) (!strcmp(a,b)) static char *lognames[] = { [EXPECT_GOTO] = "goto", [EXPECT_PRINT] = "print", [EXPECT_ERASECH] = "erasech", [EXPECT_CLEAR] = "clear", [EXPECT_SCROLLRECT] = "scrollrect", [EXPECT_SETPEN] = "setpen", }; static TickitMockTerm *mt; TickitTerm *make_term(int lines, int cols) { if(!mt) mt = tickit_mockterm_new(lines, cols); return (TickitTerm *)mt; } void drain_termlog(void) { tickit_mockterm_clearlog(mt); } void is_termlog(char *name, ...) { va_list args; va_start(args, name); int loglen = tickit_mockterm_loglen(mt); int logi; for(logi = 0; logi < loglen; logi++) { struct TermLogExpectation *exp = va_arg(args, void *); if(!exp) break; TickitMockTermLogEntry *got = tickit_mockterm_peeklog(mt, logi); if((int)exp->type != (int)got->type) { fail(name); diag("Expected %s(), got %s()", lognames[exp->type], lognames[got->type]); goto failed; } switch(exp->type) { case EXPECT_GOTO: case EXPECT_ERASECH: if(exp->val[0] == got->val1 && exp->val[1] == got->val2) continue; fail(name); diag("Expected %s(%d,%d), got %s(%d,%d)", lognames[exp->type], exp->val[0], exp->val[1], lognames[got->type], got->val1, got->val2); goto failed; case EXPECT_PRINT: if(streq(exp->str, got->str)) continue; fail(name); diag("Expected print(\"%s\"), got print(\"%s\")", exp->str, got->str); goto failed; case EXPECT_CLEAR: continue; case EXPECT_SCROLLRECT: if(exp->val[0] == got->rect.top && exp->val[1] == got->rect.left && exp->val[2] == got->rect.lines && exp->val[3] == got->rect.cols && exp->val[4] == got->val1 && exp->val[5] == got->val2) continue; fail(name); diag("Expected scrollrect(%d,%d,%d,%d, %+d,%+d), got scrollrect(%d,%d,%d,%d, %+d,%+d)", exp->val[0], exp->val[1], exp->val[2], exp->val[3], exp->val[4], exp->val[5], got->rect.top, got->rect.left, got->rect.lines, got->rect.cols, got->val1, got->val2); goto failed; case EXPECT_SETPEN: { int gotval; int expval; // Colours are tricky; -1 is the unspecified default if((expval = exp->fg == 0 ? -1 : exp->fg == EXPECT_ZERO ? 0 : exp->fg) != (gotval = tickit_pen_get_colour_attr(got->pen, TICKIT_PEN_FG))) { fail(name); diag("Expected setpen(fg=%d,...), got setpen(fg=%d,...)", expval, gotval); goto failed; } if((expval = exp->bg == 0 ? -1 : exp->bg == EXPECT_ZERO ? 0 : exp->bg) != (gotval = tickit_pen_get_colour_attr(got->pen, TICKIT_PEN_BG))) { fail(name); diag("Expected setpen(bg=%d,...), got setpen(bg=%d,...)", expval, gotval); goto failed; } // TODO: add remaining attributes } break; } } if(logi < loglen) { TickitMockTermLogEntry *got = tickit_mockterm_peeklog(mt, logi); fail(name); diag("Expected no more termlog entries; got %s()", lognames[got->type]); goto failed; } struct TermLogExpectation *exp; if((exp = va_arg(args, void *))) { fail(name); diag("Expected a %s() termlog entry; got none", lognames[exp->type]); goto failed; } pass(name); failed: tickit_mockterm_clearlog(mt); } void press_key(int type, char *str, int mod) { TickitKeyEventInfo info = { .type = type, .mod = mod, .str = str, }; tickit_term_emit_key((TickitTerm *)mt, &info); } void press_mouse(int type, int button, int line, int col, int mod) { TickitMouseEventInfo info = { .type = type, .button = button, .line = line, .col = col, .mod = mod, }; tickit_term_emit_mouse((TickitTerm *)mt, &info); }
kiwiroy/libtickit
src/termdriver.h
<reponame>kiwiroy/libtickit<filename>src/termdriver.h #include "tickit.h" #include "tickit-termdrv.h" typedef struct { const char *termtype; const struct TickitTerminfoHook *ti_hook; } TickitTermProbeArgs; typedef struct { TickitTermDriver *(*new)(const TickitTermProbeArgs *args); } TickitTermDriverProbe; extern TickitTermDriverProbe tickit_termdrv_probe_xterm; extern TickitTermDriverProbe tickit_termdrv_probe_ti;
kiwiroy/libtickit
t/05string.c
#include "tickit.h" #include "taplib.h" int main(int argc, char *argv[]) { TickitString *s; s = tickit_string_new("Hello, world!", 13); ok(!!s, "tickit_string_new"); is_str(tickit_string_get(s), "Hello, world!", "tickit_string_get"); is_int(tickit_string_len(s), 13, "tickit_string_len"); { is_ptr(tickit_string_ref(s), s, "tickit_string_ref"); tickit_string_unref(s); is_str(tickit_string_get(s), "Hello, world!", "tickit_string_get after tickit_string_unref"); } tickit_string_unref(s); return exit_status(); }
kiwiroy/libtickit
src/rect.c
<reponame>kiwiroy/libtickit #include "tickit.h" static inline int minint(int a, int b) { return a < b ? a : b; } static inline int maxint(int a, int b) { return a > b ? a : b; } void tickit_rect_init_sized(TickitRect *rect, int top, int left, int lines, int cols) { rect->top = top; rect->left = left; rect->lines = lines; rect->cols = cols; } void tickit_rect_init_bounded(TickitRect *rect, int top, int left, int bottom, int right) { rect->top = top; rect->left = left; rect->lines = bottom - top; rect->cols = right - left; } void tickit_rect_translate(TickitRect *rect, int downward, int rightward) { rect->top += downward; rect->left += rightward; } bool tickit_rect_intersect(TickitRect *dst, const TickitRect *a, const TickitRect *b) { int top = maxint(a->top, b->top); int bottom = minint(tickit_rect_bottom(a), tickit_rect_bottom(b)); if(top >= bottom) return false; int left = maxint(a->left, b->left); int right = minint(tickit_rect_right(a), tickit_rect_right(b)); if(left >= right) return false; tickit_rect_init_bounded(dst, top, left, bottom, right); return true; } bool tickit_rect_intersects(const TickitRect *a, const TickitRect *b) { return a->top < tickit_rect_bottom(b) && b->top < tickit_rect_bottom(a) && a->left < tickit_rect_right(b) && b->left < tickit_rect_right(a); } bool tickit_rect_contains(const TickitRect *large, const TickitRect *small) { return (small->top >= large->top ) && (tickit_rect_bottom(small) <= tickit_rect_bottom(large)) && (small->left >= large->left ) && (tickit_rect_right(small) <= tickit_rect_right(large) ); } int tickit_rect_add(TickitRect ret[3], const TickitRect *a, const TickitRect *b) { int a_bottom = tickit_rect_bottom(a); int a_right = tickit_rect_right(a); int b_bottom = tickit_rect_bottom(b); int b_right = tickit_rect_right(b); if(a->left > b_right || b->left > a_right || a->top > b_bottom || b->top > a_bottom) { ret[0] = *a; ret[1] = *b; return 2; } int rows[4]; rows[0] = a->top; rows[1] = b->top; rows[2] = a_bottom; rows[3] = b_bottom; /* Since we know top < bottom for each rect individually we can do this * better than a plain sort */ if(rows[0] > rows[1]) { int tmp = rows[0]; rows[0] = rows[1]; rows[1] = tmp; } // tops now in order if(rows[2] > rows[3]) { int tmp = rows[2]; rows[2] = rows[3]; rows[3] = tmp; } // bottoms now in order if(rows[1] > rows[2]) { int tmp = rows[1]; rows[1] = rows[2]; rows[2] = tmp; } // all now in order int rects = 0; for(int i = 0; i < 3; i++ ) { int this_top = rows[i]; int this_bottom = rows[i+1]; // Skip non-unique if(this_top == this_bottom) continue; int has_a = this_top >= a->top && this_bottom <= a_bottom; int has_b = this_top >= b->top && this_bottom <= b_bottom; int this_left = (has_a && has_b) ? minint(a->left, b->left) : (has_a) ? a->left : b->left; int this_right = (has_a && has_b) ? maxint(a_right, b_right) : (has_a) ? a_right : b_right; if(rects && ret[rects-1].left == this_left && ret[rects-1].cols == this_right - this_left) { ret[rects-1].lines = this_bottom - ret[rects-1].top; } else { tickit_rect_init_bounded(ret + rects, this_top, this_left, this_bottom, this_right); rects++; } } return rects; } int tickit_rect_subtract(TickitRect ret[5], const TickitRect *orig, const TickitRect *hole) { if(tickit_rect_contains(hole, orig)) return 0; if(!tickit_rect_intersects(hole, orig)) { ret[0] = *orig; return 1; } int rects = 0; int orig_right = tickit_rect_right(orig); int hole_right = tickit_rect_right(hole); if(orig->top < hole->top) { tickit_rect_init_bounded(ret + rects, orig->top, orig->left, hole->top, orig_right); rects++; } int orig_bottom = tickit_rect_bottom(orig); int hole_bottom = tickit_rect_bottom(hole); int mid_top = maxint(orig->top, hole->top); int mid_bottom = minint(orig_bottom, hole_bottom); if(orig->left < hole->left) { tickit_rect_init_bounded(ret + rects, mid_top, orig->left, mid_bottom, hole->left); rects++; } if(orig_right > hole_right) { tickit_rect_init_bounded(ret + rects, mid_top, hole_right, mid_bottom, orig_right); rects++; } if(orig_bottom > hole_bottom) { tickit_rect_init_bounded(ret + rects, hole_bottom, orig->left, orig_bottom, orig_right); rects++; } return rects; }
kiwiroy/libtickit
t/09debug.c
<gh_stars>10-100 #ifdef __GLIBC__ # define _XOPEN_SOURCE 500 // strdup #endif #include "tickit.h" #include "taplib.h" #include <stdlib.h> #include <string.h> char *msg = NULL; void savemsg(const char *str, void *data) { if(msg) free(msg); msg = strdup(str); } int main(int argc, char *argv[]) { putenv("TICKIT_DEBUG_FLAGS=T,X,Ca"); tickit_debug_set_func(savemsg, NULL); tickit_debug_init(); tickit_debug_logf("T", "Test message %s", "here"); ok(!!msg, "tickit_debug_logf saves a message"); // First 12 characters are timestamp is_str(msg+12, " [T ]: Test message here\n", "message string"); if(msg) { free(msg); msg = NULL; } tickit_debug_logf("A", "Another message"); ok(!msg, "tickit_debug_logf does not save a message with nonmatching flag"); if(msg) { free(msg); msg = NULL; } tickit_debug_logf("Ca", "Submatch pass"); ok(!!msg, "tickit_debug_logf logs on submatch"); if(msg) { free(msg); msg = NULL; } tickit_debug_logf("Cb", "Submatch fail"); ok(!msg, "tickit_debug_logf does not log failing submatch"); return exit_status(); }
kiwiroy/libtickit
t/taplib-tickit.h
#ifndef __TAPLIB_TICKIT_H__ #define __TAPLIB_TICKIT_H__ #include "tickit.h" TickitRect *rect_init_strp(TickitRect *rect, const char *str); void is_rect(TickitRect *got, const char *expect, char *name); #endif
kiwiroy/libtickit
t/taplib.h
<gh_stars>0 void plan_tests(int n); void skip_all(char *reason); void ok(int cmp, char *name); void pass(char *name); void fail(char *name); void diag(char *fmt, ...); void is_int(int got, int expect, char *name); void is_ptr(void *got, void *expect, char *name); void is_str(const char *got, const char *expect, char *name); void is_str_escape(const char *got, const char *expect, char *name); int exit_status(void);
kiwiroy/libtickit
t/50tickit.c
#include "tickit.h" #include "tickit-mockterm.h" #include "taplib.h" int main(int argc, char *argv[]) { Tickit *t = tickit_new_for_term(tickit_mockterm_new(25, 80)); ok(!!t, "tickit_new_stdio()"); /* TODO: add some real tests * There isn't a lot that can be checked in a unit-test script yet, until * more accessors, mutators, and maybe some construction options or a * builder happens */ tickit_unref(t); return exit_status(); }
kiwiroy/libtickit
t/taplib-mockterm.h
#include <tickit-mockterm.h> struct TermLogExpectation { enum { EXPECT_GOTO = LOG_GOTO, EXPECT_PRINT = LOG_PRINT, EXPECT_ERASECH = LOG_ERASECH, EXPECT_CLEAR = LOG_CLEAR, EXPECT_SCROLLRECT = LOG_SCROLLRECT, EXPECT_SETPEN = LOG_SETPEN, } type; int val[6]; char *str; // These must match pen attr names int fg, bg, b, u, i, rv, strike, af; }; #define GOTO(line,col) \ &(struct TermLogExpectation){EXPECT_GOTO, .val = {line, col}} #define PRINT(s) \ &(struct TermLogExpectation){EXPECT_PRINT, .str = s} #define ERASECH(count,moveend) \ &(struct TermLogExpectation){EXPECT_ERASECH, .val = {count, moveend}} #define CLEAR() \ &(struct TermLogExpectation){EXPECT_CLEAR} #define SCROLLRECT(top,left,lines,cols,downward,rightward) \ &(struct TermLogExpectation){EXPECT_SCROLLRECT, .val = {top, left, lines, cols, downward, rightward}} // IMPORTANT: set an expectation of this to expect the value 0 explicitly; // 0 will be treated as unspecified #define EXPECT_ZERO 0x100000 #define SETPEN(...) \ &(struct TermLogExpectation){EXPECT_SETPEN, __VA_ARGS__} TickitTerm *make_term(int lines, int cols); void drain_termlog(void); void is_termlog(char *name, ...); void press_key(int type, char *str, int mod); void press_mouse(int type, int button, int line, int col, int mod);
kiwiroy/libtickit
t/10term-write.c
<gh_stars>0 #include "tickit.h" #include "taplib.h" #include <string.h> #include <unistd.h> bool output_eof = false; void output(TickitTerm *tt, const char *bytes, size_t len, void *user) { char *buffer = user; if(bytes) strncat(buffer, bytes, len); else output_eof = true; } int main(int argc, char *argv[]) { TickitTerm *tt; int fd[2]; char buffer[1024] = { 0 }; size_t len; /* We'll need a real filehandle we can write/read. * pipe() can make us one */ pipe(fd); tt = tickit_term_new_for_termtype("xterm"); ok(!!tt, "tickit_term_new_for_termtype"); tickit_term_set_output_fd(tt, fd[1]); is_int(tickit_term_get_output_fd(tt), fd[1], "tickit_term_get_output_fd"); /* Already it should have written its DECSLRM probe string */ len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_str_escape(buffer, "\e[?69h\e[?69$p\e[?25$p\e[?12$p\eP$q q\e\\" "\e[38;5;255m\e[38:2:0:1:2m\eP$qm\e\\\e[m" "\e[G\e[K", "buffer after initialisation contains DECSLRM and cursor status probes"); tickit_term_print(tt, "Hello world!"); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_int(len, 12, "read() length after tickit_term_print"); is_str_escape(buffer, "Hello world!", "buffer after tickit_term_print"); tickit_term_printn(tt, "another string here", 7); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_int(len, 7, "read() length after tickit_term_printn"); is_str_escape(buffer, "another", "buffer after tickit_term_printn"); tickit_term_printf(tt, "%s %s!", "More", "messages"); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_int(len, 14, "read() length after tickit_term_printf"); is_str_escape(buffer, "More messages!", "buffer after tickit_term_printf"); tickit_term_goto(tt, 2, 5); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_str_escape(buffer, "\e[3;6H", "buffer after tickit_term_goto line+col"); tickit_term_goto(tt, 4, -1); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_str_escape(buffer, "\e[5d", "buffer after tickit_term_goto line"); tickit_term_goto(tt, -1, 10); len = read(fd[0], buffer, sizeof buffer); buffer[len] = 0; is_str_escape(buffer, "\e[11G", "buffer after tickit_term_goto col"); buffer[0] = 0; tickit_term_set_output_func(tt, output, buffer); tickit_term_print(tt, "Hello, world"); is_str(buffer, "Hello, world", "buffer after print using output func"); tickit_term_unref(tt); ok(1, "tickit_term_unref"); ok(output_eof, "output func receives EOF indication after tickit_term_unref"); return exit_status(); }
kiwiroy/libtickit
t/45window-input.c
<reponame>kiwiroy/libtickit #include "tickit.h" #include "taplib.h" #include "taplib-mockterm.h" #include <string.h> struct LastEvent { int type; int mod; int line, col, button; char str[16]; int ret; }; int on_key_event_capture(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { struct LastEvent *last_event = data; TickitKeyEventInfo *info = _info; last_event->type = info->type; last_event->mod = info->mod; strcpy(last_event->str, info->str); return last_event->ret; } int on_mouse_event_capture(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { struct LastEvent *last_event = data; TickitMouseEventInfo *info = _info; last_event->type = info->type; last_event->mod = info->mod; last_event->line = info->line; last_event->col = info->col; last_event->button = info->button; return last_event->ret; } int next_idx = 0; char *ids[3]; int on_event_push(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { ids[next_idx++] = data; return 0; } int on_event_incr_int(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { ((int *)data)[0]++; return 0; } int on_termevent_incr_int(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { ((int *)data)[0]++; return 0; } TickitWindow *childwin = NULL; int childmouse = 0; int win_on_mouse_child(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { if(childwin) return 0; childwin = tickit_window_new(win, (TickitRect){0, 0, 2, 2}, 0); tickit_window_bind_event(childwin, TICKIT_WINDOW_ON_MOUSE, 0, &on_event_incr_int, &childmouse); return 0; } TickitWindow *siblingwin = NULL; int siblingmouse = 0; int win_on_mouse_sibling(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { if(siblingwin) return 0; siblingwin = tickit_window_new(win, (TickitRect){0, 0, 2, 2}, 0); tickit_window_bind_event(siblingwin, TICKIT_WINDOW_ON_MOUSE, 0, &on_event_incr_int, &siblingmouse); return 0; } int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitWindow *root = tickit_window_new_root(tt); TickitWindow *win = tickit_window_new(root, (TickitRect){3, 10, 4, 20}, 0); tickit_window_take_focus(win); tickit_window_flush(root); struct LastEvent win_last = { .ret = 1 }; int key_bind_id = tickit_window_bind_event(win, TICKIT_WINDOW_ON_KEY, 0, &on_key_event_capture, &win_last); int mouse_bind_id = tickit_window_bind_event(win, TICKIT_WINDOW_ON_MOUSE, 0, &on_mouse_event_capture, &win_last); // Key events { press_key(TICKIT_KEYEV_TEXT, "A", 0); is_int(win_last.type, TICKIT_KEYEV_TEXT, "win_last.type for A"); is_str(win_last.str, "A", "win_last.str for A"); press_key(TICKIT_KEYEV_KEY, "C-a", TICKIT_MOD_CTRL); is_int(win_last.type, TICKIT_KEYEV_KEY, "win_last.type for C-a"); is_str(win_last.str, "C-a", "win_last.str for C-a"); is_int(win_last.mod, TICKIT_MOD_CTRL, "win_last.mod for C-a"); } // Mouse events { win_last.type = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 5, 15, 0); is_int(win_last.type, TICKIT_MOUSEEV_PRESS, "win_last.type for press 1@15,5"); is_int(win_last.line, 2, "win_last.line for press 1@15,5"); is_int(win_last.col, 5, "win_last.col for press 1@15,5"); win_last.type = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 1, 2, 0); is_int(win_last.type, 0, "win_last.type still 0 after press @1,2"); } // Unhandled events are not consumed { int term_invoked = 0; int bind_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, &on_termevent_incr_int, &term_invoked); win_last.ret = 0; press_key(TICKIT_KEYEV_KEY, "A", 0); ok(term_invoked, "term event handler invoked after unhandled window event"); tickit_term_unbind_event_id(tt, bind_id); } TickitWindow *subwin = tickit_window_new(win, (TickitRect){2, 2, 1, 10}, 0); // Subwindow { tickit_window_take_focus(subwin); tickit_window_flush(root); struct LastEvent subwin_last = { .ret = 1 }; int sub_key_bind_id = tickit_window_bind_event(subwin, TICKIT_WINDOW_ON_KEY, 0, &on_key_event_capture, &subwin_last); int sub_mouse_bind_id = tickit_window_bind_event(subwin, TICKIT_WINDOW_ON_MOUSE, 0, &on_mouse_event_capture, &subwin_last); win_last.type = 0; press_key(TICKIT_KEYEV_TEXT, "B", 0); is_int(subwin_last.type, TICKIT_KEYEV_TEXT, "subwin_last.type for B"); is_str(subwin_last.str, "B", "subwin_last.str for B"); is_int(win_last.type, 0, "win_last.type for B"); subwin_last.type = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 5, 15, 0); is_int(subwin_last.type, TICKIT_MOUSEEV_PRESS, "subwin_last.type for press 1@15,5"); is_int(subwin_last.line, 0, "subwin_last.line for press 1@15,5"); is_int(subwin_last.col, 3, "subwin_last.col for press 1@15,5"); subwin_last.ret = 0; subwin_last.type = 0; win_last.type = 0; press_key(TICKIT_KEYEV_TEXT, "C", 0); is_int(subwin_last.type, TICKIT_KEYEV_TEXT, "subwin_last.type for C"); is_str(subwin_last.str, "C", "subwin_last.str for C"); is_int(win_last.type, TICKIT_KEYEV_TEXT, "win_last.type for C"); is_str(win_last.str, "C", "win_last.str for C"); tickit_window_unbind_event_id(subwin, sub_key_bind_id); tickit_window_unbind_event_id(subwin, sub_mouse_bind_id); } tickit_window_unbind_event_id(win, key_bind_id); tickit_window_unbind_event_id(win, mouse_bind_id); // Event ordering { TickitWindow *otherwin = tickit_window_new(root, (TickitRect){10, 10, 4, 20}, 0); tickit_window_flush(root); int bind_ids[] = { tickit_window_bind_event(win, TICKIT_WINDOW_ON_KEY, 0, &on_event_push, "win"), tickit_window_bind_event(subwin, TICKIT_WINDOW_ON_KEY, 0, &on_event_push, "subwin"), tickit_window_bind_event(otherwin, TICKIT_WINDOW_ON_KEY, 0, &on_event_push, "otherwin"), }; press_key(TICKIT_KEYEV_TEXT, "D", 0); is_int(next_idx, 3, "press_key pushes 3 strings for D"); is_str(ids[0], "subwin", "ids[0] for D"); is_str(ids[1], "win", "ids[1] for D"); is_str(ids[2], "otherwin", "ids[2] for D"); tickit_window_hide(subwin); next_idx = 0; press_key(TICKIT_KEYEV_TEXT, "E", 0); is_int(next_idx, 2, "press_key pushes 2 strings for E"); is_str(ids[0], "win", "ids[0] for E"); is_str(ids[1], "otherwin", "ids[1] for E"); tickit_window_unref(otherwin); tickit_window_flush(root); tickit_window_unbind_event_id(win, bind_ids[0]); tickit_window_unbind_event_id(subwin, bind_ids[1]); } tickit_window_unref(subwin); // Windows created in input events handlers don't receive events // child windows { int id = tickit_window_bind_event(win, TICKIT_WINDOW_ON_MOUSE, 0, &win_on_mouse_child, NULL); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 3, 10, 0); ok(!!childwin, "child window created"); is_int(childmouse, 0, "child window has not yet received a mouse event"); tickit_window_flush(root); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 3, 10, 0); is_int(childmouse, 1, "child window has now received an event after flush"); tickit_window_unbind_event_id(win, id); tickit_window_unref(childwin); tickit_window_flush(root); } // sibling windows { int id = tickit_window_bind_event(win, TICKIT_WINDOW_ON_MOUSE, 0, &win_on_mouse_sibling, NULL); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 3, 10, 0); ok(!!siblingwin, "sibling window created"); is_int(siblingmouse, 0, "sibling window has not yet received a mouse event"); tickit_window_flush(root); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 3, 10, 0); is_int(siblingmouse, 1, "sibling window has now received an event after flush"); tickit_window_unbind_event_id(win, id); tickit_window_unref(siblingwin); tickit_window_flush(root); } // STEAL_INPUT { TickitWindow *thief = tickit_window_new(root, (TickitRect){2, 5, 3, 3}, TICKIT_WINDOW_STEAL_INPUT); struct LastEvent thief_last = { .ret = 1 }; tickit_window_bind_event(thief, TICKIT_WINDOW_ON_KEY, 0, &on_key_event_capture, &thief_last); tickit_window_bind_event(thief, TICKIT_WINDOW_ON_MOUSE, 0, &on_mouse_event_capture, &thief_last); ok(tickit_window_is_steal_input(thief), "tickit_window_is_steal_input() returns true"); press_key(TICKIT_KEYEV_TEXT, "D", 0); is_int(thief_last.type, TICKIT_KEYEV_TEXT, "thief_last.type for D"); is_str(thief_last.str, "D", "thief_last.str for D"); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 1, 1, 0); is_int(thief_last.type, TICKIT_MOUSEEV_PRESS, "thief_last.type for press 1@1,1"); is_int(thief_last.line, -1, "thief_last.line for press 1@1,1"); is_int(thief_last.col, -4, "thief_last.col for press 1@1,1"); thief_last.type = 0; win_last.type = 0; tickit_window_setctl_int(thief, TICKIT_WINCTL_STEAL_INPUT, false); ok(!tickit_window_is_steal_input(thief), "tickit_window_is_steal_input() returns false"); press_mouse(TICKIT_MOUSEEV_PRESS, 1, 1, 1, 0); is_int(thief_last.type, 0, "thief does not see event after disabling STEAL_INPUT"); tickit_window_unref(thief); } tickit_window_unref(win); tickit_window_unref(root); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/03rect.c
#include "tickit.h" #include "taplib.h" #include "taplib-tickit.h" #include <stdio.h> int main(int argc, char *argv[]) { TickitRect rect1, rect2, rectOut; tickit_rect_init_sized(&rect1, 5, 10, 7, 20); is_int(rect1.top, 5, "rect1.top"); is_int(rect1.left, 10, "rect1.left"); is_int(rect1.lines, 7, "rect1.lines"); is_int(rect1.cols, 20, "rect1.cols"); is_int(tickit_rect_bottom(&rect1), 12, "tickit_rect_bottom(rect1)"); is_int(tickit_rect_right(&rect1), 30, "tickit_rect_right(rect1)"); tickit_rect_init_sized(&rect2, 0, 0, 25, 80); tickit_rect_intersect(&rectOut, &rect1, &rect2); is_int(rectOut.top, 5, "rectOut.top from intersect wholescreen"); is_int(rectOut.left, 10, "rectOut.left from intersect wholescreen"); is_int(rectOut.lines, 7, "rectOut.lines from intersect wholescreen"); is_int(rectOut.cols, 20, "rectOut.cols from intersect wholescreen"); is_int(tickit_rect_bottom(&rectOut), 12, "tickit_rect_bottom(rectOut) from intersect wholescreen"); is_int(tickit_rect_right(&rectOut), 30, "tickit_rect_right(rectOut) from intersect wholescreen"); tickit_rect_init_sized(&rect2, 10, 20, 15, 60); tickit_rect_intersect(&rectOut, &rect1, &rect2); is_int(rectOut.top, 10, "rectOut.top from intersect partial"); is_int(rectOut.left, 20, "rectOut.left from intersect partial"); is_int(rectOut.lines, 2, "rectOut.lines from intersect partial"); is_int(rectOut.cols, 10, "rectOut.cols from intersect partial"); is_int(tickit_rect_bottom(&rectOut), 12, "tickit_rect_bottom(rectOut) from intersect partial"); is_int(tickit_rect_right(&rectOut), 30, "tickit_rect_right(rectOut) from intersect partial"); tickit_rect_init_sized(&rect2, 20, 20, 5, 60); ok(!tickit_rect_intersect(&rectOut, &rect1, &rect2), "false from intersect outside"); tickit_rect_init_sized(&rect2, 7, 12, 3, 10); ok(tickit_rect_contains(&rect1, &rect2), "tickit_rect_contains() for smaller"); tickit_rect_init_sized(&rect2, 3, 10, 5, 12); ok(!tickit_rect_contains(&rect1, &rect2), "tickit_rect_contains() for overlap"); tickit_rect_init_sized(&rect2, 3, 10, 5, 12); ok(tickit_rect_intersects(&rect1, &rect2), "tickit_rect_intersects() with overlap"); tickit_rect_init_sized(&rect2, 14, 10, 3, 20); ok(!tickit_rect_intersects(&rect1, &rect2), "tickit_rect_intersects() with other"); tickit_rect_init_sized(&rect2, 12, 10, 3, 20); ok(!tickit_rect_intersects(&rect1, &rect2), "tickit_rect_intersects() with abutting"); tickit_rect_init_bounded(&rect1, 3, 8, 9, 22); is_int(rect1.top, 3, "rect1.top from init_bounded"); is_int(rect1.left, 8, "rect1.left from init_bounded"); is_int(rect1.lines, 6, "rect1.lines from init_bounded"); is_int(rect1.cols, 14, "rect1.cols from init_bounded"); is_int(tickit_rect_bottom(&rect1), 9, "tickit_rect_bottom(rect1) from init_bounded"); is_int(tickit_rect_right(&rect1), 22, "tickit_rect_right(rect1) from init_bounded"); tickit_rect_translate(&rect1, 2, 4); is_int(rect1.top, 5, "rect1.top after translate"); is_int(rect1.left, 12, "rect1.left after translate"); is_int(rect1.lines, 6, "rect1.lines after translate"); is_int(rect1.cols, 14, "rect1.cols after translate"); // Rectangle addition TickitRect rects[4]; int n_rects; rect_init_strp(&rect1, "10,10..20,20"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "10,10..20,20")); is_int(n_rects, 1, "rect_add same"); is_rect(rects + 0, "10,10..20,20", "rects[0] for rect_add same"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "5,10..10,20")); is_int(n_rects, 1, "rect_add left"); is_rect(rects + 0, "5,10..20,20", "rects[0] for rect_add left"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "20,10..25,20")); is_int(n_rects, 1, "rect_add right"); is_rect(rects + 0, "10,10..25,20", "rects[0] for rect_add right"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "10,5..20,10")); is_int(n_rects, 1, "rect_add top"); is_rect(rects + 0, "10,5..20,20", "rects[0] for rect_add top"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "10,20..20,25")); is_int(n_rects, 1, "rect_add bottom"); is_rect(rects + 0, "10,10..20,25", "rects[0] for rect_add bottom"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "12,5..18,10")); is_int(n_rects, 2, "rect_add T above"); is_rect(rects + 0, "12,5..18,10", "rects[0] for rect_add T above"); is_rect(rects + 1, "10,10..20,20", "rects[1] for rect_add T above"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "12,20..18,30")); is_int(n_rects, 2, "rect_add T below"); is_rect(rects + 0, "10,10..20,20", "rects[0] for rect_add T below"); is_rect(rects + 1, "12,20..18,30", "rects[1] for rect_add T below"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "5,12..10,18")); is_int(n_rects, 3, "rect_add T left"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_add T left"); is_rect(rects + 1, "5,12..20,18", "rects[1] for rect_add T left"); is_rect(rects + 2, "10,18..20,20", "rects[2] for rect_add T left"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "20,12..25,18")); is_int(n_rects, 3, "rect_add T right"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_add T right"); is_rect(rects + 1, "10,12..25,18", "rects[1] for rect_add T right"); is_rect(rects + 2, "10,18..20,20", "rects[2] for rect_add T right"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "15,15..25,25")); is_int(n_rects, 3, "rect_add diagonal"); is_rect(rects + 0, "10,10..20,15", "rects[0] for rect_add diagonal"); is_rect(rects + 1, "10,15..25,20", "rects[1] for rect_add diagonal"); is_rect(rects + 2, "15,20..25,25", "rects[2] for rect_add diagonal"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "12,8..18,22")); is_int(n_rects, 3, "rect_add cross"); is_rect(rects + 0, "12,8..18,10", "rects[0] for rect_add cross"); is_rect(rects + 1, "10,10..20,20", "rects[1] for rect_add cross"); is_rect(rects + 2, "12,20..18,22", "rects[2] for rect_add cross"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "10,30..20,40")); is_int(n_rects, 2, "rect_add non-overlap horizontal"); is_rect(rects + 0, "10,10..20,20", "rects[0] for rect_add non-overlap horizontal"); is_rect(rects + 1, "10,30..20,40", "rects[1] for rect_add non-overlap horizontal"); n_rects = tickit_rect_add(rects, &rect1, rect_init_strp(&rect2, "30,10..40,20")); is_int(n_rects, 2, "rect_add non-overlap vertical"); is_rect(rects + 0, "10,10..20,20", "rects[0] for rect_add non-overlap vertical"); is_rect(rects + 1, "30,10..40,20", "rects[1] for rect_add non-overlap vertical"); // Rectangle subtraction n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "10,10..20,20")); is_int(n_rects, 0, "rect_subtract self"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "5,10..15,20")); is_int(n_rects, 1, "rect_subtract truncate left"); is_rect(rects + 0, "15,10..20,20", "rects[0] for rect_subtract truncate left"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "15,10..25,20")); is_int(n_rects, 1, "rect_subtract truncate right"); is_rect(rects + 0, "10,10..15,20", "rects[0] for rect_subtract truncate right"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "10,5..20,15")); is_int(n_rects, 1, "rect_subtract truncate top"); is_rect(rects + 0, "10,15..20,20", "rects[0] for rect_subtract truncate top"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "10,15..20,25")); is_int(n_rects, 1, "rect_subtract truncate bottom"); is_rect(rects + 0, "10,10..20,15", "rects[0] for rect_subtract truncate bottom"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "5,12..25,18")); is_int(n_rects, 2, "rect_subtract slice horizontal"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_subtract slice horizontal"); is_rect(rects + 1, "10,18..20,20", "rects[1] for rect_subtract slice horizontal"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "12,5..18,25")); is_int(n_rects, 2, "rect_subtract slice vertical"); is_rect(rects + 0, "10,10..12,20", "rects[0] for rect_subtract slice vertical"); is_rect(rects + 1, "18,10..20,20", "rects[1] for rect_subtract slice vertical"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "5,12..15,18")); is_int(n_rects, 3, "rect_subtract U left"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_subtract U left"); is_rect(rects + 1, "15,12..20,18", "rects[1] for rect_subtract U left"); is_rect(rects + 2, "10,18..20,20", "rects[2] for rect_subtract U left"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "15,12..25,18")); is_int(n_rects, 3, "rect_subtract U right"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_subtract U right"); is_rect(rects + 1, "10,12..15,18", "rects[1] for rect_subtract U right"); is_rect(rects + 2, "10,18..20,20", "rects[2] for rect_subtract U right"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "12,5..18,15")); is_int(n_rects, 3, "rect_subtract U top"); is_rect(rects + 0, "10,10..12,15", "rects[0] for rect_subtract U top"); is_rect(rects + 1, "18,10..20,15", "rects[1] for rect_subtract U top"); is_rect(rects + 2, "10,15..20,20", "rects[2] for rect_subtract U top"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "12,15..18,25")); is_int(n_rects, 3, "rect_subtract U bottom"); is_rect(rects + 0, "10,10..20,15", "rects[0] for rect_subtract U bottom"); is_rect(rects + 1, "10,15..12,20", "rects[1] for rect_subtract U bottom"); is_rect(rects + 2, "18,15..20,20", "rects[2] for rect_subtract U bottom"); n_rects = tickit_rect_subtract(rects, &rect1, rect_init_strp(&rect2, "12,12..18,18")); is_int(n_rects, 4, "rect_subtract hole"); is_rect(rects + 0, "10,10..20,12", "rects[0] for rect_subtract hole"); is_rect(rects + 1, "10,12..12,18", "rects[1] for rect_subtract hole"); is_rect(rects + 2, "18,12..20,18", "rects[2] for rect_subtract hole"); is_rect(rects + 3, "10,18..20,20", "rects[3] for rect_subtract hole"); return exit_status(); }
kiwiroy/libtickit
t/52tickit-timer.c
#include "tickit.h" #include "tickit-mockterm.h" #include "taplib.h" static int unbound_count; static int on_call_incr(Tickit *t, TickitEventFlags flags, void *info, void *user) { if(flags & TICKIT_EV_FIRE) { int *ip = user; (*ip)++; tickit_stop(t); } if(flags & TICKIT_EV_UNBIND) unbound_count++; return 1; } struct State { int *counterp; int capture; }; static int on_call_capture(Tickit *t, TickitEventFlags flags, void *info, void *user) { struct State *state = user; state->capture = *state->counterp; (*state->counterp)--; if(!(*state->counterp)) tickit_stop(t); return 1; } int main(int argc, char *argv[]) { Tickit *t = tickit_new_for_term(tickit_mockterm_new(25, 80)); /* tickit_watch_timer_after_msec */ { int called = 0; tickit_watch_timer_after_msec(t, 10, 0, &on_call_incr, &called); tickit_run(t); is_int(called, 1, "tickit_watch_timer_after_msec invokes callback"); } /* tickit_watch_timer_at_tv */ { struct timeval tv; gettimeofday(&tv, NULL); tv.tv_usec += 1000; if(tv.tv_usec >= 1000000) tv.tv_sec++, tv.tv_usec -= 1000000; int called = 0; tickit_watch_timer_at_tv(t, &tv, 0, &on_call_incr, &called); tickit_run(t); is_int(called, 1, "tickit_watch_timer_at_tv invokes callback"); } /* two timers with ordering */ { int counter = 2; struct State state_a = { .counterp = &counter }, state_b = { .counterp = &counter }; tickit_watch_timer_after_msec(t, 10, 0, &on_call_capture, &state_a); tickit_watch_timer_after_msec(t, 20, 0, &on_call_capture, &state_b); tickit_run(t); is_int(state_a.capture, 2, "tickit_watch_timer_after_msec first capture"); is_int(state_b.capture, 1, "tickit_watch_timer_after_msec second capture"); } /* timer cancellation */ { void *watch = tickit_watch_timer_after_msec(t, 5, TICKIT_BIND_UNBIND, &on_call_incr, NULL); tickit_watch_cancel(t, watch); pass("immediate tickit_watch_cancel does not segfault"); } { int called = 0; tickit_watch_timer_after_msec(t, 10, 0, &on_call_incr, &called); int not_called = 0; void *watch = tickit_watch_timer_after_msec(t, 5, TICKIT_BIND_UNBIND, &on_call_incr, &not_called); unbound_count = 0; tickit_watch_cancel(t, watch); is_int(unbound_count, 1, "unbound_count after tickit_watch_cancel"); tickit_run(t); ok(!not_called, "tickit_watch_cancel prevents invocation"); } /* object destruction */ { tickit_watch_timer_after_msec(t, 10, TICKIT_BIND_DESTROY, &on_call_incr, NULL); unbound_count = 0; tickit_unref(t); is_int(unbound_count, 1, "unbound_count after tickit_unref"); } return exit_status(); }
kiwiroy/libtickit
src/bindings.h
#include "tickit.h" struct TickitBinding; struct TickitBindings { struct TickitBinding *first; int is_iterating : 1; int needs_delete : 1; }; typedef int TickitEventFn(void *owner, TickitEventFlags flags, void *info, void *data); void tickit_bindings_run_event(struct TickitBindings *bindings, void *owner, int evindex, void *info); int tickit_bindings_run_event_whilefalse(struct TickitBindings *bindings, void *owner, int evindex, void *info); int tickit_bindings_bind_event(struct TickitBindings *bindings, void *owner, int evindex, TickitBindFlags flags, TickitEventFn *fn, void *data); void tickit_bindings_unbind_event_id(struct TickitBindings *bindings, void *owner, int id); void tickit_bindings_unbind_and_destroy(struct TickitBindings *bindings, void *owner); #define DEFINE_BINDINGS_FUNCS(NAME,OWNER,EVENTFN) \ int tickit_##NAME##_bind_event(OWNER *owner, OWNER##Event evindex, \ TickitBindFlags flags, EVENTFN *fn, void *data) \ { \ return tickit_bindings_bind_event(&owner->bindings, owner, \ evindex, flags, (TickitEventFn*)fn, data); \ } \ \ void tickit_##NAME##_unbind_event_id(OWNER *owner, int id) \ { \ tickit_bindings_unbind_event_id(&owner->bindings, owner, id); \ } \ \ static inline void run_events(OWNER *owner, int evindex, \ void *info) \ { \ tickit_bindings_run_event(&owner->bindings, owner, evindex, info); \ } \ \ static inline int run_events_whilefalse(OWNER *owner, int evindex, \ void *info) \ { \ return tickit_bindings_run_event_whilefalse(&owner->bindings, owner, evindex, \ info); \ }
kiwiroy/libtickit
t/18term-builder.c
#include "tickit.h" #include "taplib.h" #include <string.h> #define streq(a,b) (!strcmp(a,b)) static const char *ti_getstr(const char *name, const char *value, void *user) { if(streq(name, "cursor_address")) return "GOTO(%p1%d,%p2%d)"; return value; } static void output(TickitTerm *tt, const char *bytes, size_t len, void *user) { char *buffer = user; strncat(buffer, bytes, len); } int main(int argc, char *argv[]) { // termtype { struct TickitTermBuilder builder = { .termtype = "linux", }; TickitTerm *tt = tickit_term_build(&builder); is_str(tickit_term_get_termtype(tt), "linux", "termtype for built term"); tickit_term_unref(tt); } // getstr override { struct TickitTermBuilder builder = { .termtype = "linux", .ti_hook = &(const struct TickitTerminfoHook){ .getstr = ti_getstr }, }; TickitTerm *tt = tickit_term_build(&builder); char buffer[1024] = { 0 }; tickit_term_set_output_func(tt, output, buffer); tickit_term_set_output_buffer(tt, 4096); buffer[0] = 0; tickit_term_goto(tt, 4, 6); tickit_term_flush(tt); is_str_escape(buffer, "GOTO(4,6)", "buffer after goto for built term"); tickit_term_unref(tt); } return exit_status(); }
kiwiroy/libtickit
t/35renderbuffer-mask.c
#include "tickit.h" #include "taplib.h" #include "taplib-mockterm.h" int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitRenderBuffer *rb; rb = tickit_renderbuffer_new(10, 20); TickitRect mask = {.top = 3, .left = 5, .lines = 4, .cols = 6}; // Mask over text { tickit_renderbuffer_mask(rb, &mask); tickit_renderbuffer_text_at(rb, 3, 2, "ABCDEFG"); // before tickit_renderbuffer_text_at(rb, 4, 6, "HI"); // inside tickit_renderbuffer_text_at(rb, 5, 8, "JKLMN"); // after tickit_renderbuffer_text_at(rb, 6, 2, "OPQRSTUVWXYZ"); // spanning tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer masking around text", GOTO(3, 2), SETPEN(), PRINT("ABC"), GOTO(5,11), SETPEN(), PRINT("MN"), GOTO(6, 2), SETPEN(), PRINT("OPQ"), GOTO(6,11), SETPEN(), PRINT("XYZ"), NULL); } // Mask over erase { tickit_renderbuffer_mask(rb, &mask); tickit_renderbuffer_erase_at(rb, 3, 2, 6); // before tickit_renderbuffer_erase_at(rb, 4, 6, 2); // inside tickit_renderbuffer_erase_at(rb, 5, 8, 5); // after tickit_renderbuffer_erase_at(rb, 6, 2, 12); // spanning tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer masking around erasech", GOTO(3, 2), SETPEN(), ERASECH(3,-1), GOTO(5,11), SETPEN(), ERASECH(2,-1), GOTO(6, 2), SETPEN(), ERASECH(3,-1), GOTO(6,11), SETPEN(), ERASECH(3,-1), NULL); } // Mask over lines { tickit_renderbuffer_mask(rb, &mask); tickit_renderbuffer_hline_at(rb, 3, 2, 8, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 4, 6, 8, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 5, 8, 13, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_hline_at(rb, 6, 2, 14, TICKIT_LINE_SINGLE, 0); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer masking around lines", GOTO(3, 2), SETPEN(), PRINT("╶──"), GOTO(5,11), SETPEN(), PRINT("──╴"), GOTO(6, 2), SETPEN(), PRINT("╶──"), GOTO(6,11), SETPEN(), PRINT("───╴"), NULL); } // Restore removes masks { tickit_renderbuffer_save(rb); { tickit_renderbuffer_mask(rb, &mask); tickit_renderbuffer_text_at(rb, 3, 0, "AAAAAAAAAAAAAAAAAAAA"); } tickit_renderbuffer_restore(rb); tickit_renderbuffer_text_at(rb, 4, 0, "BBBBBBBBBBBBBBBBBBBB"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer save/restore removes mask", GOTO(3, 0), SETPEN(), PRINT("AAAAA"), GOTO(3,11), SETPEN(), PRINT("AAAAAAAAA"), GOTO(4, 0), SETPEN(), PRINT("BBBBBBBBBBBBBBBBBBBB"), NULL); } // translate over mask { tickit_renderbuffer_mask(rb, &(TickitRect){.top = 2, .left = 2, .lines = 1, .cols = 1}); { tickit_renderbuffer_save(rb); tickit_renderbuffer_translate(rb, 0, 0); tickit_renderbuffer_text_at(rb, 0, 0, "A"); tickit_renderbuffer_restore(rb); } { tickit_renderbuffer_save(rb); tickit_renderbuffer_translate(rb, 0, 2); tickit_renderbuffer_text_at(rb, 0, 0, "B"); tickit_renderbuffer_restore(rb); } { tickit_renderbuffer_save(rb); tickit_renderbuffer_translate(rb, 2, 0); tickit_renderbuffer_text_at(rb, 0, 0, "C"); tickit_renderbuffer_restore(rb); } { tickit_renderbuffer_save(rb); tickit_renderbuffer_translate(rb, 2, 2); tickit_renderbuffer_text_at(rb, 0, 0, "D"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("RenderBuffer translate over mask", GOTO(0,0), SETPEN(), PRINT("A"), GOTO(0,2), SETPEN(), PRINT("B"), GOTO(2,0), SETPEN(), PRINT("C"), // D was masked NULL); } // Mask out of limits doesn't SEGV { tickit_renderbuffer_save(rb); tickit_renderbuffer_mask(rb, &(TickitRect){.top = 0, .left = 0, .lines = 50, .cols = 200}); tickit_renderbuffer_mask(rb, &(TickitRect){.top = -10, .left = -20, .lines = 5, .cols = 20}); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_unref(rb); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
examples/demo-rgb8.c
<filename>examples/demo-rgb8.c #include "tickit.h" #include <errno.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define streq(a,b) (!strcmp(a,b)) #define COL_RED 1 #define COL_GREEN 2 #define COL_BLUE 4 static int on_geomchange(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { /* re-expose the entire window if it changes shape */ tickit_window_expose(win, NULL); return 1; } static int on_expose(TickitWindow *win, TickitEventFlags flags, void *_info, void *data) { TickitExposeEventInfo *info = _info; TickitRenderBuffer *rb = info->rb; int cols = tickit_window_cols(win); TickitPen *pen = tickit_pen_new(); tickit_renderbuffer_eraserect(rb, &info->rect); /* Red */ tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, COL_RED); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text_at(rb, 1, 0, "Red:"); tickit_renderbuffer_goto(rb, 2, 0); for(int x = 0; x < cols; x++) { tickit_pen_set_colour_attr(pen, TICKIT_PEN_BG, x > cols/2 ? COL_RED : 0); tickit_pen_set_colour_attr_rgb8(pen, TICKIT_PEN_BG, (TickitPenRGB8){ .r = 255 * x / (cols-1), .g = 0, .b = 0 }); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text(rb, " "); } tickit_pen_clear_attr(pen, TICKIT_PEN_BG); /* Green */ tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, COL_GREEN); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text_at(rb, 5, 0, "Green:"); tickit_renderbuffer_goto(rb, 6, 0); for(int x = 0; x < cols; x++) { tickit_pen_set_colour_attr(pen, TICKIT_PEN_BG, x > cols/2 ? COL_GREEN : 0); tickit_pen_set_colour_attr_rgb8(pen, TICKIT_PEN_BG, (TickitPenRGB8){ .r = 0, .g = 255 * x / (cols-1), .b = 0 }); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text(rb, " "); } tickit_pen_clear_attr(pen, TICKIT_PEN_BG); /* Blue */ tickit_pen_set_colour_attr(pen, TICKIT_PEN_FG, COL_BLUE); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text_at(rb, 9, 0, "Blue:"); tickit_renderbuffer_goto(rb, 10, 0); for(int x = 0; x < cols; x++) { tickit_pen_set_colour_attr(pen, TICKIT_PEN_BG, x > cols/2 ? COL_BLUE : 0); tickit_pen_set_colour_attr_rgb8(pen, TICKIT_PEN_BG, (TickitPenRGB8){ .r = 0, .g = 0, .b = 255 * x / (cols-1) }); tickit_renderbuffer_setpen(rb, pen); tickit_renderbuffer_text(rb, " "); } tickit_pen_clear_attr(pen, TICKIT_PEN_BG); return 1; } int main(int argc, char *argv[]) { Tickit *t = tickit_new_stdio(); TickitWindow *root = tickit_get_rootwin(t); if(!root) { fprintf(stderr, "Cannot create TickitTerm - %s\n", strerror(errno)); return 1; } tickit_window_bind_event(root, TICKIT_WINDOW_ON_GEOMCHANGE, 0, &on_geomchange, NULL); tickit_window_bind_event(root, TICKIT_WINDOW_ON_EXPOSE, 0, &on_expose, NULL); tickit_run(t); tickit_window_close(root); tickit_unref(t); return 0; }
kiwiroy/libtickit
t/15term-input.c
<reponame>kiwiroy/libtickit<filename>t/15term-input.c<gh_stars>0 #ifdef __GLIBC__ # define _XOPEN_SOURCE 500 // usleep #endif #include "tickit.h" #include "taplib.h" #include <string.h> #include <unistd.h> TickitKeyEventType keytype; char keystr[16]; int keymod; int on_key_return = 1; int on_key(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { TickitKeyEventInfo *info = _info; keytype = info->type; strncpy(keystr, info->str, sizeof(keystr)-1); keystr[sizeof(keystr)-1] = 0; keymod = info->mod; return on_key_return; } int on_key_incr(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { (*(int *)data)++; return 1; } TickitMouseEventType mousetype; int mousebutton, mouseline, mousecol; int mousemod; int on_mouse(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { TickitMouseEventInfo *info = _info; mousetype = info->type; mousebutton = info->button; mouseline = info->line; mousecol = info->col; mousemod = info->mod; return 1; } char events[2]; uint8_t i = 0; int on_key_push(TickitTerm *tt, TickitEventFlags flags, void *info, void *user) { events[i++] = *(char*)user; return 0; } int main(int argc, char *argv[]) { TickitTerm *tt; tt = tickit_term_new_for_termtype("xterm"); tickit_term_set_utf8(tt, 1); ok(tickit_term_get_utf8(tt), "get_utf8 true"); tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, on_key, NULL); tickit_term_bind_event(tt, TICKIT_TERM_ON_MOUSE, 0, on_mouse, NULL); { TickitKeyEventInfo info = { .type = TICKIT_KEYEV_TEXT, .mod = 0, .str = " ", }; tickit_term_emit_key(tt, &info); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after emit_key"); is_str(keystr, " ", "keystr after emit_key"); is_int(keymod, 0, "keymod after emit_key"); } tickit_term_input_push_bytes(tt, "A", 1); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after push_bytes A"); is_str(keystr, "A", "keystr after push_bytes A"); is_int(keymod, 0, "keymod after push_bytes A"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after A"); /* U+0109 - LATIN SMALL LETTER C WITH CIRCUMFLEX * UTF-8: 0xc4 0x89 */ tickit_term_input_push_bytes(tt, "\xc4\x89", 2); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after push_bytes U+0109"); is_str(keystr, "\xc4\x89", "keystr after push_bytes U+0109"); is_int(keymod, 0, "keymod after push_bytes U+0109"); tickit_term_input_push_bytes(tt, "\e[A", 3); is_int(keytype, TICKIT_KEYEV_KEY, "keytype after push_bytes Up"); is_str(keystr, "Up", "keystr after push_bytes Up"); is_int(keymod, 0, "keymod after push_bytes Up"); tickit_term_input_push_bytes(tt, "\x01", 1); is_int(keytype, TICKIT_KEYEV_KEY, "keytype after push_bytes C-a"); is_str(keystr, "C-a", "keystr after push_bytes C-a"); is_int(keymod, TICKIT_MOD_CTRL, "keymod after push_bytes C-a"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after Up"); { TickitMouseEventInfo info = { .type = TICKIT_MOUSEEV_PRESS, .button = 1, .line = 2, .col = 3, .mod = 0, }; tickit_term_emit_mouse(tt, &info); is_int(mousetype, TICKIT_MOUSEEV_PRESS, "mousetype after emit_mouse"); is_int(mousebutton, 1, "mousebutton after emit_mouse"); is_int(mouseline, 2, "mouseline after emit_mouse"); is_int(mousecol, 3, "mousecol after emit_mouse"); } tickit_term_input_push_bytes(tt, "\e[M !!", 6); is_int(mousetype, TICKIT_MOUSEEV_PRESS, "mousetype after mouse button press"); is_int(mousebutton, 1, "mousebutton after mouse button press"); is_int(mouseline, 0, "mouseline after mouse button press"); is_int(mousecol, 0, "mousecol after mouse button press"); is_int(mousemod, 0, "mousemod after mouse button press"); tickit_term_input_push_bytes(tt, "\e[M#!!", 6); is_int(mousetype, TICKIT_MOUSEEV_RELEASE, "mousetype after mouse button release"); is_int(mousebutton, 1, "mousebutton after mouse button release"); is_int(mouseline, 0, "mouseline after mouse button release"); is_int(mousecol, 0, "mousecol after mouse button release"); is_int(mousemod, 0, "mousemod after mouse button release"); tickit_term_input_push_bytes(tt, "\e[M`!!", 6); is_int(mousetype, TICKIT_MOUSEEV_WHEEL, "mousetype after mouse wheel up"); is_int(mousebutton, TICKIT_MOUSEWHEEL_UP, "mousebutton after mouse wheel up"); is_int(mouseline, 0, "mouseline after mouse wheel up"); is_int(mousecol, 0, "mousecol after mouse wheel up"); is_int(mousemod, 0, "mousemod after mouse wheel up"); keytype = -1; keystr[0] = 0; tickit_term_input_push_bytes(tt, "\e[", 2); is_int(keytype, -1, "keytype not set after push_bytes partial Down"); ok(tickit_term_input_check_timeout_msec(tt) > 0, "term has timeout after partial Down"); tickit_term_input_push_bytes(tt, "B", 1); is_int(keytype, TICKIT_KEYEV_KEY, "keytype after push_bytes completed Down"); is_str(keystr, "Down", "keystr after push_bytes completed Down"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after completed Down"); keytype = -1; keystr[0] = 0; tickit_term_input_push_bytes(tt, "\e", 1); is_int(keytype, -1, "keytype not set after push_bytes Escape"); int msec = tickit_term_input_check_timeout_msec(tt); ok(msec > 0, "term has timeout after Escape"); /* Add an extra milisecond timing grace */ usleep((msec+1) * 1000); tickit_term_input_check_timeout_msec(tt); is_int(keytype, TICKIT_KEYEV_KEY, "keytype after push_bytes completed Escape"); is_str(keystr, "Escape", "keystr after push_bytes completed Escape"); is_int(tickit_term_input_check_timeout_msec(tt), -1, "term has no timeout after completed Escape"); { int count = 0; int bind_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, &on_key_incr, &count); keytype = -1; on_key_return = 1; tickit_term_input_push_bytes(tt, "A", 1); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after push bytes with two events bound"); is_int(count, 0, "count of second event binding after first event with return 1"); keytype = -1; on_key_return = 0; tickit_term_input_push_bytes(tt, "A", 1); is_int(keytype, TICKIT_KEYEV_TEXT, "keytype after push bytes with two events bound the second time"); is_int(count, 1, "count of second event binding after first event with return 0"); tickit_term_unbind_event_id(tt, bind_id); } { int bindA_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, &on_key_push, "A"); int bindB_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, TICKIT_BIND_FIRST, &on_key_push, "B"); tickit_term_input_push_bytes(tt, "X", 1); is_int(i, 2, "two events fired"); is_int(events[0], 'B', "TICKIT_BIND_FIRST event fired first"); tickit_term_unbind_event_id(tt, bindA_id); tickit_term_unbind_event_id(tt, bindB_id); } tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/60tickit-setup.c
#include "tickit.h" #include "taplib.h" #include <string.h> void output(TickitTerm *tt, const char *bytes, size_t len, void *user) { char *buffer = user; strncat(buffer, bytes, len); } int main(int argc, char *argv[]) { char buffer[1024] = { 0 }; /* Regular setup */ { TickitTerm *tt = tickit_term_new_for_termtype("xterm"); Tickit *t = tickit_new_for_term(tt); tickit_term_set_output_func(tt, output, buffer); buffer[0] = 0; tickit_tick(t, TICKIT_RUN_NOHANG); /* This test is somewhat fragile, but there's not a lot we can do about * that. It has to be */ is_str_escape(buffer, "\e[?1049h" // ALTSCREEN on "\e[?25l" // CURSORVIS off "\e[?1002h\e[?1006h" // MOUSE "\e=" // KEYPAD_APP "\e[2J", // clear "buffer after setup"); tickit_unref(t); } { TickitTerm *tt = tickit_term_new_for_termtype("xterm"); Tickit *t = tickit_new_for_term(tt); tickit_term_set_output_func(tt, output, buffer); tickit_setctl_int(t, TICKIT_CTL_USE_ALTSCREEN, 0); buffer[0] = 0; tickit_tick(t, TICKIT_RUN_NOHANG); /* This test is somewhat fragile, but there's not a lot we can do about * that. It has to be */ is_str_escape(buffer, // no ALTSCREEN "\e[?25l" // CURSORVIS off "\e[?1002h\e[?1006h" // MOUSE "\e=" // KEYPAD_APP "\e[2J", // clear "buffer after setup"); tickit_unref(t); } return exit_status(); }
DimaBond174/lib_template
include/geomlib.h
/* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef GEOMLIB_H #define GEOMLIB_H #if defined _WIN32 || defined __CYGWIN__ #ifdef BUILDING_GeomLib #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllexport)) #else #define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax. #endif #else #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllimport)) #else #define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax. #endif #endif #define DLL_LOCAL #else #if __GNUC__ >= 4 #define DLL_PUBLIC __attribute__ ((visibility ("default"))) #define DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define DLL_PUBLIC #define DLL_LOCAL #endif #endif //extern "C" DLL_PUBLIC void set_logger(ILog *ilog); extern "C" DLL_PUBLIC const char *get_tag(); extern "C" DLL_PUBLIC void apply_settings(const char *json, int json_len); /* Check if the diagonals of the rectangle are the same JSON format: { "x1":123, "y1":123, "x2":123, "y2":123, "x3":123, "y3":123, "x4":123, "y4":123 } Will check distance (x1,y1)-(x3,y3) vs (x2,y2)-(x4,y4) --------------------- Return 0 if distances are different, 1 if distances are same */ extern "C" DLL_PUBLIC int check_restangle(const char *json, int json_len); #endif // GEOMLIB_H
DimaBond174/lib_template
src/common/i/iconfig.h
<reponame>DimaBond174/lib_template /* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef ICONFIG_H #define ICONFIG_H #include <string> #include "tools/specstatic.h" class IConfig { public: virtual ~IConfig() { } // setPath - where to load|save config virtual void set_paths(const std::string& in_exec_dir, const std::string& in_config_path) = 0; // try to save to path virtual void save() = 0; // try to load from path virtual bool load() = 0; // try load from JSON, values will replace existing virtual bool load_json(const char *in_json, uint32_t json_size) = 0; // try load from Dson, values will replace existing virtual bool load_dson(unsigned char *in_dson, uint32_t dson_size) = 0; // float you can store in minor ed: 1.23 -> 123 virtual int getIntValue(const ConstString &key) = 0; virtual long long getLongValue(const ConstString &key) = 0; virtual std::string getStringValue(const ConstString &key) = 0; virtual void setValue(const ConstString &key, const std::string &value) = 0; virtual void setValue(const ConstString &key, uint32_t value) = 0; std::string config_path; // where to save|load std::string exec_dir; // where executive to replace ./ -> fullpath }; #endif // ICONFIG_H
DimaBond174/lib_template
src/common/tools/specjson.h
<gh_stars>0 /* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef SPECJSON_H #define SPECJSON_H #include <string.h> #include <string> //must be greater 4: const int kSPECJSON_LEAF_SIZE = 256; class TNode { public: const char *pKey; unsigned int lenKey; void *pData; unsigned int lenData; TNode *nextNode; char type; }; class TLeaf { public: TNode nodes[kSPECJSON_LEAF_SIZE]; }; struct WhiteSpaces { unsigned char t[256]; WhiteSpaces() { memset(t, 0, 256); //'\t'==ch || ' '==ch || '\n'==ch || '\r'==ch t[static_cast<unsigned char>('\t')] = 1; t[static_cast<unsigned char>(' ')] = 1; t[static_cast<unsigned char>('\n')] = 1; t[static_cast<unsigned char>('\r')] = 1; } }; static WhiteSpaces whiteSpaces; //static const unsigned char whitespaces[256] = { // // 0 1 2 3 4 5 6 7 8 9 A B C D E F // 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 // 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // 2 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 // // // 128-255 // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 //}; struct Digits { unsigned char t[256]; Digits() { memset(t, 0, 256); //'\t'==ch || ' '==ch || '\n'==ch || '\r'==ch t[static_cast<unsigned char>('0')] = 1; t[static_cast<unsigned char>('1')] = 1; t[static_cast<unsigned char>('2')] = 1; t[static_cast<unsigned char>('3')] = 1; t[static_cast<unsigned char>('4')] = 1; t[static_cast<unsigned char>('5')] = 1; t[static_cast<unsigned char>('6')] = 1; t[static_cast<unsigned char>('7')] = 1; t[static_cast<unsigned char>('8')] = 1; t[static_cast<unsigned char>('9')] = 1; t[static_cast<unsigned char>('.')] = 1; } }; static Digits digits; //static const unsigned char digits[256] = { // // 0 1 2 3 4 5 6 7 8 9 A B C D E F // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, // 2 // 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 3 // 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 // 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 // // // 128-255 // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, // 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 //}; // 'z' = zero, not a node // 'n' = next leaf pointer // 's' = string // 'a' = array // 'o' = object // 'd' = digit // 'l' = true, false, null. class SpecJson { public: SpecJson(const char *json, unsigned int len, bool doCopy) : _json_len(len) { if (doCopy) { _jsonCopy = std::string(json, len); _json = _jsonCopy.c_str(); } else { _json = json; } state = 0; curLeaf = &headLeaf; curNode = 0; headLeaf.nodes[maxNode].type = 'z'; } ~SpecJson() { if ('n' == headLeaf.nodes[maxNode].type) { freeLeafs((TLeaf *)(headLeaf.nodes[maxNode].pData)); } } bool parse() { const char *p = _json; const char *pEnd = _json + _json_len; for (; p < pEnd; ++p) { if ('{' == *p) { ++p; if (parseObject_inJSON(p, pEnd)) { if (-1 != state) { state = 1; } return true; } } } return false; } std::string getStrByKey(const char *key, unsigned int keyLen) { return getStrByKey(key, keyLen, &(headLeaf.nodes[0])); } inline bool keyCompare(const char *lKey, unsigned int lKeyLen, const char *rKey, unsigned int rKeyLen) { if (lKeyLen == rKeyLen && rKeyLen > 0) { do { --rKeyLen; if (lKey[rKeyLen] != rKey[rKeyLen]) { return false; } } while (rKeyLen > 0); return true; } return false; } std::string getStrByKey(const char *key, unsigned int keyLen, TNode *jsonObj) { std::string re; if (1 == state) { TNode *cur = jsonObj; while (cur) { if (keyCompare(key, keyLen, cur->pKey, cur->lenKey)) { switch (cur->type) { case 's': case 'd': return std::string(static_cast<const char *>(cur->pData), cur->lenData); } } cur = cur->nextNode; } } return re; } TNode * getObjByKey(const char *key, unsigned int keyLen, TNode *jsonObj) { TNode *re = 0; if (1 == state) { TNode *cur = jsonObj; while (cur) { if (keyCompare(key, keyLen, cur->pKey, cur->lenKey)) { if ('o' == cur->type) { re = cur; break; } } cur = cur->nextNode; } } return re; } TNode * getFirstNode() { TNode *re = 0; if (1 == state) { re = &(headLeaf.nodes[0]); if ('z' == re->type) { re = 0; } } // state return re; } private: const char *_json; const unsigned int _json_len; std::string _jsonCopy; int state; TLeaf headLeaf; TLeaf *curLeaf; unsigned int curNode; static const unsigned int maxNode = (kSPECJSON_LEAF_SIZE - 1); void freeLeafs(TLeaf *n) { if ('n' == n->nodes[maxNode].type) { freeLeafs(static_cast<TLeaf *>(n->nodes[maxNode].pData)); } delete n; } TNode * getNewNode() { TNode *re = &(curLeaf->nodes[curNode]); re->type = 'z'; re->lenData = re->lenKey = 0; re->pKey = 0; re->pData = 0; re->nextNode = 0; ++curNode; if (curNode == maxNode) { TLeaf *nextLeaf = new TLeaf(); nextLeaf->nodes[maxNode].type = 'z'; TNode *n = &(curLeaf->nodes[curNode]); n->type = 'n'; n->pData = reinterpret_cast<void *>(nextLeaf); n->lenData = n->lenKey = 0; n->pKey = 0; n->nextNode = 0; curLeaf = nextLeaf; curNode = 0; } return re; } inline unsigned int getStrLen(const char * &p, const char *pEnd) { unsigned int re = 0; while (p < pEnd) { if ('\\' == *p && '"' == *(p + 1)) { ++re; ++p; } else if ('"' == *(p)) { return re; } ++re; ++p; } // while state = -1; return 0; } inline unsigned int getNumLen(const char * &p, const char *pEnd) { unsigned int re = 0; while (p < pEnd && digits.t[static_cast<unsigned char>(*p)]) { ++re; ++p; } return re; } TNode * parseArray(const char * &p, const char *pEnd, unsigned int *lenData) { *lenData = 0; TNode *reNode = 0; TNode *preNode = 0; TNode *curNode = 0; unsigned int cnt = 0; while (p < pEnd) { if (whiteSpaces.t[static_cast<unsigned char>(*p)]) { ++p; continue; } switch (*p) { case ',': break; case ']': break; case '"': curNode = getNewNode(); ++cnt; if (preNode) { preNode->nextNode = curNode; preNode = curNode; } else { reNode = preNode = curNode; } ++p; curNode->pData = (void *)(p); curNode->lenData = getStrLen(p, pEnd); curNode->type = 's'; //string break; case '{': curNode = getNewNode(); ++cnt; if (preNode) { preNode->nextNode = curNode; preNode = curNode; } else { reNode = preNode = curNode; } curNode->pData = parseObject_inJSON(++p, pEnd);//parseObject_inArray(++p, pEnd); curNode->lenData = 0; curNode->type = 'o'; //object break; case '[': curNode = getNewNode(); ++cnt; if (preNode) { preNode->nextNode = curNode; preNode = curNode; } else { reNode = preNode = curNode; } curNode->pData = parseArray(++p, pEnd, &(curNode->lenData)); curNode->type = 'a'; //array break; default: if (digits.t[static_cast<unsigned char>(*p)]) { curNode = getNewNode(); ++cnt; if (preNode) { preNode->nextNode = curNode; preNode = curNode; } else { reNode = preNode = curNode; } curNode->pData = (void *)(p); curNode->lenData = getNumLen(p, pEnd); curNode->type = 'd'; //digital break; } return nullptr; } if (']' == *p) { ++p; *lenData = cnt; return reNode; } ++p; } // while (p<pEnd) state = -1; return nullptr; } // parseArray TNode * parseObject_inJSON(const char * &p, const char *pEnd) { TNode *reNode = 0; TNode *preNode = 0; TNode *curNode = 0; unsigned char searchLvl = 0; //key //bool allOk = true; while (p < pEnd) { if (whiteSpaces.t[static_cast<unsigned char>(*p)]) { ++p; continue; } switch (*p) { case '"': if (0 == searchLvl) { curNode = getNewNode(); curNode->pKey = ++p; curNode->lenKey = getStrLen(p, pEnd); if (-1 == state) { return nullptr; } curNode->type = 'z'; //zero if (preNode) { preNode->nextNode = curNode; preNode = curNode; } else { reNode = preNode = curNode; } ++searchLvl; } else if (2 == searchLvl) { ++p; curNode->pData = (void *)(p); curNode->lenData = getStrLen(p, pEnd); curNode->type = 's'; //string searchLvl = 0; } break; case ':': if (1 == searchLvl) { ++searchLvl; } else { state = -1; return nullptr; } break; case '}': break; case '{': if (2 == searchLvl) { curNode->pData = parseObject_inJSON(++p, pEnd); curNode->lenData = 0; curNode->type = 'o'; //object searchLvl = 0; } else { state = -1; return nullptr; } break; case '[': if (2 == searchLvl) { curNode->pData = parseArray(++p, pEnd, &(curNode->lenData)); curNode->type = 'a'; //array searchLvl = 0; } else { state = -1; return nullptr; } break; case ',': if (0 == searchLvl) { break; } default: if (2 == searchLvl) { if (digits.t[static_cast<unsigned char>(*p)]) { curNode->pData = (void *)(p); curNode->lenData = getNumLen(p, pEnd); curNode->type = 'd'; //digital searchLvl = 0; break; } } return nullptr; } if ('}' == *p) { if (0 == searchLvl) { ++p; return reNode; } else { state = -1; return nullptr; } } ++p; } // while (p<pEnd) //if (0 == searchLvl // && (p == pEnd) // && ('}' == *(p - 1))) { // return reNode; //} state = -1; return nullptr; } // parseObject }; #endif // SPECJSON_H
DimaBond174/lib_template
src/common/config/json/configjson.h
/* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef ConfigJSON_H #define ConfigJSON_H #pragma once #include <string> #include <map> #include "i/iconfig.h" #include "tools/specjson.h" class ConfigJSON : public IConfig { public: // setPath - where to load|save config void set_paths(const std::string& in_exec_dir, const std::string& in_config_path) override; // try to save to path void save() override; // try to load from path bool load() override; // try load from JSON, values will replace existing bool load_json(const char *in_json, uint32_t json_size) override; // try load from Dson, values will replace existing bool load_dson(unsigned char *in_dson, uint32_t dson_size) override; // update current Dson, return true is something new found bool if_new_in_update_json(const char *in_json, int32_t json_size); // float you can store in minor ed: 1.23 -> 123 int getIntValue(const ConstString &key) override; long long getLongValue(const ConstString &key) override; std::string getStringValue(const ConstString &key) override; void setValue(const ConstString &key, const std::string &value) override; void setValue(const ConstString &key, uint32_t value) override; ConfigJSON(); virtual ~ConfigJSON() {} protected: std::map<std::string, std::string> mapConfig; virtual void traverse(TNode *node); bool check_traverse(TNode *node); }; #endif //ConfigJSON_H
DimaBond174/lib_template
src/main_lib/src/impl/geomimpl.h
<reponame>DimaBond174/lib_template<gh_stars>0 /* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef GeomImpl_H #define GeomImpl_H class GeomImpl { public: const char *get_tag() { return TAG; } void apply_settings(const char *json, int json_len); int check_restangle(const char *json, int json_len); private: const char * const TAG { "GeomLib" }; }; #endif // GeomImpl_H
DimaBond174/lib_template
src/common/i/ilib.h
/* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef ILIB_H #define ILIB_H #if defined _WIN32 || defined __CYGWIN__ #ifdef BUILDING_LIB #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllexport)) #else #define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax. #endif #else #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllimport)) #else #define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax. #endif #endif #define DLL_LOCAL #else #if __GNUC__ >= 4 #define DLL_PUBLIC __attribute__ ((visibility ("default"))) #define DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define DLL_PUBLIC #define DLL_LOCAL #endif #endif #endif // ILIB_H
DimaBond174/lib_template
src/main_test/src/test1/test1_impl.h
<filename>src/main_test/src/test1/test1_impl.h /* * This is the source code of SpecNet project * It is licensed under MIT License. * * Copyright (c) <NAME> * feel free to contact me: <EMAIL> */ #ifndef Test1Lib_H #define Test1Lib_H #if defined _WIN32 || defined __CYGWIN__ #ifdef BUILDING_Test1Lib #ifdef __GNUC__ #define DLL_PUBLIC_T __attribute__ ((dllexport)) #else #define DLL_PUBLIC_T __declspec(dllexport) // Note: actually gcc seems to also supports this syntax. #endif #else #ifdef __GNUC__ #define DLL_PUBLIC_T __attribute__ ((dllimport)) #else //#define DLL_PUBLIC_T __declspec(dllimport) // Note: actually gcc seems to also supports this syntax. // https://stackoverflow.com/questions/5159353/how-can-i-get-rid-of-the-imp-prefix-in-the-linker-in-vc // Для статики нельзя делать префикс __declspec(dllimport)!!! #define DLL_PUBLIC_T #endif #endif #define DLL_LOCAL_T #else #if __GNUC__ >= 4 #define DLL_PUBLIC_T __attribute__ ((visibility ("default"))) #define DLL_LOCAL_T __attribute__ ((visibility ("hidden"))) #else #define DLL_PUBLIC_T #define DLL_LOCAL_T #endif #endif extern "C" DLL_PUBLIC_T int do_Test1(); #endif // Test1Lib_H
tacrazymage/Data-Structures-and-Algorithms
Graph Algorithms/boilerplate.h
<gh_stars>10-100 /* * author: @tirthasheshpatel * Base code for all Graph Algorithms * Contains implementation of: Queue, Stack, Linked Lists. */ #ifndef GUARD_BOILERPLATE_H #define GUARD_BOILERPLATE_H // Importing dependencies #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #define INF 2147483647; // Making the `size_t` keyword easier to interpret. typedef size_t size_type; // A pointer to the nodes in the list // is defined for easy use in functions. typedef struct Node* list_iterator; typedef struct vertex* vertex_iterator; // A structure of `Node` used in the // doubly linked list for storing keys // and pointers to neighbouring Nodes. struct Node { vertex_iterator key; // Stores the value to be accessed by the user at runtime. // Pointers to the next and previous elements in the list. list_iterator prev, next; }; typedef struct vertex { int value; char color; int depth; int start; int end; vertex_iterator parent; list_iterator adj_list; }Vertex; typedef struct queue { int size; int front; int rear; vertex_iterator* que; }Queue; typedef struct stack { int empty; list_iterator head; list_iterator tail; }Stack; void init_stack(Stack* s) { s->empty = 1; s->head = s->tail = 0; } void push(Stack* s, vertex_iterator key) { if(s->empty == 1) { s->empty = 0; s->head = (list_iterator)malloc(sizeof(struct Node)); s->head->key = key; s->head->next = 0; s->head->prev = 0; s->tail = s->head; } else { s->tail->next = (list_iterator)malloc(sizeof(struct Node)); s->tail->next->key = key; s->tail->next->next = 0; s->tail->next->prev = s->tail; s->tail = s->tail->next; } } vertex_iterator pop(Stack* s) { if(s->empty == 1) { printf("Stack empty!"); exit(1); } else if(s->head == s->tail) { vertex_iterator element = s->head->key; s->empty = 1; s->head = s->tail = 0; return element; } vertex_iterator element = s->tail->key; s->tail = s->tail->prev; s->tail->next = 0; return element; } // A function that creates and initializes the // doubly linked list. list_iterator create_doubly_linked_list(vertex_iterator key) { /* * Arguments: `key` (int) -> A value to be stored in the list. * Creates a doubly linked list. * Returns : `first` (list_iterator) -> A pointer to the first element of list. */ // Step 1: Allocate memory to store a variable of type `Node`. list_iterator first = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize key as provided by the user. first->key = key; // Step 3: First element in the list so it doesn't // have next and prev elements. first->prev = 0; first->next = 0; // Step 4: Return the pointer to allocated node. return first; } // Insert a node at the front of the linked list in O(1) time. list_iterator insert_in_front_of_the_doubly_linked_list(list_iterator first, vertex_iterator key) { /* * Argments: `first` (list_iterator) -> A pointer to the first element in the list. * Initialize the list using `create_doubly_linked_list()` * to get this pointer variable * `key` (int) -> The element to be stored in the list. * This function is used to insert a Node at the front of the * doubly linked list. The Node is intialized by the provided value * of the key and other attributes are initalized according to * the previously allocated nodes. * Returns: `new_node` (list_iterator) -> A pointer variable pointing at the new * Node inserted using this function. */ // Step 1: Allocate memory for the new node to be stored. list_iterator new_node = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize the key using the key provided by user. // Step 3: This node has the `next` member as `first` // which used to be the first Node in the list. // Step 4: Also, don't forget to add the newly allocated // node as the previous member of the `first` Node. // Step 5: The previous member is still `NULL`. new_node->key = key; new_node->next = first; first->prev = new_node; new_node->prev = 0; // Step 6: Return the newly allocated node which will act as the 'first' node in the list. return new_node; } void initalize_queue(Queue* q, int size) { q->size = size; q->front = q->rear = -1; q->que = (vertex_iterator*)malloc(size*sizeof(vertex_iterator)); for(int i=0;i<q->size;i++) { q->que[i] = 0; } // printf("Queue Initialized!!\n\n"); } void reintialize_in_queue(Queue* q) { q->que[q->front] = 0; } void enqueue(Queue* q, vertex_iterator val) { if(q->front==(q->rear+1)%q->size){ printf("\nQueue Overflow!"); exit(1); } else { q->rear=(q->rear+1)%q->size; q->que[q->rear]=val; if(q->front==-1) q->front=0; } } vertex_iterator dequeue(Queue* q) { if(q->front==-1) { printf("\nQueue Underflow!"); exit(1); } else { vertex_iterator ele; ele=q->que[q->front]; if(q->front==q->rear) { reintialize_in_queue(q); q->front=-1; q->rear=-1; } else { reintialize_in_queue(q); q->front=(q->front+1)%q->size; } return ele; } } #endif
tacrazymage/Data-Structures-and-Algorithms
priority_queue.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX 3 typedef struct queue Queue; struct queue { int front; int rear; int q[MAX+1][2]; }; // Deletes a element from the front of the Queue. int* dequeue(Queue* q) { /* * Arguments: `q` (Queue*) -> A referance to a Queue object * Deletes and returns the first element present in the Queue `q`. * Returns : `ele` (int) -> First element in the Queue `q` */ // If the `front` and `rear` attributes of // Queue `q` are overlapping // and are not equal to -1 means there is // only one element present in the Queue // which we will delete and reset the attributes // again to -1. if(q->front == q->rear && q->front != -1) { int *ele = q->q[q->front]; // get element in front of the queue q->q[q->front][0] = 0; // reinitialize the element q->q[q->front][1] = 0; // reinitialize priority q->front = q->rear = -1; // reset the attributes return ele; // return element. } // If the front or the rear attributes // are -1 means there are no elements // present in the queue and further // deletion doesn't make sense. So, // print error. else if(q->front == -1) { printf("Queue Underflow!\nTerminating Program...\n"); exit(1); // terminate program } // Else delete element and increament // `front` attribute of Queue `q`. else { // extract the element int *ele = q->q[q->front]; q->q[q->front][0] = 0; // reinitialize the element q->q[q->front][1] = 0; // reinitialize priority q->front++; // increment front return ele; // return element } } void enqueue(Queue* q, int key, int priority) { /* * Arguments: `q` (Queue*) -> A referance to a queue `q`. * `key` (int) -> A value to be inserted in the queue `q`. * Inserts `key` at the top of the queue `q`. */ // If the rear of the queue has reached its // maximum `MAX` print error Overflow. if(q->rear == MAX){ printf("Queue Overflow\nTerminating Program...\n"); exit(1); } // Else insert key at the end of // the queue `q`. else { if(q->rear!=-1){ int insertInd = q->rear; q->rear++; // increment attribute `rear` while(priority < q->q[insertInd][1]) { q->q[insertInd+1][0] = q->q[insertInd][0]; q->q[insertInd+1][1] = q->q[insertInd][1]; insertInd--; } q->q[insertInd+1][0] = key; // insert key q->q[insertInd+1][1] = priority; // insert priority } else { q->rear++; q->q[q->rear][0] = key; // insert key q->q[q->rear][1] = priority; // insert priority q->front++; } } } void disp_queue(Queue* q) { if(q->front == -1) printf("No elements present in the queue!"); else for(int i=q->front;i<=q->rear;i++) printf("[%d]%d ", q->q[i][1], q->q[i][0]); printf("\n"); } void init_queue(Queue* q) { q->front = -1; q->rear = -1; for(int i=0;i<MAX;i++) { q->q[i][0] = q->q[i][1] = 0; } } int main() { Queue que; init_queue(&que); enqueue(&que, 10, 1); enqueue(&que, 20, 2); enqueue(&que, 30, 3); enqueue(&que, 40, 1); disp_queue(&que); }
tacrazymage/Data-Structures-and-Algorithms
queue_using_static_array.c
<filename>queue_using_static_array.c<gh_stars>10-100 /* * @author: tirthasheshpatel * @g-mail: <EMAIL> * Summary: Queue implemented using static array */ // Inclusing necessary libraries #include <stdio.h> // printf, scanf, fflush #include <stdlib.h> #define MAX 65535 // Alternate for `struct queue` typedef struct queue Queue; // Alternate for `size_t` typedef size_t size_type; // A stucture for Queue holding attributes: // `front`: A integer indicating the first element in the array // `rear` : A integer indicating the last element in the array. // `q` : A array (of size `MAX`) holding values in the queue. struct queue { int front; int rear; int q[MAX+1]; }; // Deletes a element from the front of the Queue. int dequeue(Queue* q) { /* * Arguments: `q` (Queue*) -> A referance to a Queue object * Deletes and returns the first element present in the Queue `q`. * Returns : `ele` (int) -> First element in the Queue `q` */ // If the `front` and `rear` attributes of // Queue `q` are overlapping // and are not equal to -1 means there is // only one element present in the Queue // which we will delete and reset the attributes // again to -1. if(q->front == q->rear && q->front != -1) { int ele = q->q[q->front]; // get element in front of the queue q->q[q->front] = 0; // reinitialize the element q->front = q->rear = -1; // reset the attributes return ele; // return element. } // If the front or the rear attributes // are -1 means there are no elements // present in the queue and further // deletion doesn't make sense. So, // print error. else if(q->front == -1) { printf("Queue Underflow!\nTerminating Program...\n"); exit(1); // terminate program } // Else delete element and increament // `front` attribute of Queue `q`. else { // extract the element int ele = q->q[q->front]; q->q[q->front] = 0; // reinitialize the element q->front++; // increment front return ele; // return element } } void enqueue(Queue* q, int key) { /* * Arguments: `q` (Queue*) -> A referance to a queue `q`. * `key` (int) -> A value to be inserted in the queue `q`. * Inserts `key` at the top of the queue `q`. */ // If the rear of the queue has reached its // maximum `MAX` print error Overflow. if(q->rear == MAX){ printf("Queue Overflow\nTerminating Program...\n"); exit(1); } // Else insert key at the end of // the queue `q`. else { q->rear++; // increment attribute `rear` q->q[q->rear] = key; // insert key // If this is the first element inserted // in the Queue, do q->front = 0; if(q->front == -1) q->front++; } } void disp_queue(Queue* q) { if(q->front == -1) printf("No elements present in the queue!"); else for(int i=q->front;i<=q->rear;i++) printf("%d ", q->q[i]); printf("\n"); } int main() { Queue que = {-1,-1,0}; enqueue(&que, 10); enqueue(&que, 20); disp_queue(&que); dequeue(&que); disp_queue(&que); dequeue(&que); disp_queue(&que); }
tacrazymage/Data-Structures-and-Algorithms
Greedy Algorithms/huffmann_codes.c
<reponame>tacrazymage/Data-Structures-and-Algorithms #include <stdio.h> #include <stdlib.h> typedef struct node Node; struct node { int value; Node* right; Node* left; }; int left(int i) { return 2 * i + 1; } int right(int i) { return 2 * i + 2; } int parent(int i) { return ceil((float)i / 2) - 1; } void min_heapify(int arr[], int i, int n) { int l = left(i); int r = right(i); int lowest; if (l < n && arr[l] < arr[i]) lowest = l; else lowest = i; if (r < n && arr[r] < arr[lowest]) lowest = r; if (lowest != i) { swap(&arr[i], &arr[lowest]); min_heapify(arr, lowest, n); } } int heap_extract_min(int arr[], int *n) { if ((*n) < 1) return -10000; int min = arr[0]; swap(&arr[0], &arr[(*n) - 1]); (*n)--; min_heapify(arr, 0, (*n)); return min; } void huffman(Node* tree[], int nb_characters) { }
tacrazymage/Data-Structures-and-Algorithms
polynomial_addition.c
<reponame>tacrazymage/Data-Structures-and-Algorithms<filename>polynomial_addition.c<gh_stars>10-100 #include <stdio.h> #include <stdlib.h> typedef struct node* iterator; typedef struct node { int coef; int expo; struct node* next; }Node; iterator create_singly_linked_list(int coef, int expo) { iterator head = (iterator)malloc(sizeof(Node)); head->coef = coef; head->expo = expo; head->next = 0; return head; } iterator insert_inorder(int coef, int expo, iterator head) { iterator it = head; iterator prev = 0; if(head->expo < expo) { iterator new = (iterator)malloc(sizeof(Node)); new->coef = coef; new->expo = expo; new->next = head; head = new; return head; } while(it->expo > expo) { if(it->next == 0) { if(it->coef == coef) { it->coef += coef; return head; } iterator new = (iterator)malloc(sizeof(Node)); new->coef = coef; new->expo = expo; new->next = 0; it->next = new; return head; } prev = it; it = it->next; } if(it->expo == expo) { it->coef += coef; return head; } iterator new = (iterator)malloc(sizeof(Node)); new->coef = coef; new->expo = expo; new->next = it; prev->next = new; return head; } iterator insert_at_end(int coef, int expo, iterator head) { iterator it = head; while(it->next != 0) it = it->next; iterator new = (iterator)malloc(sizeof(Node)); new->coef = coef; new->expo = expo; new->next = 0; it->next = new; return head; } iterator add_polynomials(iterator head1, iterator head2) { iterator temp1 = head1; iterator temp2 = head2; iterator head3 = 0; while(temp1 != 0 && temp2 != 0) { if(temp1->expo < temp2->expo) { if(head3 == 0){ head3 = create_singly_linked_list(temp2->coef, temp2->expo); } else{ head3 = insert_at_end(temp2->coef, temp2->expo, head3); } temp2 = temp2->next; } else if(temp1->expo > temp2->expo) { if(head3 == 0){ head3 = create_singly_linked_list(temp1->coef, temp1->expo); } else{ head3 = insert_at_end(temp1->coef, temp1->expo, head3); } temp1 = temp1->next; } else { if(head3 == 0){ head3 = create_singly_linked_list(temp1->coef + temp2->coef, temp1->expo); } else{ head3 = insert_at_end(temp1->coef + temp2->coef, temp1->expo, head3); } temp1 = temp1->next; temp2 = temp2->next; } } iterator it = head3; while(it->next != 0) it = it->next; if(temp1 == 0 && temp2 != 0) it->next = temp2; else if(temp2 == 0 && temp1 != 0) it->next = temp1; return head3; } void display_sll(iterator head) { iterator it = head; while(it->next != 0) { printf("%d * x^%d + ", it->coef, it->expo); it = it->next; } printf("%d * x^%d", it->coef, it->expo); printf("\n"); } int main() { iterator head1 = 0; iterator head2 = 0; int terms1, terms2; printf("Enter the number of terms in first polynomial: "); scanf("%d", &terms1); printf("Enter the coeficient and exponent for all terms of first polynomial: "); for(int i=0;i<terms1;i++) { int coef, expo; scanf("%d%d", &coef, &expo); if(head1 == 0) head1 = create_singly_linked_list(coef, expo); else head1 = insert_inorder(coef, expo, head1); } display_sll(head1); printf("Enter the number of terms in second polynomial: "); scanf("%d", &terms2); printf("Enter the coeficient and exponent for all terms of second polynomial: "); for(int i=0;i<terms2;i++) { int coef, expo; scanf("%d%d", &coef, &expo); if(head2 == 0) head2 = create_singly_linked_list(coef, expo); else head2 = insert_inorder(coef, expo, head2); } display_sll(head2); iterator head3 = add_polynomials(head1, head2); display_sll(head3); }
tacrazymage/Data-Structures-and-Algorithms
infix_to_prefix/main.c
<reponame>tacrazymage/Data-Structures-and-Algorithms<filename>infix_to_prefix/main.c #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX 65535 struct stack { int top; char s_content[MAX+1]; }; void PUSH(struct stack *s, char value) { if(s->top==MAX) perror("Overflow"); s->top++; s->s_content[s->top]=value; } char POP(struct stack *s) { if(s->top==-1) perror("Underflow !!!"); char element = s->s_content[s->top]; s->s_content[s->top]=0; s->top--; return element; } int f(char a) { if(a=='(') return 9; if(isalpha(a)) return 7; if(a=='^') return 6; if(a=='*' || a=='/') return 3; if(a=='+' || a=='-') return 1; if(a==')' || a=='#') return 0; return -1000; } int g(char a) { if(isalpha(a)) return 8; if(a=='^') return 5; if(a=='*' || a=='/') return 4; if(a=='+' || a=='-') return 2; if(a==')' || a=='#') return -1; return 0; } int r(char a) { if(isalpha(a)) return 1; if(a=='+' || a=='-' || a=='*' || a=='/' || a=='^') return -1; if(a=='#') return 0; return -1; } void infix_to_prefix(char infix[]) { char prefix[500]; int rank=0; struct stack s = {-1,0}; int i=0,j=0; PUSH(&s,'#'); while(infix[i]!='#') { while(g(s.s_content[s.top]) >= f(infix[i])) { char temp= POP(&s); if(temp!='(' && temp!=')') { prefix[j++]=temp; rank+= r(temp); } } PUSH(&s,infix[i++]); } while(s.s_content[s.top] != '#') { char temp= POP(&s); if(temp != '(' && temp != ')') { prefix[j++]=temp; rank += r(temp); } } prefix[j]='\0'; char prefix_final[100]; strcpy(prefix_final,""); int j2=0; for(int i=strlen(prefix)-1;i>=0;i--) { prefix_final[j2]=prefix[i]; j2++; } prefix_final[j2]='\0'; printf("Prefix expression is : "); puts(prefix_final); } int main() { printf("enter the expression :"); char infix_0[100]; gets(infix_0); char infix[100]; int j=0; for(int i=strlen(infix_0)-1;i>=0;i--) { if(infix_0[i] == '(') infix[j] = ')'; else if(infix_0[i] == ')') infix[j] = '('; else infix[j]=infix_0[i]; j++; } infix[j]='#'; infix[j+1]='\0'; infix_to_prefix(infix); }
tacrazymage/Data-Structures-and-Algorithms
Dynamic Programming/longest_common_subsequence.c
#include <stdio.h> #include <stdlib.h> #include <string.h> void LCS(char X[], char Y[]) { int m = strlen(X)+1; int n = strlen(Y)+1; int c[m][n]; char b[m][n]; for(int i=0;i<m;i++) c[i][0] = 0; for(int i=0;i<n;i++) c[0][i] = 0; for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { if(X[i-1] == Y[j-1]) { c[i][j] = c[i-1][j-1]+1; b[i][j] = '\\'; } else if(c[i-1][j] >= c[i][j-1]) { c[i][j] = c[i-1][j]; b[i][j] = '|'; } else { c[i][j] = c[i][j-1]; b[i][j] = '-'; } } } printf("\n"); printf(" - "); for(int i=0;i<n;i++) printf("%c ", Y[i]); printf("\n"); for(int i=0;i<m;i++) { printf(" "); for(int j=0;j<n;j++) { printf("%c ", b[i][j]); } printf("\n"); if(i == 0) printf("- "); else printf("%c ", X[i-1]); for(int j=0;j<n;j++) { printf("%d ", c[i][j]); } printf("\n"); } printf("\n"); char lcs[c[m-1][n-1]+1]; int i=m-1, j=n-1, k=c[m-1][n-1]-1; while(i!=0 && j!=0) { if(X[i-1] == Y[j-1]) { lcs[k] = X[i-1]; k--; i--; j--; } else if(c[i-1][j] >= c[i][j-1]) { i--; } else j--; } lcs[c[m-1][n-1]] = '\0'; printf("The lcs of %s and %s is %s.", X, Y, lcs); } int main() { char A[] = "tirthasheshpatel"; char B[] = "letaphsehsahtrit"; LCS(A,B); }
tacrazymage/Data-Structures-and-Algorithms
tower_of_hanoi.c
#include <stdio.h> #include <stdlib.h> void tower_of_hanoi(int n, int fromPeg, int auxPeg, int toPeg) { if(n == 1) printf("Move top disk from peg %d to peg %d\n", fromPeg, toPeg); else{ tower_of_hanoi(n-1, fromPeg, toPeg, auxPeg); printf("Move top disk from peg %d to peg %d\n", fromPeg, toPeg); tower_of_hanoi(n-1, auxPeg, fromPeg, toPeg); } } int main() { tower_of_hanoi(3, 1, 2, 3); }
tacrazymage/Data-Structures-and-Algorithms
queue/queue/Queue.h
<reponame>tacrazymage/Data-Structures-and-Algorithms #ifndef GUARD_QUEUE_H #define GUARD_QUEUE_H #include <memory> #include <algorithm> #include <stdexcept> using std::max; template<class T> class Queue { public: typedef T* iterator; typedef const T* const_iterator; typedef size_t size_type; typedef T value_type; Queue() { create(); } explicit Queue(size_type n, const T& val = T()) { create(n, val); } Queue(const Queue& q) { create(q.begin(), q.end()); } Queue& operator=(const Queue&); ~Queue() { uncreate(); } T& operator[](size_type i) { return data[i]; } const T& operator[](size_type i) const { return data[i]; } size_type size() const { return avail - data; } void empty() { return avail == data; } void clear() { uncreate(); } T& dequeue() { if (data) { T val = data[0]; size_type new_size = max(limit - data, ptrdiff_t(1)); iterator new_data = alloc.allocate(new_size); iterator new_avail = std::uninitialized_copy(data + 1, avail, new_data); uncreate(); data = new_data; avail = new_avail; limit = data + new_size; return val; } else throw std::domain_error("Queue Underflow!"); } void enqueue(const T& val) { if (avail == limit) grow(); append(val); } private: iterator data; iterator avail; iterator limit; std::allocator<T> alloc; void create() { data = avail = limit = 0; } void create(size_type n, const T& val) { data = alloc.allocate(n); avail = limit = data + n; std::uninitialized_fill(data, avail, val); } void create(const_iterator i, const_iterator j) { data = alloc.allocate(j - i); avail = limit = std::uninitialized_copy(i, j, data); } void uncreate() { if (data) { iterator it = avail; while (it != avail) { alloc.destroy(--it); } alloc.deallocate(data, limit - data); } data = avail = limit = 0; } void grow() { size_type new_size = max(2 * (avail - data), ptrdiff_t(1)); iterator new_data = alloc.allocate(new_size); iterator new_avail = std::uninitialized_copy(data, avail, new_data); uncreate(); data = new_data; avail = new_avail; limit = new_data + new_size; } void append(const T& val) { alloc.construct(avail++, val); } }; #endif template<class T> Queue<T>& Queue<T>::operator=(const Queue& rhs) { if (&rhs != this) { uncreate(); create(rhs.begin(), rhs.end()); } return *this; }
tacrazymage/Data-Structures-and-Algorithms
stack/stack/Stack.h
<filename>stack/stack/Stack.h #ifndef GUARD_STACK_H #define GUARD_STACK_H #include <memory> #include <cstddef> #include <stdexcept> #include <algorithm> template<class T> class Stack { public: typedef T* iterator; typedef const T* const_iterator; typedef size_t size_type; typedef T value_type; Stack() { create(); } explicit Stack(size_type n, const T& val = T()) { create(n, val); } Stack(const Stack& s) { create(s.begin(), s.end()); } Stack& operator=(const Stack&); ~Stack() { uncreate(); } size_type size() const { return avail - data; } T& operator[](size_type i) { return data[i]; } const T& operator[](size_type i) const { return data[i]; } iterator begin() { return data; } const_iterator begin() const { return data; } iterator end() { return avail; } const_iterator end() const { return avail; } T& pop_back(); void push_back(const T&); void clear() { uncreate(); } bool empty() { return data == avail; } private: iterator data; iterator avail; iterator limit; std::allocator<T> alloc; void create(); void create(size_type, const T&); void create(const_iterator, const_iterator); void grow(); void uncreate(); void append(const T&); }; #endif template<class T> T& Stack<T>::pop_back() { if (avail == data) { throw std::domain_error("Stack Underflow!"); } iterator it = avail; T val = *(it - 1); alloc.destroy(--it); avail--; return val; } template<class T> void Stack<T>::push_back(const T& val) { if (avail == limit) grow(); append(val); } template<class T> void Stack<T>::create() { data = avail = limit = 0; } template<class T> void Stack<T>::create(size_type n, const T& val) { data = alloc.allocate(n); limit = avail = data + n; std::uninitialized_fill(data, avail, val); } template<class T> void Stack<T>::create(const_iterator i, const_iterator j) { data = alloc.allocate(j - i); avail = limit = std::uninitialized_copy(i, j, data); } template<class T> void Stack<T>::grow() { size_type new_size = std::max(2 * (limit - data), ptrdiff_t(1)); iterator new_data = alloc.allocate(new_size); iterator new_avail = std::uninitialized_copy(data, avail, new_data); uncreate(); data = new_data; avail = new_avail; limit = data + new_size; } template<class T> void Stack<T>::uncreate() { if (data) { iterator it = avail; while (it != data) { alloc.destroy(--it); } alloc.deallocate(data, limit - data); } data = avail = limit = 0; } template<class T> void Stack<T>::append(const T& val) { alloc.construct(avail++, val); } template<class T> Stack<T>& Stack<T>::operator=(const Stack& rhs) { if (&rhs != this) { uncreate(); create(rhs.begin(), rhs.end()); } return *this; }
tacrazymage/Data-Structures-and-Algorithms
prefix_to_postfix/main.c
<reponame>tacrazymage/Data-Structures-and-Algorithms /* ->Author : <NAME> ->Editor : <NAME> ->E-mail : <EMAIL> ->Summary : Converting `prefix` to `postfix` using STACK */ #include <stdio.h> #include <stdlib.h> // malloc, calloc #include <ctype.h> // isalpha #include <string.h> // strlen, strcpy, strcat #include <errno.h> // perror // Making a Structure of Stack that can store // a string struct stack { int top; // integer indicating the size of the string array // An array of maximum 100 string type element. char st[100][100]; }; // PUSH is a operation // to add an element onto the stack. void PUSH(struct stack *s,char n3[]) { /* * Arguments: `s` (stack) -> A stack object in which you want to push. * `n3` (c_str) -> A string object to be pushed to the stack `s`. * Inserts the string `n3` on the top of the stack. * Returns: - */ // If stack is full print error "Overflow!" if(s->top==100) perror("Overflow"); // Else, increment the top attribute of the stack // and insert element at the new index of the `st` attribute // of stack. else { s->top++; // increment top strcpy(s->st[s->top],n3); // Copy the passed string onto the stack. } } // POP element from the top of the stack void POP(struct stack *s, char element[]) { /* * Arguments: `s` (stack) -> A stack object from which the element * is being poped. * `element` (c_str) -> A string object in which the poped element * is stored. * Deletes top element from the `st` attribute of the stack object * and stores the deleted object in string `element`. * Returns: - */ // If the stack is empty, print error "Underflow" if(s->top==-1) perror("Underflow\n"); // Else, copy the top string and decrement `top` attribute by 1. else{ strcpy(element,s->st[s->top]); // copy top of stack in `element` s->top--; // decrement top return; } } // Converts a prefix strint to postfix. void prefix_to_postfix(char p[]) { // Make a stack object and initialize the `top` as -1. struct stack s = {-1}; int i=strlen(p)-1; // used to iterate through the postfix string. do { if(isalpha(p[i])) //isalpha(p[i]) will return true if //p[i] is alphabet i.e. for us `variable name` { char temp[100]; //it is temporary string to copy the `variable name` temp[0]=p[i]; temp[1]='\0'; //because string should end with `\0` PUSH(&s,temp); //it will push the `temp` to the stack of string } // Now if while scanning the prefix if any operator aqppears then // POP the last `variable_name` then append the operator then // again POP the `variable_name` and also append it. else if(p[i]=='+' || p[i]=='-' || p[i]=='*' || p[i]=='/' || p[i]=='%') //these are some binary operator { char n3[100]; //`n3` is for the final string after appending the expresstion. strcpy(n3,""); //initializing `n3` with `(` so that precedece is maintainted. char n2[100]; //`n2` is for the second `variable_name` POP(&s, n2); char n1[100]; //`n1` is for the first `variable_name` POP(&s, n1); strcat(n3,n2); // concatenating `n1` in `n3`. // every string ends with `\0`. strcat(n3,n1); size_t sz = strlen(n3); // storing length of `n3` in `sz` variable. n3[sz]=p[i]; // appending the operator in `n3` n3[sz+1]='\0'; //appending `n2` in `n3`. // ending the expression with `)` PUSH(&s,n3); // push this expression`n3` as `variable_name` in stack. } i--; }while(i>=0); // loop terminates when `\0` is scanned from `prefix`. char postfix[100]; POP(&s, postfix); printf("Postfix expression is : "); puts(postfix); } int main() { char p[100]; //`p` to store prefix expression. printf("Enter the prefix : "); scanf("%s", p); // scan prefix expression from user. prefix_to_postfix(p); }
tacrazymage/Data-Structures-and-Algorithms
warshall_algorithm.c
<reponame>tacrazymage/Data-Structures-and-Algorithms<gh_stars>0 #include <stdio.h> #include <stdlib.h> void run_warshall(int graph[][4]) { int num_iterations = 4 + 1; for(int i=0;i<num_iterations;i++) { } } int main() { int num_vertices = 4; int graph[4][4] = { {0 , 1 , 0 , 0}, {1 , 0 , 1 , 0}, {0 , 0 , 0 , 1}, {1 , 0 , 0 , 0} }; int set[4] = {-1}; run_warshall(graph); }
tacrazymage/Data-Structures-and-Algorithms
euclidean_gcd.c
#include <stdio.h> #include <stdlib.h> int gcd(int m, int n) { if(n == 0) return m; else if(n>m) return gcd(n,m); else return gcd(n, m%n); } int main() { int i = gcd(10,20); printf("%d", i); }
tacrazymage/Data-Structures-and-Algorithms
doubly_linked_list.c
<gh_stars>10-100 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> // Making the `size_t` keyword easier to interpret. typedef size_t size_type; // A pointer to the nodes in the list // is defined for easy use in functions. typedef struct Node* list_iterator; // A structure of `Node` used in the // doubly linked list for storing keys // and pointers to neighbouring Nodes. struct Node { int key; // Stores the value to be accessed by the user at runtime. // Pointers to the next and previous elements in the list. struct Node *prev, *next; }; // A function that creates and initializes the // doubly linked list. list_iterator create_doubly_linked_list(int key) { /* * Arguments: `key` (int) -> A value to be stored in the list. * Creates a doubly linked list. * Returns : `first` (list_iterator) -> A pointer to the first element of list. */ // Step 1: Allocate memory to store a variable of type `Node`. list_iterator first = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize key as provided by the user. first->key = key; // Step 3: First element in the list so it doesn't // have next and prev elements. first->prev = 0; first->next = 0; // Step 4: Return the pointer to allocated node. return first; } // Insert a node at the front of the linked list in O(1) time. list_iterator insert_in_front_of_the_doubly_linked_list(list_iterator first, int key) { /* * Argments: `first` (list_iterator) -> A pointer to the first element in the list. * Initialize the list using `create_doubly_linked_list()` * to get this pointer variable * `key` (int) -> The element to be stored in the list. * This function is used to insert a Node at the front of the * doubly linked list. The Node is intialized by the provided value * of the key and other attributes are initalized according to * the previously allocated nodes. * Returns: `new_node` (list_iterator) -> A pointer variable pointing at the new * Node inserted using this function. */ // Step 1: Allocate memory for the new node to be stored. list_iterator new_node = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize the key using the key provided by user. // Step 3: This node has the `next` member as `first` // which used to be the first Node in the list. // Step 4: Also, don't forget to add the newly allocated // node as the previous member of the `first` Node. // Step 5: The previous member is still `NULL`. new_node->key = key; new_node->next = first; first->prev = new_node; new_node->prev = 0; // Step 6: Return the newly allocated node which will act as the 'first' node in the list. return new_node; } // Insert a Node at the end of the linked list in O(1) time. list_iterator insert_in_end_of_the_doubly_linked_list(list_iterator last, int key) { /* * Argments: `last` (list_iterator) -> A pointer to the last element in the list. * `key` (int) -> The element to be stored in the list. * This function is used to insert a Node at the end of the * doubly linked list. The Node is intialized by the provided value * of the key and other attributes are initalized according to * the previously allocated nodes. * Returns: `new_node` (list_iterator) -> A pointer variable pointing at the new * Node inserted using this function. */ // Step 1: Allocate memory required to store the new node to be inserted in the list. list_iterator new_node = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize the key according to the value of key // provided by the user. // Step 3: The attribute `prev` will be a pointer to the last node // in the list. i.e. `last`. // Step 4: Don't forget to change the `next` attribute of the // node `last` to `new_node`. // Step 5: The next member of the list is still NULL. new_node->key = key; new_node->prev = last; last->next = new_node; new_node->next = 0; // Step 6: Return a pointer to the newly allocated element in the list. return new_node; } // Delete a Node from the end of a linked list in O(1) time. list_iterator delete_from_the_front_of_the_doubly_linked_list(list_iterator first) { /* * Arguments: `first` (list_iterator) -> A pointer to the first element in the list. * Deletes the first element in the linked list. * Returns: `second` (list_iterator) -> A pointer to second element in the list. */ // Step 1: Check if there is any other node present in the list. // If no node is present, delete the `first` pointer and // hence the whole linked list. // Return new linked list initialized by key -1. if(first->next == 0){ free(first);return create_doubly_linked_list(-1); } // Step 2: Create a pointer to the next element in the list. list_iterator second = first->next; // Step 3: Delete the `first` pointer pointing to the first element in the list. free(first); // Step 4: Update the `prev` attribute of the second node to NULL. second->prev = 0; // Step 5: Return thr second element. return second; } // Delete a Node from the end of the linked list in O(1) time. list_iterator delete_from_the_end_of_the_doubly_linked_list(list_iterator last) { /* * Arguments: `last` (list_iterator) -> A pointer to the last element in the list. * Deletes the last element in the linked list. * Returns: `previous` (list_iterator) -> A pointer to second element in the list. */ // Step 1: Check if there is any other node present in the list. // If no node is present, delete the `last` pointer and // hence the whole linked list. // Return new linked list initialized by key -1. if(last->prev == 0){ free(last);return create_doubly_linked_list(-1); } // Step 2: Create a pointer to the previous element in the list. list_iterator previous = last->prev; // Step 3: Delete the `last` pointer pointing to the last element in the list. free(last); // Step 4: Update the `next` attribute of the previous node to NULL. previous->next = 0; // Step 5: Return thr previous element. return previous; } // Deletes a element from the linked list in O(n) time. list_iterator delete_from_the_doubly_linked_list(list_iterator first, size_type key) { /* * Arguments: `first` (list_iterator) -> A pointer to the first element in the list. * `key` (size_type) -> A key to be deleted from the linked list. * Deletes the key from the linked list. */ // Step 1: Make a copy of `first` list_iterator. list_iterator it = first; // Step 2: Now, iterate through the list until no more elements are left. while(it != 0) { // Step 3: If the key is found then if(it->key == key){ // Case 1: It is the first element in the list. // So, delete it using `delete_from_the_front_of_the_doubly_linked_list`. if(it == first){ first = delete_from_the_front_of_the_doubly_linked_list(it); return first; // return the new first pointer to the list. } // Case 2: It is the last element in the list. // So, delete it using `delete_from_the_end_of_the_doubly_linked_list` if(it->next == 0){ delete_from_the_end_of_the_doubly_linked_list(it); return first; // return original first pointer. } // Case 3: It is a element somewhere in between the linked list. list_iterator temp1 = it->prev; // Make a copy of `prev` and `next` nodes of found node. list_iterator temp2 = it->next; // Now, the new `next` member of the node `temp1` is the `next` member of `it`. temp1->next = it->next; // Similarly, change the pointer `prev` of temp2 to be the next node of `it`. temp2->prev = it->prev; free(it); // Delete `it`. break; // terminate loop as we found the key. } // move ahead in the list. it = it->next; } return first; // return the new/original first pointer to the list. } // Searches a element with specified key list_iterator search_from_start_in_the_doubly_linked_list(list_iterator first, int key) { /* * Arguments: `first` (list_iterator) -> A pointer to the first node in the list. * `key` (int) -> A key to be retrived during search. * Search and returns a pointer to the node having the specified key. * Returns: `temp` (list_iterator) -> A pointer to the found node. */ // Make a copy of the first pointer to use // it during iteration. list_iterator current_node = first; // Iterate until key is found and the node pointer is not empty. while(current_node != 0 && current_node->key != key) current_node = current_node->next; // move ahead in the list if(current_node != 0) return current_node; // if the node is not empty return. list_iterator temp = 0; // else return a empty pointer. return temp; } list_iterator search_from_end_in_the_doubly_linked_list(list_iterator last, int key) { list_iterator current_node = last; while(current_node->key != key && current_node != 0) current_node = current_node->prev; if(current_node != 0) return current_node; list_iterator temp = 0; return temp; } int main() { // Creating a doubly linked list. list_iterator first = create_doubly_linked_list(10); // Insert 10 20 and 30 in the front of the doubly linked list. first = insert_in_front_of_the_doubly_linked_list(first, 10); first = insert_in_front_of_the_doubly_linked_list(first, 20); first = insert_in_front_of_the_doubly_linked_list(first, 30); // Print the list list_iterator it = first; while(it!=0){ printf("%d ", it->key); it = it->next; } }
tacrazymage/Data-Structures-and-Algorithms
Dynamic Programming/fibonacci.c
<filename>Dynamic Programming/fibonacci.c<gh_stars>10-100 /* * @author: <EMAIL> * Implement a program to find n'th term * in the fibonacci sequence through * dynamic programming. */ #include <stdio.h> #include <stdlib.h> // We take as arguments: `n` -> The integer representing the term // of the fibonacci sequence we want. // `memo` -> A array storing the already appeared // fibonacci term. int fibo(int n, int memo[]) { // If we have already came up with // the n'th fibonacci term return it. if(memo[n] != 0) return memo[n]; // Otherwise, if n is 0 or 1 then return 1. else if(n == 0 || n == 1) return 1; // Otherwise, get the result and store it in the memory. int result = fibo(n-1, memo) + fibo(n-2, memo); memo[n] = result; // store result at index `n` return result; // return the result. } int fibo_bottom_up(int n) { if(n == 0 || n == 1) return 1; int memo[n+1]; memo[0] = 0; memo[1] = 1; for(int i=2;i<=n;i++) { memo[i] = memo[i-1] + memo[i-2]; } return memo[n]; } int main() { int memo[11] = {0}; printf("%d\n", fibo(10, memo)); printf("%d\n", fibo_bottom_up(11)); }
tacrazymage/Data-Structures-and-Algorithms
stack_as_static_arrays.c
#include <stdio.h> // Handles standard input/output #include <errno.h> // Error Handling library #include <stdlib.h> // The maximum number of elements that can be stored in a stack. #define MAX 65535 // Structure of stack struct stack { // A integer pointing at the top of the stack. int top; // A array to hold the values of stack. int arr[MAX+1]; }s; // Deletes and returns the top element in a stack. int POP(struct stack* s) { // IMPLEMENT POP // Handle error when stack is empty. if(s->top == -1) perror("Stack Underflow!"); // Get a copy of value at the top of the stack // in a variable `element` that we are going to return. int element = s->arr[s->top]; // Initialize the value at the top of the stack again to 0. s->arr[s->top] = 0; // Decrease the value of `top` by 1. s->top--; // Finally, return `element`. return element; } // Adds a element onto the top of stack void PUSH(struct stack* s, int value) { // IMPLEMENT PUSH // Handle error in case the stack has reached its maximum limit `MAX`. if(s->top == MAX) perror("Stack Overflow!"); // Increase the value of `top` by 1. s->top++; // Insert element at the index `top`. s->arr[s->top] = value; } // Returns the i'th element from the top of the stack int PEEP(struct stack* s, int index) { // IMPLEMENT PEEP // Handle error if index is not valid if(index <= 0 || index > MAX) perror("index out of range!"); return s->arr[s->top - index]; // return the i'th element from the top. } void CHANGE(struct stack* s, int index, int new_value) { // IMPLEMENT CHANGE // Handle error in case of out of range access. if(index <= 0 || index > MAX) perror("index out of range!"); // Insert the new value at index `top-index`. s->arr[s->top - index] = new_value; } void PRINT_STACK(struct stack* s) { if(s->top == -1) perror("Nothing present in stack!"); for(int i=0;i<=s->top;i++){ printf("%d ", PEEP(s, s->top-i)); } printf("\n"); } int main() { struct stack s = {-1, 0}; char command; while(1) { printf("Enter command: "); scanf("%c", &command); fflush(stdout); fflush(stdin); if(command == 'i'){ printf("Enter the value to insert: "); int value; scanf("%d", &value); PUSH(&s, value); } else if(command == 'd'){ int deleted_element = POP(&s); printf("The element popped is: %d", deleted_element); } else if(command == 'p'){ printf("Enter the index at which you wnat to peep: "); int index; scanf("%d", &index); int peeped_element = PEEP(&s, index); printf("Peeped Element: ", peeped_element); } else if(command == 'c'){ printf("Enter the index you wnat to edit: "); int index; scanf("%d", &index); printf("Enter the new value: "); int new_value; scanf("%d", &new_value); CHANGE(&s, index, new_value); } else if(command == 's') PRINT_STACK(&s); else if(command == 'q') break; else perror("Command not found!"); } }
tacrazymage/Data-Structures-and-Algorithms
Graph Algorithms/depth_first_search.c
#include <stdio.h> #include <stdlib.h> #include "boilerplate.h" #define print printf #define scan scanf void DFS(vertex_iterator* graph, int nb_vertices, vertex_iterator source) { // graph = 1->2->3->4->5, source = 1 int currTime = 0, explored = 0; Stack* s = (Stack*)malloc(sizeof(Stack)); init_stack(s); while(1) { push(s, source); source->color = 'G'; source->start = ++currTime; while(s->empty != 1) { vertex_iterator v = pop(s); if(v->color == 'B') { v->end = ++currTime; print("Node with value %d fount at time %d and its exploration ended at time %d\n", v->value, v->start, v->end); } else push(s, v); list_iterator temp = v->adj_list; while(temp != 0) { if(temp->key->color == 'W') { temp->key->start = ++currTime; temp->key->parent = v; temp->key->color = 'G'; push(s, temp->key); } temp = temp->next; } v->color = 'B'; } explored = 1; for(int i=0;i<nb_vertices;i++) { if(graph[i]->color == 'W') { source = graph[i]; explored = 0; break; } } if(explored == 0) continue; free(s); break; } } int main(int argc, int argv[]) { int nb_vertices; print("Enter the number of vertices in your graph: "); scan("%d", &nb_vertices); vertex_iterator* graph = (vertex_iterator*)malloc(nb_vertices*sizeof(vertex_iterator)); print("Enter value of all the vertices: "); fflush(stdin); for(int i=0;i<nb_vertices;i++) { int temp; scan("%d", &temp); graph[i] = (vertex_iterator)malloc(sizeof(Vertex)); graph[i]->value = temp; graph[i]->color = 'W'; graph[i]->depth = -1; graph[i]->parent = 0; graph[i]->adj_list = 0; graph[i]->end = -1; graph[i]->start = -1; // print("Vertex added to graph\n"); } print("Enter the index of nodes in the adjecent list of vertex with value \n"); for(int i=0;i<nb_vertices;i++) { list_iterator templ = 0; int ind = 0; print("%d (terminate with `-1`): ", graph[i]->value); while(ind!=-1) { scan("%d", &ind); if(ind == -1) break; if(templ==0) templ = create_doubly_linked_list(graph[ind]); else templ = insert_in_front_of_the_doubly_linked_list(templ, graph[ind]); } graph[i]->adj_list = templ; fflush(stdin); } int index; print("Enter the source to run DFS on: "); scan("%d", &index); print("\n\n"); DFS(graph, nb_vertices, graph[index]); }
tacrazymage/Data-Structures-and-Algorithms
postfix_to_infix/text.c
<filename>postfix_to_infix/text.c #include<stdio.h> #include<string.h> #include<ctype.h> void main() { char c='w'; char r[100] = "tirht"; strcat(r,c); puts(r); }
tacrazymage/Data-Structures-and-Algorithms
Graph Algorithms/breadth_first_search.c
<reponame>tacrazymage/Data-Structures-and-Algorithms #include <stdio.h> #include <stdlib.h> #include "boilerplate.h" #define print printf #define scan scanf void BFS(vertex_iterator source) { Queue* q = (Queue*)malloc(sizeof(Queue)); initalize_queue(q, 10); source->color = 'G'; source->depth = 0; source->parent = 0; enqueue(q, source); while(q->front != -1) { vertex_iterator u = dequeue(q); list_iterator temp = u->adj_list; while(temp != 0) { if(temp->key->color == 'W') { // print("New vertex found at %x!\n", temp->key); temp->key->color = 'G'; temp->key->depth = u->depth + 1; temp->key->parent = u; enqueue(q, temp->key); } temp = temp->next; } u->color = 'B'; print("Node with value %d fount at depth %d\n", u->value, u->depth); } } int main(int argc, char *argv[]) { int nb_vertices; print("Enter the number of vertices in your graph: "); scan("%d", &nb_vertices); vertex_iterator* graph = (vertex_iterator*)malloc(nb_vertices*sizeof(vertex_iterator)); print("Enter value of all the vertices: "); fflush(stdin); for(int i=0;i<nb_vertices;i++) { int temp; scan("%d", &temp); graph[i] = (vertex_iterator)malloc(sizeof(Vertex)); graph[i]->value = temp; graph[i]->color = 'W'; graph[i]->depth = -1; graph[i]->parent = 0; graph[i]->adj_list = 0; graph[i]->end = -1; graph[i]->start = -1; // print("Vertex added to graph\n"); } print("Enter the index of nodes in the adjecent list of vertex with value \n"); for(int i=0;i<nb_vertices;i++) { list_iterator templ = 0; int ind = 0; print("%d (terminate with `-1`): ", graph[i]->value); while(ind!=-1) { scan("%d", &ind); if(ind == -1) break; if(templ==0) templ = create_doubly_linked_list(graph[ind]); else templ = insert_in_front_of_the_doubly_linked_list(templ, graph[ind]); } graph[i]->adj_list = templ; fflush(stdin); } int index; print("Enter the source to run BFS on: "); scan("%d", &index); print("\n\n"); BFS(graph[index]); }
tacrazymage/Data-Structures-and-Algorithms
direct_address_table.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10000 typedef size_t size_type; typedef struct Table* iterator; typedef const struct Table* const_iterator; struct Table { int key; char element[100]; }; int insert_in_dat(iterator t, int key, char element[]) { if(key < 0 || key >= MAX) return 1; else if(t[key].key != -1) return 2; struct Table temp = {key, element}; t[key] = temp; return 0; } int del_from_dat(iterator t, int key) { if(key < 0 || key >= MAX) return 1; t[key].key = -1; strcpy(t[key].element, ""); return 0; } int search_in_dat(iterator t, int key) { if(key < 0 || key >= MAX) return 0; else if(t[key].key == -1) return 0; return 1; } int main() { iterator slots = (iterator)malloc(MAX*sizeof(struct Table)); for(int i=0;i<MAX;i++){ slots[i].key = -1; strcpy(slots[i].element,""); } int error_code = 0; char command; while(!error_code) { printf("Enter command: "); fflush(stdout); scanf("%c", &command); fflush(stdin); if(command == 'i'){ printf("Enter the key and correseponding string you want to store in the table: "); int key; char element[100]; scanf("%d%s", &key, element); fflush(stdin); error_code = insert(slots, key, element); } else if(command == 'd'){ printf("Enter the key you want to delete: "); int key; scanf("%d", &key); error_code = del(slots, key); } else if(command == 's'){ printf("Enter the key you want to search: "); int key; scanf("%d", &key); int success = search(slots, key); if(success) printf("The element present at %d is %s\n", key, slots[key]); else printf("Key not found!\n"); } else if(command == 'q') break; } if(error_code == 1) printf("ERROR 1: Out of index access not allowed!\nTerminating Program...\n"); else if(error_code == 2) printf("ERROR 2: Entered key doesn't exist in the table!\nTerminating Program...\n"); }
tacrazymage/Data-Structures-and-Algorithms
infix_to_postfix/main.c
<gh_stars>0 #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX 65535 struct stack{ int top; char s_content[MAX+1]; }; void PUSH(struct stack *s, char value) { if(s->top==MAX) perror("Overflow"); s->top++; s->s_content[s->top]=value; } char POP(struct stack *s){ if(s->top==-1) perror("Underflow !!!"); char element = s->s_content[s->top]; s->s_content[s->top]=0; s->top--; return element; } int f(char a) { if(a=='(') return 9; if(isalpha(a)) return 7; if(a=='^') return 6; if(a=='*' || a=='/') return 3; if(a=='+' || a=='-') return 1; if(a==')' || a=='#') return 0; return -1000; } int g(char a) { if(isalpha(a)) return 8; if(a=='^') return 5; if(a=='*' || a=='/') return 4; if(a=='+' || a=='-') return 2; if(a==')' || a=='#') return -1; return 0; } int r(char a) { if(isalpha(a)) return 1; if(a=='+' || a=='-' || a=='*' || a=='/' || a=='^') return -1; if(a=='#') return 0; return -1; } void infix_to_postfix(char infix[]) { char postfix[500]; int rank=0; struct stack s = {-1,0}; int i=0,j=0; PUSH(&s,'#'); while(infix[i]!='#') { while(g(s.s_content[s.top]) >= f(infix[i])) { char temp= POP(&s); if(temp!='(' && temp!=')') { postfix[j++]=temp; rank+= r(temp); } } PUSH(&s,infix[i++]); } while(s.s_content[s.top] != '#') { char temp= POP(&s); if(temp != '(' && temp != ')') { postfix[j++]=temp; rank += r(temp); } } postfix[j]='\0'; printf("Postfix expression is : "); puts(postfix); } int main() { printf("Enter the expression :"); char infix[100]; gets(infix); strcat(infix, "#"); infix_to_postfix(infix); }
tacrazymage/Data-Structures-and-Algorithms
hash_tables.c
<filename>hash_tables.c /* * @author: tirthasheshpatel * @e-mail: <EMAIL> * Summary: Implemented hash tables and resolved * collisions using (primarily) chaining * and open addressing. */ // Including necessary libraries. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> // Defining `M` which is the number of slots // in our hash table. Because we extract a // 14-bit least significant bits of the hashed // key, the maximum size of the slots, hash // function would hash to, becomes 2^14. #define M 16385 // The constant A which is used to perform // hash by multiplication method is defined // as `PHI` (conjugate of the golden number) // as stated in Knuth(2003) and cited in the // book `Introduction to Algorithms` Section 11. #define PHI 0.6180339887 // Making the `size_t` keyword easier to interpret. typedef size_t size_type; // A pointer to the nodes in the list // is defined for easy use in functions. typedef struct Node* list_iterator; // A structure of `Node` used in the // doubly linked list for storing keys // and pointers to neighbouring Nodes. struct Node { int key; // Stores the value to be accessed by the user at runtime. // Pointers to the next and previous elements in the list. struct Node *prev, *next; }; // A function that creates and initializes the // doubly linked list. list_iterator create_doubly_linked_list(int key) { /* * Arguments: `key` (int) -> A value to be stored in the list. * Creates a doubly linked list. * Returns : `first` (list_iterator) -> A pointer to the first element of list. */ // Step 1: Allocate memory to store a variable of type `Node`. list_iterator first = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize key as provided by the user. first->key = key; // Step 3: First element in the list so doesn't // have next and prev elements. first->prev = 0; first->next = 0; // Step 4: Return the pointer to allocated node. return first; } // Insert a node at the front of the linked list in O(1) time. list_iterator insert_in_front_of_the_doubly_linked_list(list_iterator first, int key) { /* * Argments: `first` (list_iterator) -> A pointer to the first element in the list. * Initialize the list using `create_doubly_linked_list()` * to get this pointer variable * `key` (int) -> The element to be stored in the list. * This function is used to insert a Node at the front of the * doubly linked list. The Node is intialized by the provided value * of the key and other attributes are initalized according to * the previously allocated nodes. * Returns: `new_node` (list_iterator) -> A pointer variable pointing at the new * Node inserted using this function. */ // Step 1: Allocate memory for the new node to be stored. list_iterator new_node = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize the key using the key provided by user. // Step 3: This node has the `next` member as `first` // which used to be the first Node in the list. // Step 4: Also, don't forget to add the newly allocated // node as the previous member of the `first` Node. // Step 5: The previous member is still `NULL`. new_node->key = key; new_node->next = first; first->prev = new_node; new_node->prev = 0; // Step 6: Return the newly allocated node which will act as the 'first' node in the list. return new_node; } // Insert a Node at the end of the linked list in O(1) time. list_iterator insert_in_end_of_the_doubly_linked_list(list_iterator last, int key) { /* * Argments: `last` (list_iterator) -> A pointer to the last element in the list. * `key` (int) -> The element to be stored in the list. * This function is used to insert a Node at the end of the * doubly linked list. The Node is intialized by the provided value * of the key and other attributes are initalized according to * the previously allocated nodes. * Returns: `new_node` (list_iterator) -> A pointer variable pointing at the new * Node inserted using this function. */ // Step 1: Allocate memory required to store the new node to be inserted in the list. list_iterator new_node = (list_iterator)malloc(sizeof(struct Node)); // Step 2: Initialize the key according to the value of key // provided by the user. // Step 3: The attribute `prev` will be a pointer to the last node // in the list. i.e. `last`. // Step 4: Don't forget to change the `next` attribute of the // node `last` to `new_node`. // Step 5: The next member of the list is still NULL. new_node->key = key; new_node->prev = last; last->next = new_node; new_node->next = 0; // Step 6: Return a pointer to the newly allocated element in the list. return new_node; } // Delete a Node from the end of a linked list in O(1) time. list_iterator delete_from_the_front_of_the_doubly_linked_list(list_iterator first) { /* * Arguments: `first` (list_iterator) -> A pointer to the first element in the list. * Deletes the first element in the linked list. * Returns: `second` (list_iterator) -> A pointer to second element in the list. */ // Step 1: Check if there is any other node present in the list. // If no node is present, delete the `first` pointer and // hence the whole linked list. // Return new linked list initialized by key -1. if(first->next == 0){ free(first);return create_doubly_linked_list(-1); } // Step 2: Create a pointer to the next element in the list. list_iterator second = first->next; // Step 3: Delete the `first` pointer pointing to the first element in the list. free(first); // Step 4: Update the `prev` attribute of the second node to NULL. second->prev = 0; // Step 5: Return thr second element. return second; } // Delete a Node from the end of the linked list in O(1) time. list_iterator delete_from_the_end_of_the_doubly_linked_list(list_iterator last) { /* * Arguments: `last` (list_iterator) -> A pointer to the last element in the list. * Deletes the last element in the linked list. * Returns: `previous` (list_iterator) -> A pointer to second element in the list. */ // Step 1: Check if there is any other node present in the list. // If no node is present, delete the `last` pointer and // hence the whole linked list. // Return new linked list initialized by key -1. if(last->prev == 0){ free(last);return create_doubly_linked_list(-1); } // Step 2: Create a pointer to the previous element in the list. list_iterator previous = last->prev; // Step 3: Delete the `last` pointer pointing to the last element in the list. free(last); // Step 4: Update the `next` attribute of the previous node to NULL. previous->next = 0; // Step 5: Return thr previous element. return previous; } // Deletes a element from the linked list in O(n) time. list_iterator delete_from_the_doubly_linked_list(list_iterator first, size_type key) { /* * Arguments: `first` (list_iterator) -> A pointer to the first element in the list. * `key` (size_type) -> A key to be deleted from the linked list. * Deletes the key from the linked list. */ // Step 1: Make a copy of `first` list_iterator. list_iterator it = first; // Step 2: Now, iterate through the list until no more elements are left. while(it != 0) { // Step 3: If the key is found then if(it->key == key){ // Case 1: It is the first element in the list. // So, delete it using `delete_from_the_front_of_the_doubly_linked_list`. if(it == first){ first = delete_from_the_front_of_the_doubly_linked_list(it); return first; // return the new first pointer to the list. } // Case 2: It is the last element in the list. // So, delete it using `delete_from_the_end_of_the_doubly_linked_list` if(it->next == 0){ delete_from_the_end_of_the_doubly_linked_list(it); return first; // return original first pointer. } // Case 3: It is a element somewhere in between the linked list. list_iterator temp1 = it->prev; // Make a copy of `prev` and `next` nodes of found node. list_iterator temp2 = it->next; // Now, the new `next` member of the node `temp1` is the `next` member of `it`. temp1->next = it->next; // Similarly, change the pointer `prev` of temp2 to be the next node of `it`. temp2->prev = it->prev; free(it); // Delete `it`. break; // terminate loop as we found the key. } // move ahead in the list. it = it->next; } return first; // return the new/original first pointer to the list. } // Searches a element with specified key list_iterator search_from_start_in_the_doubly_linked_list(list_iterator first, int key) { /* * Arguments: `first` (list_iterator) -> A pointer to the first node in the list. * `key` (int) -> A key to be retrived during search. * Search and returns a pointer to the node having the specified key. * Returns: `temp` (list_iterator) -> A pointer to the found node. */ // Make a copy of the first pointer to use // it during iteration. list_iterator current_node = first; // Iterate until key is found and the node pointer is not empty. while(current_node != 0 && current_node->key != key) current_node = current_node->next; // move ahead in the list if(current_node != 0) return current_node; // if the node is not empty return. list_iterator temp = 0; // else return a empty pointer. return temp; } list_iterator search_from_end_in_the_doubly_linked_list(list_iterator last, int key) { list_iterator current_node = last; while(current_node->key != key && current_node != 0) current_node = current_node->prev; if(current_node != 0) return current_node; list_iterator temp = 0; return temp; } // A function to find the Hash Code of a integer key // using the division method. // h(k) = k modulo m; // where m is the size of the hash table. size_type hash_by_division_method(size_type key) { /* * Arguments: `key` (size_type) -> A integer key to be hashed. * Hashes the given key using the division method for hashing. * Returns: (size_type) -> Hashed key. */ return key%M; } // A function to find the hash code of the // key using multiplication method proposed // in the book `Introduction to algorithms`. size_type hash_by_multiplication_method(size_type key) { /* * Arguments: `key` (size_type) -> A integer key to be Hashed. * Hashes and returns the entered key using the multiplication method. * Returns : (size_type) -> 14-bit Hash Code of the given key. */ // Set the bit-width 32 because at the end // we are going to multiply two 32 bit integers // to get a 64 bit long integer. Using 64 bit // integer may lead to possible loss of data. long long w = 4294967296; // Bit-width w = 2^32 // Now, we have a constant A = PHI, that we // need to convert in the form ` s / w ` // such that `s` is the nearest integer that can // be represented as ` A * w `. As // `A = PHI`, we have `s = floor(PHI * w)`. // Then, we multiply the key with obtained `s` // => `l = key * s` // Now, we have `l = w * r1 + r0` where // `r0` is the fractional part of `l`. // We extract 14 most significant bits of `r0` // to get our 14 bit hash key. return ( ( ( (size_type)fmod((key*floor(PHI*w)),w) ) >> (32-14) ) ); } // A function to find Hash Code of the key // using linear probing. Used by hash tables // in which collision is resolved by open addressing. size_type open_address_linear_probing(size_type key, size_type probe) { /* * Arguments: `key` (size_type) -> Key to be hashed * `probe` (size_type) -> Probe number assigned to the key. * Hashes the provided key using Linear Probing method * used to resolve collisions in hash tables using * open addressing. The equation used to hash the key is: * `h(k) = ( h'(k) + probe ) modulo `M` where `k` = key * `h` = hash function, `h'` = other hash function, `M` = slots in the hash table * and `probe` = probe number of key `k`. * Returns: (size_type) -> Hash Code of key. */ return (hash_by_multiplication_method(key) + probe)%M; } // A function to find the hash code of a key // using Quadratic Probing. Used by hash tables // in which collision is resolved through // open addressing. size_type open_address_quadratic_probing(size_type key, size_type probe) { /* * Arguments: `key` (size_type) -> Key to be hashed. * `probe` (size_type) -> Probe number assigned to the key. * Hashes the provided key using Quadratic Probing method * used to resolve collisions in hash tables using * open addressing. The equation used to hash the key is: * `h(k) = ( h'(k) + a*(probe) + b*(probe^2)) modulo M` * where `M` = Slots in the table, `k` = Key to be hashed, * `h'` = hash function, `a` and `b` = arbitary constants, * `probe` = Probe number of key `k`. * Returns: (size_type) -> Hash Code of the key. */ return (hash_by_multiplication_method(key) + 4*probe + 5*probe*probe)%M; } // A function to find the hash of a key // using Double Hashing method used to // resolve the collisions in hash tables. size_type open_address_double_hashing(size_type key, size_type probe) { /* * Arguments: `key` (size_type) -> Key to be hashed. * `probe` (size_type) -> Probe number assigned to the key. * Hashes the provided key using two other hash functions * used to resolve collisions by providing the property of * almost random behaviour. It is used in hash tables * using Open Addressing to resolve collisions. * Returns: (size_type) -> Hash Code of the key. */ return ( hash_by_multiplication_method(key) + probe*hash_by_division_method(key) )%M; } // A function that inserts a key into the hash table in O(1) time. void insert_in_hash_table(list_iterator *table, size_type key) { /* * Arguments: `table` (list_iterator) -> A hash table with slots M. * `key` (size_type) -> A key to be stored in the table. * Stores the entered key into the hash table in O(1) time. * The hash table resolves collisions through `Chaining`. * So, the keys are stored in a doubly linked list. * Returns: - */ // Check if key to be stored is valid. if(key <= 0) return; // Find the 14-bit hash code of the key `key` using multiplication method. size_type hash = hash_by_multiplication_method(key); // The hash code of the key is now our new key or the // index where the original key is to be stored // in the hash tables. if(table[hash]->key == -1) // Check if the slot is empty { // If empty, store the key in the first node of the doubly linked list. table[hash]->key = key; table[hash]->next = 0; // No next and previous node is present. table[hash]->prev = 0; return; } // If the slot is not empty, add a node to the list and store the key there. table[hash] = insert_in_front_of_the_doubly_linked_list(table[hash], key); return; } // Delete a key from the slot of the table in a average-case time O(ALPHA) // where ALPHA = load factor = N/M. N = No of keys to be inserted, M = Slots present. void delete_from_hash_table(list_iterator *table, size_type key) { // Find the hash code of a key `key` using Multiplication Method. size_type hash = hash_by_multiplication_method(key); // Delete element from the doubly linked // list present at the hashed slot. // This function runs in linear time by first searching // for the key and deleting the found node if any. table[hash] = delete_from_the_doubly_linked_list(table[hash], key); return; } // Searches for a key in the hash table in linear time. list_iterator search_in_hash_table(list_iterator *table, size_type key) { /* * Arguments: `table` (list_iterator) -> An object of Hash Table. * `key` (size_type) -> A key to be stored in the hash table. * Hashes the key and searches for the original key in the hashed slot * using search function of doubly linked list. * Returns : `element` (list_iterator) -> The found node where the key is present. */ // Hash the key. size_type hash = hash_by_multiplication_method(key); // Search in the doubly linked list from the start. list_iterator element = search_from_start_in_the_doubly_linked_list(table[hash], key); return element; // return element if found otherwise return empty pointer. } int main() { int key = 123456; printf("%lu\n", hash_by_multiplication_method(key)); }
tacrazymage/Data-Structures-and-Algorithms
Dynamic Programming/rod_cutting_problem.c
<gh_stars>10-100 #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <math.h> #define max(a,b) (((a) > (b)) ? (a) : (b)) typedef struct pair { int x; int y; }Pair; int callbacks = 0; int cut_rod_top_down(int n, int rev[]) { callbacks++; if(n == 0) return 0; int r = INT_MIN; for(int i=0;i<n;i++) { r = max(r, rev[i] + cut_rod_top_down(n-i-1, rev)); } return r; } int memoized_cut_rod_top_down(int n, int rev[], int memo[]) { callbacks++; if(n == 0) return 0; else if(memo[n-1] != -1) { return memo[n-1]; } int r = INT_MIN; for(int i=0;i<n;i++) { r = max(r, rev[i] + memoized_cut_rod_top_down(n-i-1, rev, memo)); } memo[n-1] = r; return r; } int memoized_cut_rod_bottom_up(int n, int rev[]) { int memo[n+1]; memo[0] = 0; int r; for(int i=1;i<=n;i++) { r = INT_MIN; for(int j=1;j<=i;j++) { r = max(r, rev[j-1] + memo[i-j]); } memo[i] = r; } return memo[n]; } Pair extended_memoized_cut_rod_bottom_up(int n, int rev[]) { int memo[n+1]; int cuts[n+1]; Pair p = {-1,-1}; memo[0] = 0; int r; for(int i=1;i<=n;i++) { r = INT_MIN; for(int j=1;j<=i;j++) { if(r < rev[j-1] + memo[i-j]){ r = rev[j-1] + memo[i-j]; cuts[i] = j; } } memo[i] = r; } p.x = memo[n]; p.y = cuts[n]; return p; } int main() { int revenue[] = {1,5,8,9,10,17,17,20,24,30}; int n = 10; printf("Top-Down : %d\n", cut_rod_top_down(n,revenue)); printf("Callbacks : %d\n\n", callbacks); callbacks = 0; int memo[10]; for(int i=0;i<10;i++) memo[i] = -1; printf("Memoized top-down : %d\n", memoized_cut_rod_top_down(n,revenue, memo)); printf("Callbacks : %d\n\n", callbacks); printf("Memoized bottom-up: %d\n\n", memoized_cut_rod_bottom_up(n,revenue)); for(int i=0;i<=n;i++) { Pair p = extended_memoized_cut_rod_bottom_up(i, revenue); printf("Revenue: %d Optimum Cut: %d\n", p.x, p.y); } }
tacrazymage/Data-Structures-and-Algorithms
Greedy Algorithms/activity_selection_problem.c
#include <stdio.h> #include <stdlib.h> void recursive_activity_selector(int (*set)[2], int a[], int i, int n, int k) { int m = k+1; while(m < n && set[m][0] < set[k][1]) { m++; } if(m<n) { a[i++] = m+1; recursive_activity_selector(set, a, i, n, m); } } void greedy_activity_selector(int (*set)[2], int a[], int n) { recursive_activity_selector(set, a, 0, n, -1); } // void dynamic_activity_selector(int (*set)[2], int a[], int n) // { // int c[n][n]; // for(int i=0;i<n;i++) // { // c[i][i] = 0; // } // for(int i=0;i<n-1;i++) // { // for(int j=i+1;j<n;j++) // { // c[i][j]=0; // for(int k=i;k<=j;k++) // { // c[i][j] = max(c[i][j], c[i][k] + c[k][j] + 1); // } // } // } // printf("%d ", c[0][n-1]); // } int main() { int activities[][2] = { // {start, finish} {1,4}, {3,5}, {0,6}, {5,7}, {3,9}, {5,9}, {6,10}, {8,11}, {8,12}, {2,14}, {12,16} }; int *a = (int*)calloc(11,sizeof(int)); greedy_activity_selector(activities, a, 11); for(int i=0;i<11;i++) printf("%d ", a[i]); }
tacrazymage/Data-Structures-and-Algorithms
Dynamic Programming/matrix_chain_multiplication.c
<reponame>tacrazymage/Data-Structures-and-Algorithms #include <stdio.h> #include <stdlib.h> #include <limits.h> void print_param_of_matrix_chain(int (*s)[6],int i, int j, int n) { if(i == j) printf(" A[%d] ", i+1); else{ printf("( "); print_param_of_matrix_chain(s, i, s[i][j], n); print_param_of_matrix_chain(s, s[i][j]+1, j, n); printf(" )"); } } void matrix_chain_multiplication(int (*shape)[2], int n) { int nb_mul[n][n],div[n][n],temp=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { nb_mul[i][j] = 0; div[i][j] = 0; } } for(int l=1;l<=n;l++) { for(int i=0;i<n-l;i++) { int j = i+l; nb_mul[i][j] = INT_MAX; for(int k=i;k<j;k++) { temp = nb_mul[i][k]+nb_mul[k+1][j]+shape[i][0]*shape[j][1]*shape[k][1]; if(temp<nb_mul[i][j]) { nb_mul[i][j] = temp; div[i][j] = k; } } } } printf("Multiplication Matrix: [start][end][cut]nb_mul\n"); for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { printf("[%d][%d][%d]%d\n", i+1, j+1, div[i][j]+1, nb_mul[i][j]); } } printf("The optimal paranthesization is: "); print_param_of_matrix_chain(div,0,5,6); } int main() { int n = 6; int shapes[6][2] = { {30,35}, {35,15}, {15,5}, {5,10}, {10,20}, {20,25} }; matrix_chain_multiplication(shapes, 6); }
PlaymodesStudio/ofxOceanode_Osc
src/oscSender.h
<filename>src/oscSender.h<gh_stars>1-10 // // oscSender.h // Oceanode // // Created by <NAME> on 17/02/2021. // #ifndef oscSender_h #define oscSender_h #include "ofxOceanodeNodeModel.h" #include "ofxOsc.h" #include "ofxOceanodeOSCController.h" class oscSender : public ofxOceanodeNodeModel{ public: oscSender(string name, string config, shared_ptr<ofxOceanodeOSCController> _controller) : additionalName(name), configuration(config), controller(_controller), ofxOceanodeNodeModel("Osc Sender " + name){ controller->addSender(additionalName); }; void setup(){ string host = controller->addSender(additionalName); addParameter(oscHost.set("Host", host), ofxOceanodeParameterFlags_DisableSavePreset); addParameter(oscPort.set("Port", "11511")); sender.setup(oscHost, ofToInt(oscPort)); listeners.push(controller->hostEvents[additionalName].newListener([this](string &s){ oscHost = s; })); listeners.push(oscHost.newListener([this](string &s){ sender.setup(oscHost, ofToInt(oscPort)); })); listeners.push(oscPort.newListener([this](string &s){ sender.setup(oscHost, ofToInt(oscPort)); })); vector<string> splittedConfig = ofSplitString(configuration, ", "); for(string &s : splittedConfig){ vector<string> ss = ofSplitString(s, ":"); if(ss[0] == "f"){ ofParameter<float> f; addParameter(f.set(ss[1], ofToFloat(ss[2]), ofToFloat(ss[2]), ofToFloat(ss[3]))); listeners.push(f.newListener([this, f](float &f_){ if (!disable) { ofxOscMessage message; message.setAddress("/" + additionalName + "/" + f.getName()); message.addFloatArg(ofClamp(f_, f.getMin(), f.getMax())); sender.sendMessage(message); } })); }else if(ss[0] == "vf"){ ofParameter<vector<float>> vf; addParameter(vf.set(ss[1], vector<float>(1, ofToFloat(ss[2])), vector<float>(1, ofToFloat(ss[2])), vector<float>(1, ofToFloat(ss[3])))); listeners.push(vf.newListener([this, vf](vector<float> &vf_){ if (!disable) { ofxOscMessage message; message.setAddress("/" + additionalName + "/" + vf.getName()); for (auto f : vf_) { message.addFloatArg(ofClamp(f, vf.getMin()[0], vf.getMax()[0])); } sender.sendMessage(message); } })); } else if(ss[0] == "i"){ ofParameter<int> i; addParameter(i.set(ss[1], ofToInt(ss[2]), ofToInt(ss[2]), ofToInt(ss[3]))); listeners.push(i.newListener([this, i](int &i_){ if (!disable) { ofxOscMessage message; message.setAddress("/" + additionalName + "/" + i.getName()); message.addIntArg(ofClamp(i_, i.getMin(), i.getMax())); sender.sendMessage(message); } })); } } disable = false; } void presetWillBeLoaded() override { disable = true; } void presetHasLoaded() override { disable = false; for (int i = 0; i < getParameterGroup().size(); i++) { ofxOceanodeAbstractParameter &absParam = static_cast<ofxOceanodeAbstractParameter&>(getParameterGroup().get(i)); if (absParam.valueType() == typeid(float).name()) { auto tempCast = absParam.cast<float>().getParameter(); ofxOscMessage message; message.setAddress("/" + additionalName + "/" + tempCast.getName()); message.addFloatArg(ofClamp(tempCast, tempCast.getMin(), tempCast.getMax())); sender.sendMessage(message); } else if (absParam.valueType() == typeid(int).name()) { auto tempCast = absParam.cast<int>().getParameter(); ofxOscMessage message; message.setAddress("/" + additionalName + "/" + tempCast.getName()); message.addIntArg(ofClamp(tempCast, tempCast.getMin(), tempCast.getMax())); sender.sendMessage(message); } else if (absParam.valueType() == typeid(std::vector<float>).name()) { auto tempCast = absParam.cast<std::vector<float>>().getParameter(); ofxOscMessage message; message.setAddress("/" + additionalName + "/" + tempCast.getName()); for (auto f : tempCast.get()) { message.addFloatArg(ofClamp(f, tempCast.getMin()[0], tempCast.getMax()[0])); } sender.sendMessage(message); } } } private: string additionalName; string configuration; shared_ptr<ofxOceanodeOSCController> controller; ofxOscSender sender; ofParameter<string> oscHost; ofParameter<string> oscPort; ofEventListeners listeners; bool disable; }; #endif /* oscSender_h */
PlaymodesStudio/ofxOceanode_Osc
src/ofxOceanodeOSCController.h
<reponame>PlaymodesStudio/ofxOceanode_Osc // // ofxOceanodeOSCController.h // PLedNodes // // Created by <NAME> on 09/05/2018. // #ifndef ofxOceanodeOSCController_h #define ofxOceanodeOSCController_h #include "ofxOceanodeBaseController.h" class ofxOceanodeOSCController : public ofxOceanodeBaseController{ public: ofxOceanodeOSCController(std::shared_ptr<ofxOceanodeContainer> _container); ~ofxOceanodeOSCController(); void draw(); void save(); string addSender(string name); map<string, ofEvent<string>> hostEvents; private: std::shared_ptr<ofxOceanodeContainer> container; map<string, string> hosts; ofJson json; }; #endif /* ofxOceanodeOSCController_h */
parisiale/marionette-collective
lib/mcollective/vendor/json/ext/json/ext/generator/generator.c
#include "generator.h" #ifdef HAVE_RUBY_ENCODING_H static VALUE CEncoding_UTF_8; static ID i_encoding, i_encode; #endif static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject, mHash, mArray, mFixnum, mBignum, mFloat, mString, mString_Extend, mTrueClass, mFalseClass, mNilClass, eGeneratorError, eNestingError, CRegexp_MULTILINE, CJSON_SAFE_STATE_PROTOTYPE, i_SAFE_STATE_PROTOTYPE; static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before, i_object_nl, i_array_nl, i_max_nesting, i_allow_nan, i_ascii_only, i_quirks_mode, i_pack, i_unpack, i_create_id, i_extend, i_key_p, i_aref, i_send, i_respond_to_p, i_match, i_keys, i_depth, i_dup; /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* * Index into the table below with the first byte of a UTF-8 sequence to * get the number of trailing bytes that are supposed to follow it. * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is * left as-is for anyone who may want to do such conversion, which was * allowed in earlier algorithms. */ static const char trailingBytesForUTF8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; /* * Magic values subtracted from a buffer value during UTF8 conversion. * This table contains as many values as there might be trailing bytes * in a UTF-8 sequence. */ static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Utility routine to tell whether a sequence of bytes is legal UTF-8. * This must be called with the length pre-determined by the first byte. * If not calling this from ConvertUTF8to*, then the length can be set by: * length = trailingBytesForUTF8[*source]+1; * and the sequence is illegal right away if there aren't that many bytes * available. * If presented with a length > 4, this returns 0. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static unsigned char isLegalUTF8(const UTF8 *source, unsigned long length) { UTF8 a; const UTF8 *srcptr = source+length; switch (length) { default: return 0; /* Everything else falls through when "1"... */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; case 2: if ((a = (*--srcptr)) > 0xBF) return 0; switch (*source) { /* no fall-through in this inner switch */ case 0xE0: if (a < 0xA0) return 0; break; case 0xED: if (a > 0x9F) return 0; break; case 0xF0: if (a < 0x90) return 0; break; case 0xF4: if (a > 0x8F) return 0; break; default: if (a < 0x80) return 0; } case 1: if (*source >= 0x80 && *source < 0xC2) return 0; } if (*source > 0xF4) return 0; return 1; } /* Escapes the UTF16 character and stores the result in the buffer buf. */ static void unicode_escape(char *buf, UTF16 character) { const char *digits = "0123456789abcdef"; buf[2] = digits[character >> 12]; buf[3] = digits[(character >> 8) & 0xf]; buf[4] = digits[(character >> 4) & 0xf]; buf[5] = digits[character & 0xf]; } /* Escapes the UTF16 character and stores the result in the buffer buf, then * the buffer buf іs appended to the FBuffer buffer. */ static void unicode_escape_to_buffer(FBuffer *buffer, char buf[6], UTF16 character) { unicode_escape(buf, character); fbuffer_append(buffer, buf, 6); } /* Converts string to a JSON string in FBuffer buffer, where all but the ASCII * and control characters are JSON escaped. */ static void convert_UTF8_to_JSON_ASCII(FBuffer *buffer, VALUE string) { const UTF8 *source = (UTF8 *) RSTRING_PTR(string); const UTF8 *sourceEnd = source + RSTRING_LEN(string); char buf[6] = { '\\', 'u' }; while (source < sourceEnd) { UTF32 ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { rb_raise(rb_path2class("JSON::GeneratorError"), "partial character in source, but hit end"); } if (!isLegalUTF8(source, extraBytesToRead+1)) { rb_raise(rb_path2class("JSON::GeneratorError"), "source sequence is illegal/malformed utf-8"); } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { #if UNI_STRICT_CONVERSION source -= (extraBytesToRead+1); /* return to the illegal value itself */ rb_raise(rb_path2class("JSON::GeneratorError"), "source sequence is illegal/malformed utf-8"); #else unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR); #endif } else { /* normal case */ if (ch >= 0x20 && ch <= 0x7f) { switch (ch) { case '\\': fbuffer_append(buffer, "\\\\", 2); break; case '"': fbuffer_append(buffer, "\\\"", 2); break; default: fbuffer_append_char(buffer, (char)ch); break; } } else { switch (ch) { case '\n': fbuffer_append(buffer, "\\n", 2); break; case '\r': fbuffer_append(buffer, "\\r", 2); break; case '\t': fbuffer_append(buffer, "\\t", 2); break; case '\f': fbuffer_append(buffer, "\\f", 2); break; case '\b': fbuffer_append(buffer, "\\b", 2); break; default: unicode_escape_to_buffer(buffer, buf, (UTF16) ch); break; } } } } else if (ch > UNI_MAX_UTF16) { #if UNI_STRICT_CONVERSION source -= (extraBytesToRead+1); /* return to the start */ rb_raise(rb_path2class("JSON::GeneratorError"), "source sequence is illegal/malformed utf8"); #else unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR); #endif } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ ch -= halfBase; unicode_escape_to_buffer(buffer, buf, (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START)); unicode_escape_to_buffer(buffer, buf, (UTF16)((ch & halfMask) + UNI_SUR_LOW_START)); } } } /* Converts string to a JSON string in FBuffer buffer, where only the * characters required by the JSON standard are JSON escaped. The remaining * characters (should be UTF8) are just passed through and appended to the * result. */ static void convert_UTF8_to_JSON(FBuffer *buffer, VALUE string) { const char *ptr = RSTRING_PTR(string), *p; unsigned long len = RSTRING_LEN(string), start = 0, end = 0; const char *escape = NULL; int escape_len; unsigned char c; char buf[6] = { '\\', 'u' }; for (start = 0, end = 0; end < len;) { p = ptr + end; c = (unsigned char) *p; if (c < 0x20) { switch (c) { case '\n': escape = "\\n"; escape_len = 2; break; case '\r': escape = "\\r"; escape_len = 2; break; case '\t': escape = "\\t"; escape_len = 2; break; case '\f': escape = "\\f"; escape_len = 2; break; case '\b': escape = "\\b"; escape_len = 2; break; default: unicode_escape(buf, (UTF16) *p); escape = buf; escape_len = 6; break; } } else { switch (c) { case '\\': escape = "\\\\"; escape_len = 2; break; case '"': escape = "\\\""; escape_len = 2; break; default: end++; continue; break; } } fbuffer_append(buffer, ptr + start, end - start); fbuffer_append(buffer, escape, escape_len); start = ++end; escape = NULL; } fbuffer_append(buffer, ptr + start, end - start); } static char *fstrndup(const char *ptr, unsigned long len) { char *result; if (len <= 0) return NULL; result = ALLOC_N(char, len); memccpy(result, ptr, 0, len); return result; } /* fbuffer implementation */ static FBuffer *fbuffer_alloc() { FBuffer *fb = ALLOC(FBuffer); memset((void *) fb, 0, sizeof(FBuffer)); fb->initial_length = FBUFFER_INITIAL_LENGTH; return fb; } static FBuffer *fbuffer_alloc_with_length(unsigned long initial_length) { FBuffer *fb; assert(initial_length > 0); fb = ALLOC(FBuffer); memset((void *) fb, 0, sizeof(FBuffer)); fb->initial_length = initial_length; return fb; } static void fbuffer_free(FBuffer *fb) { if (fb->ptr) ruby_xfree(fb->ptr); ruby_xfree(fb); } static void fbuffer_clear(FBuffer *fb) { fb->len = 0; } static void fbuffer_inc_capa(FBuffer *fb, unsigned long requested) { unsigned long required; if (!fb->ptr) { fb->ptr = ALLOC_N(char, fb->initial_length); fb->capa = fb->initial_length; } for (required = fb->capa; requested > required - fb->len; required <<= 1); if (required > fb->capa) { REALLOC_N(fb->ptr, char, required); fb->capa = required; } } static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned long len) { if (len > 0) { fbuffer_inc_capa(fb, len); MEMCPY(fb->ptr + fb->len, newstr, char, len); fb->len += len; } } static void fbuffer_append_str(FBuffer *fb, VALUE str) { const char *newstr = StringValuePtr(str); unsigned long len = RSTRING_LEN(str); RB_GC_GUARD(str); fbuffer_append(fb, newstr, len); } static void fbuffer_append_char(FBuffer *fb, char newchr) { fbuffer_inc_capa(fb, 1); *(fb->ptr + fb->len) = newchr; fb->len++; } static void freverse(char *start, char *end) { char c; while (end > start) { c = *end, *end-- = *start, *start++ = c; } } static long fltoa(long number, char *buf) { static char digits[] = "0123456789"; long sign = number; char* tmp = buf; if (sign < 0) number = -number; do *tmp++ = digits[number % 10]; while (number /= 10); if (sign < 0) *tmp++ = '-'; freverse(buf, tmp - 1); return tmp - buf; } static void fbuffer_append_long(FBuffer *fb, long number) { char buf[20]; unsigned long len = fltoa(number, buf); fbuffer_append(fb, buf, len); } static FBuffer *fbuffer_dup(FBuffer *fb) { unsigned long len = fb->len; FBuffer *result; if (len > 0) { result = fbuffer_alloc_with_length(len); fbuffer_append(result, FBUFFER_PAIR(fb)); } else { result = fbuffer_alloc(); } return result; } /* * Document-module: JSON::Ext::Generator * * This is the JSON generator implemented as a C extension. It can be * configured to be used by setting * * JSON.generator = JSON::Ext::Generator * * with the method generator= in JSON. * */ /* * call-seq: to_json(state = nil) * * Returns a JSON string containing a JSON object, that is generated from * this Hash instance. * _state_ is a JSON::State object, that can also be used to configure the * produced JSON string output further. */ static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(object); } /* * call-seq: to_json(state = nil) * * Returns a JSON string containing a JSON array, that is generated from * this Array instance. * _state_ is a JSON::State object, that can also be used to configure the * produced JSON string output further. */ static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(array); } /* * call-seq: to_json(*) * * Returns a JSON string representation for this Integer number. */ static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(fixnum); } /* * call-seq: to_json(*) * * Returns a JSON string representation for this Integer number. */ static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(bignum); } /* * call-seq: to_json(*) * * Returns a JSON string representation for this Float number. */ static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(float); } /* * call-seq: String.included(modul) * * Extends _modul_ with the String::Extend module. */ static VALUE mString_included_s(VALUE self, VALUE modul) { VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend); return result; } /* * call-seq: to_json(*) * * This string should be encoded with UTF-8 A call to this method * returns a JSON string encoded with UTF16 big endian characters as * \u????. */ static VALUE mString_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(string); } /* * call-seq: to_json_raw_object() * * This method creates a raw object hash, that can be nested into * other data structures and will be generated as a raw string. This * method should be used, if you want to convert raw strings to JSON * instead of UTF-8 strings, e. g. binary data. */ static VALUE mString_to_json_raw_object(VALUE self) { VALUE ary; VALUE result = rb_hash_new(); rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self))); ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*")); rb_hash_aset(result, rb_str_new2("raw"), ary); return result; } /* * call-seq: to_json_raw(*args) * * This method creates a JSON text from the result of a call to * to_json_raw_object of this String. */ static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self) { VALUE obj = mString_to_json_raw_object(self); Check_Type(obj, T_HASH); return mHash_to_json(argc, argv, obj); } /* * call-seq: json_create(o) * * Raw Strings are JSON Objects (the raw bytes are stored in an array for the * key "raw"). The Ruby String can be created by this module method. */ static VALUE mString_Extend_json_create(VALUE self, VALUE o) { VALUE ary; Check_Type(o, T_HASH); ary = rb_hash_aref(o, rb_str_new2("raw")); return rb_funcall(ary, i_pack, 1, rb_str_new2("C*")); } /* * call-seq: to_json(*) * * Returns a JSON string for true: 'true'. */ static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(true); } /* * call-seq: to_json(*) * * Returns a JSON string for false: 'false'. */ static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(false); } /* * call-seq: to_json(*) * * Returns a JSON string for nil: 'null'. */ static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self) { GENERATE_JSON(null); } /* * call-seq: to_json(*) * * Converts this object to a string (calling #to_s), converts * it to a JSON string, and returns the result. This is a fallback, if no * special method #to_json was defined for some object. */ static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self) { VALUE state; VALUE string = rb_funcall(self, i_to_s, 0); rb_scan_args(argc, argv, "01", &state); Check_Type(string, T_STRING); state = cState_from_state_s(cState, state); return cState_partial_generate(state, string); } static void State_free(JSON_Generator_State *state) { if (state->indent) ruby_xfree(state->indent); if (state->space) ruby_xfree(state->space); if (state->space_before) ruby_xfree(state->space_before); if (state->object_nl) ruby_xfree(state->object_nl); if (state->array_nl) ruby_xfree(state->array_nl); if (state->array_delim) fbuffer_free(state->array_delim); if (state->object_delim) fbuffer_free(state->object_delim); if (state->object_delim2) fbuffer_free(state->object_delim2); ruby_xfree(state); } static JSON_Generator_State *State_allocate() { JSON_Generator_State *state = ALLOC(JSON_Generator_State); MEMZERO(state, JSON_Generator_State, 1); return state; } static VALUE cState_s_allocate(VALUE klass) { JSON_Generator_State *state = State_allocate(); return Data_Wrap_Struct(klass, NULL, State_free, state); } /* * call-seq: configure(opts) * * Configure this State instance with the Hash _opts_, and return * itself. */ static VALUE cState_configure(VALUE self, VALUE opts) { VALUE tmp; GET_STATE(self); tmp = rb_convert_type(opts, T_HASH, "Hash", "to_hash"); if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h"); if (NIL_P(tmp)) { rb_raise(rb_eArgError, "opts has to be hash like or convertable into a hash"); } opts = tmp; tmp = rb_hash_aref(opts, ID2SYM(i_indent)); if (RTEST(tmp)) { unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->indent = fstrndup(RSTRING_PTR(tmp), len); state->indent_len = len; } tmp = rb_hash_aref(opts, ID2SYM(i_space)); if (RTEST(tmp)) { unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->space = fstrndup(RSTRING_PTR(tmp), len); state->space_len = len; } tmp = rb_hash_aref(opts, ID2SYM(i_space_before)); if (RTEST(tmp)) { unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->space_before = fstrndup(RSTRING_PTR(tmp), len); state->space_before_len = len; } tmp = rb_hash_aref(opts, ID2SYM(i_array_nl)); if (RTEST(tmp)) { unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->array_nl = fstrndup(RSTRING_PTR(tmp), len); state->array_nl_len = len; } tmp = rb_hash_aref(opts, ID2SYM(i_object_nl)); if (RTEST(tmp)) { unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->object_nl = fstrndup(RSTRING_PTR(tmp), len); state->object_nl_len = len; } tmp = ID2SYM(i_max_nesting); state->max_nesting = 19; if (option_given_p(opts, tmp)) { VALUE max_nesting = rb_hash_aref(opts, tmp); if (RTEST(max_nesting)) { Check_Type(max_nesting, T_FIXNUM); state->max_nesting = FIX2LONG(max_nesting); } else { state->max_nesting = 0; } } tmp = ID2SYM(i_depth); state->depth = 0; if (option_given_p(opts, tmp)) { VALUE depth = rb_hash_aref(opts, tmp); if (RTEST(depth)) { Check_Type(depth, T_FIXNUM); state->depth = FIX2LONG(depth); } else { state->depth = 0; } } tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan)); state->allow_nan = RTEST(tmp); tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only)); state->ascii_only = RTEST(tmp); tmp = rb_hash_aref(opts, ID2SYM(i_quirks_mode)); state->quirks_mode = RTEST(tmp); return self; } /* * call-seq: to_h * * Returns the configuration instance variables as a hash, that can be * passed to the configure method. */ static VALUE cState_to_h(VALUE self) { VALUE result = rb_hash_new(); GET_STATE(self); rb_hash_aset(result, ID2SYM(i_indent), rb_str_new(state->indent, state->indent_len)); rb_hash_aset(result, ID2SYM(i_space), rb_str_new(state->space, state->space_len)); rb_hash_aset(result, ID2SYM(i_space_before), rb_str_new(state->space_before, state->space_before_len)); rb_hash_aset(result, ID2SYM(i_object_nl), rb_str_new(state->object_nl, state->object_nl_len)); rb_hash_aset(result, ID2SYM(i_array_nl), rb_str_new(state->array_nl, state->array_nl_len)); rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse); rb_hash_aset(result, ID2SYM(i_ascii_only), state->ascii_only ? Qtrue : Qfalse); rb_hash_aset(result, ID2SYM(i_quirks_mode), state->quirks_mode ? Qtrue : Qfalse); rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting)); rb_hash_aset(result, ID2SYM(i_depth), LONG2FIX(state->depth)); return result; } /* * call-seq: [](name) * * Return the value returned by method +name+. */ static VALUE cState_aref(VALUE self, VALUE name) { GET_STATE(self); if (RTEST(rb_funcall(self, i_respond_to_p, 1, name))) { return rb_funcall(self, i_send, 1, name); } else { return Qnil; } } static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { char *object_nl = state->object_nl; long object_nl_len = state->object_nl_len; char *indent = state->indent; long indent_len = state->indent_len; long max_nesting = state->max_nesting; char *delim = FBUFFER_PTR(state->object_delim); long delim_len = FBUFFER_LEN(state->object_delim); char *delim2 = FBUFFER_PTR(state->object_delim2); long delim2_len = FBUFFER_LEN(state->object_delim2); long depth = ++state->depth; int i, j; VALUE key, key_to_s, keys; if (max_nesting != 0 && depth > max_nesting) { fbuffer_free(buffer); rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth); } fbuffer_append_char(buffer, '{'); keys = rb_funcall(obj, i_keys, 0); for(i = 0; i < RARRAY_LEN(keys); i++) { if (i > 0) fbuffer_append(buffer, delim, delim_len); if (object_nl) { fbuffer_append(buffer, object_nl, object_nl_len); } if (indent) { for (j = 0; j < depth; j++) { fbuffer_append(buffer, indent, indent_len); } } key = rb_ary_entry(keys, i); key_to_s = rb_funcall(key, i_to_s, 0); Check_Type(key_to_s, T_STRING); generate_json(buffer, Vstate, state, key_to_s); fbuffer_append(buffer, delim2, delim2_len); generate_json(buffer, Vstate, state, rb_hash_aref(obj, key)); } depth = --state->depth; if (object_nl) { fbuffer_append(buffer, object_nl, object_nl_len); if (indent) { for (j = 0; j < depth; j++) { fbuffer_append(buffer, indent, indent_len); } } } fbuffer_append_char(buffer, '}'); } static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { char *array_nl = state->array_nl; long array_nl_len = state->array_nl_len; char *indent = state->indent; long indent_len = state->indent_len; long max_nesting = state->max_nesting; char *delim = FBUFFER_PTR(state->array_delim); long delim_len = FBUFFER_LEN(state->array_delim); long depth = ++state->depth; int i, j; if (max_nesting != 0 && depth > max_nesting) { fbuffer_free(buffer); rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth); } fbuffer_append_char(buffer, '['); if (array_nl) fbuffer_append(buffer, array_nl, array_nl_len); for(i = 0; i < RARRAY_LEN(obj); i++) { if (i > 0) fbuffer_append(buffer, delim, delim_len); if (indent) { for (j = 0; j < depth; j++) { fbuffer_append(buffer, indent, indent_len); } } generate_json(buffer, Vstate, state, rb_ary_entry(obj, i)); } state->depth = --depth; if (array_nl) { fbuffer_append(buffer, array_nl, array_nl_len); if (indent) { for (j = 0; j < depth; j++) { fbuffer_append(buffer, indent, indent_len); } } } fbuffer_append_char(buffer, ']'); } static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { fbuffer_append_char(buffer, '"'); #ifdef HAVE_RUBY_ENCODING_H obj = rb_funcall(obj, i_encode, 1, CEncoding_UTF_8); #endif if (state->ascii_only) { convert_UTF8_to_JSON_ASCII(buffer, obj); } else { convert_UTF8_to_JSON(buffer, obj); } fbuffer_append_char(buffer, '"'); } static void generate_json_null(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { fbuffer_append(buffer, "null", 4); } static void generate_json_false(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { fbuffer_append(buffer, "false", 5); } static void generate_json_true(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { fbuffer_append(buffer, "true", 4); } static void generate_json_fixnum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { fbuffer_append_long(buffer, FIX2LONG(obj)); } static void generate_json_bignum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { VALUE tmp = rb_funcall(obj, i_to_s, 0); fbuffer_append_str(buffer, tmp); } static void generate_json_float(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { double value = RFLOAT_VALUE(obj); char allow_nan = state->allow_nan; VALUE tmp = rb_funcall(obj, i_to_s, 0); if (!allow_nan) { if (isinf(value)) { fbuffer_free(buffer); rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); } else if (isnan(value)) { fbuffer_free(buffer); rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); } } fbuffer_append_str(buffer, tmp); } static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { VALUE tmp; VALUE klass = CLASS_OF(obj); if (klass == rb_cHash) { generate_json_object(buffer, Vstate, state, obj); } else if (klass == rb_cArray) { generate_json_array(buffer, Vstate, state, obj); } else if (klass == rb_cString) { generate_json_string(buffer, Vstate, state, obj); } else if (obj == Qnil) { generate_json_null(buffer, Vstate, state, obj); } else if (obj == Qfalse) { generate_json_false(buffer, Vstate, state, obj); } else if (obj == Qtrue) { generate_json_true(buffer, Vstate, state, obj); } else if (klass == rb_cFixnum) { generate_json_fixnum(buffer, Vstate, state, obj); } else if (klass == rb_cBignum) { generate_json_bignum(buffer, Vstate, state, obj); } else if (klass == rb_cFloat) { generate_json_float(buffer, Vstate, state, obj); } else if (rb_respond_to(obj, i_to_json)) { tmp = rb_funcall(obj, i_to_json, 1, Vstate); Check_Type(tmp, T_STRING); fbuffer_append_str(buffer, tmp); } else { tmp = rb_funcall(obj, i_to_s, 0); Check_Type(tmp, T_STRING); generate_json(buffer, Vstate, state, tmp); } } static FBuffer *cState_prepare_buffer(VALUE self) { FBuffer *buffer = fbuffer_alloc(); GET_STATE(self); if (state->object_delim) { fbuffer_clear(state->object_delim); } else { state->object_delim = fbuffer_alloc_with_length(16); } fbuffer_append_char(state->object_delim, ','); if (state->object_delim2) { fbuffer_clear(state->object_delim2); } else { state->object_delim2 = fbuffer_alloc_with_length(16); } fbuffer_append_char(state->object_delim2, ':'); if (state->space) fbuffer_append(state->object_delim2, state->space, state->space_len); if (state->array_delim) { fbuffer_clear(state->array_delim); } else { state->array_delim = fbuffer_alloc_with_length(16); } fbuffer_append_char(state->array_delim, ','); if (state->array_nl) fbuffer_append(state->array_delim, state->array_nl, state->array_nl_len); return buffer; } static VALUE fbuffer_to_s(FBuffer *fb) { VALUE result = rb_str_new(FBUFFER_PAIR(fb)); fbuffer_free(fb); FORCE_UTF8(result); return result; } static VALUE cState_partial_generate(VALUE self, VALUE obj) { FBuffer *buffer = cState_prepare_buffer(self); GET_STATE(self); generate_json(buffer, self, state, obj); return fbuffer_to_s(buffer); } /* * call-seq: generate(obj) * * Generates a valid JSON document from object +obj+ and returns the * result. If no valid JSON document can be created this method raises a * GeneratorError exception. */ static VALUE cState_generate(VALUE self, VALUE obj) { VALUE result = cState_partial_generate(self, obj); VALUE re, args[2]; GET_STATE(self); if (!state->quirks_mode) { args[0] = rb_str_new2("\\A\\s*(?:\\[.*\\]|\\{.*\\})\\s*\\Z"); args[1] = CRegexp_MULTILINE; re = rb_class_new_instance(2, args, rb_cRegexp); if (NIL_P(rb_funcall(re, i_match, 1, result))) { rb_raise(eGeneratorError, "only generation of JSON objects or arrays allowed"); } } return result; } /* * call-seq: new(opts = {}) * * Instantiates a new State object, configured by _opts_. * * _opts_ can have the following keys: * * * *indent*: a string used to indent levels (default: ''), * * *space*: a string that is put after, a : or , delimiter (default: ''), * * *space_before*: a string that is put before a : pair delimiter (default: ''), * * *object_nl*: a string that is put at the end of a JSON object (default: ''), * * *array_nl*: a string that is put at the end of a JSON array (default: ''), * * *allow_nan*: true if NaN, Infinity, and -Infinity should be * generated, otherwise an exception is thrown, if these values are * encountered. This options defaults to false. * * *quirks_mode*: Enables quirks_mode for parser, that is for example * generating single JSON values instead of documents is possible. */ static VALUE cState_initialize(int argc, VALUE *argv, VALUE self) { VALUE opts; GET_STATE(self); state->max_nesting = 19; rb_scan_args(argc, argv, "01", &opts); if (!NIL_P(opts)) cState_configure(self, opts); return self; } /* * call-seq: initialize_copy(orig) * * Initializes this object from orig if it to be duplicated/cloned and returns * it. */ static VALUE cState_init_copy(VALUE obj, VALUE orig) { JSON_Generator_State *objState, *origState; Data_Get_Struct(obj, JSON_Generator_State, objState); Data_Get_Struct(orig, JSON_Generator_State, origState); if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State"); MEMCPY(objState, origState, JSON_Generator_State, 1); objState->indent = fstrndup(origState->indent, origState->indent_len); objState->space = fstrndup(origState->space, origState->space_len); objState->space_before = fstrndup(origState->space_before, origState->space_before_len); objState->object_nl = fstrndup(origState->object_nl, origState->object_nl_len); objState->array_nl = fstrndup(origState->array_nl, origState->array_nl_len); if (origState->array_delim) objState->array_delim = fbuffer_dup(origState->array_delim); if (origState->object_delim) objState->object_delim = fbuffer_dup(origState->object_delim); if (origState->object_delim2) objState->object_delim2 = fbuffer_dup(origState->object_delim2); return obj; } /* * call-seq: from_state(opts) * * Creates a State object from _opts_, which ought to be Hash to create a * new State instance configured by _opts_, something else to create an * unconfigured instance. If _opts_ is a State object, it is just returned. */ static VALUE cState_from_state_s(VALUE self, VALUE opts) { if (rb_obj_is_kind_of(opts, self)) { return opts; } else if (rb_obj_is_kind_of(opts, rb_cHash)) { return rb_funcall(self, i_new, 1, opts); } else { if (NIL_P(CJSON_SAFE_STATE_PROTOTYPE)) { CJSON_SAFE_STATE_PROTOTYPE = rb_const_get(mJSON, i_SAFE_STATE_PROTOTYPE); } return rb_funcall(CJSON_SAFE_STATE_PROTOTYPE, i_dup, 0); } } /* * call-seq: indent() * * This string is used to indent levels in the JSON text. */ static VALUE cState_indent(VALUE self) { GET_STATE(self); return state->indent ? rb_str_new2(state->indent) : rb_str_new2(""); } /* * call-seq: indent=(indent) * * This string is used to indent levels in the JSON text. */ static VALUE cState_indent_set(VALUE self, VALUE indent) { unsigned long len; GET_STATE(self); Check_Type(indent, T_STRING); len = RSTRING_LEN(indent); if (len == 0) { if (state->indent) { ruby_xfree(state->indent); state->indent = NULL; state->indent_len = 0; } } else { if (state->indent) ruby_xfree(state->indent); state->indent = strdup(RSTRING_PTR(indent)); state->indent_len = len; } return Qnil; } /* * call-seq: space() * * This string is used to insert a space between the tokens in a JSON * string. */ static VALUE cState_space(VALUE self) { GET_STATE(self); return state->space ? rb_str_new2(state->space) : rb_str_new2(""); } /* * call-seq: space=(space) * * This string is used to insert a space between the tokens in a JSON * string. */ static VALUE cState_space_set(VALUE self, VALUE space) { unsigned long len; GET_STATE(self); Check_Type(space, T_STRING); len = RSTRING_LEN(space); if (len == 0) { if (state->space) { ruby_xfree(state->space); state->space = NULL; state->space_len = 0; } } else { if (state->space) ruby_xfree(state->space); state->space = strdup(RSTRING_PTR(space)); state->space_len = len; } return Qnil; } /* * call-seq: space_before() * * This string is used to insert a space before the ':' in JSON objects. */ static VALUE cState_space_before(VALUE self) { GET_STATE(self); return state->space_before ? rb_str_new2(state->space_before) : rb_str_new2(""); } /* * call-seq: space_before=(space_before) * * This string is used to insert a space before the ':' in JSON objects. */ static VALUE cState_space_before_set(VALUE self, VALUE space_before) { unsigned long len; GET_STATE(self); Check_Type(space_before, T_STRING); len = RSTRING_LEN(space_before); if (len == 0) { if (state->space_before) { ruby_xfree(state->space_before); state->space_before = NULL; state->space_before_len = 0; } } else { if (state->space_before) ruby_xfree(state->space_before); state->space_before = strdup(RSTRING_PTR(space_before)); state->space_before_len = len; } return Qnil; } /* * call-seq: object_nl() * * This string is put at the end of a line that holds a JSON object (or * Hash). */ static VALUE cState_object_nl(VALUE self) { GET_STATE(self); return state->object_nl ? rb_str_new2(state->object_nl) : rb_str_new2(""); } /* * call-seq: object_nl=(object_nl) * * This string is put at the end of a line that holds a JSON object (or * Hash). */ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl) { unsigned long len; GET_STATE(self); Check_Type(object_nl, T_STRING); len = RSTRING_LEN(object_nl); if (len == 0) { if (state->object_nl) { ruby_xfree(state->object_nl); state->object_nl = NULL; } } else { if (state->object_nl) ruby_xfree(state->object_nl); state->object_nl = strdup(RSTRING_PTR(object_nl)); state->object_nl_len = len; } return Qnil; } /* * call-seq: array_nl() * * This string is put at the end of a line that holds a JSON array. */ static VALUE cState_array_nl(VALUE self) { GET_STATE(self); return state->array_nl ? rb_str_new2(state->array_nl) : rb_str_new2(""); } /* * call-seq: array_nl=(array_nl) * * This string is put at the end of a line that holds a JSON array. */ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl) { unsigned long len; GET_STATE(self); Check_Type(array_nl, T_STRING); len = RSTRING_LEN(array_nl); if (len == 0) { if (state->array_nl) { ruby_xfree(state->array_nl); state->array_nl = NULL; } } else { if (state->array_nl) ruby_xfree(state->array_nl); state->array_nl = strdup(RSTRING_PTR(array_nl)); state->array_nl_len = len; } return Qnil; } /* * call-seq: check_circular? * * Returns true, if circular data structures should be checked, * otherwise returns false. */ static VALUE cState_check_circular_p(VALUE self) { GET_STATE(self); return state->max_nesting ? Qtrue : Qfalse; } /* * call-seq: max_nesting * * This integer returns the maximum level of data structure nesting in * the generated JSON, max_nesting = 0 if no maximum is checked. */ static VALUE cState_max_nesting(VALUE self) { GET_STATE(self); return LONG2FIX(state->max_nesting); } /* * call-seq: max_nesting=(depth) * * This sets the maximum level of data structure nesting in the generated JSON * to the integer depth, max_nesting = 0 if no maximum should be checked. */ static VALUE cState_max_nesting_set(VALUE self, VALUE depth) { GET_STATE(self); Check_Type(depth, T_FIXNUM); return state->max_nesting = FIX2LONG(depth); } /* * call-seq: allow_nan? * * Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise * returns false. */ static VALUE cState_allow_nan_p(VALUE self) { GET_STATE(self); return state->allow_nan ? Qtrue : Qfalse; } /* * call-seq: ascii_only? * * Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise * returns false. */ static VALUE cState_ascii_only_p(VALUE self) { GET_STATE(self); return state->ascii_only ? Qtrue : Qfalse; } /* * call-seq: quirks_mode? * * Returns true, if quirks mode is enabled. Otherwise returns false. */ static VALUE cState_quirks_mode_p(VALUE self) { GET_STATE(self); return state->quirks_mode ? Qtrue : Qfalse; } /* * call-seq: quirks_mode=(enable) * * If set to true, enables the quirks_mode mode. */ static VALUE cState_quirks_mode_set(VALUE self, VALUE enable) { GET_STATE(self); state->quirks_mode = RTEST(enable); return Qnil; } /* * call-seq: depth * * This integer returns the current depth of data structure nesting. */ static VALUE cState_depth(VALUE self) { GET_STATE(self); return LONG2FIX(state->depth); } /* * call-seq: depth=(depth) * * This sets the maximum level of data structure nesting in the generated JSON * to the integer depth, max_nesting = 0 if no maximum should be checked. */ static VALUE cState_depth_set(VALUE self, VALUE depth) { GET_STATE(self); Check_Type(depth, T_FIXNUM); return state->depth = FIX2LONG(depth); } /* * */ void Init_generator() { rb_require("json/common"); mJSON = rb_define_module("JSON"); mExt = rb_define_module_under(mJSON, "Ext"); mGenerator = rb_define_module_under(mExt, "Generator"); eGeneratorError = rb_path2class("JSON::GeneratorError"); eNestingError = rb_path2class("JSON::NestingError"); cState = rb_define_class_under(mGenerator, "State", rb_cObject); rb_define_alloc_func(cState, cState_s_allocate); rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1); rb_define_method(cState, "initialize", cState_initialize, -1); rb_define_method(cState, "initialize_copy", cState_init_copy, 1); rb_define_method(cState, "indent", cState_indent, 0); rb_define_method(cState, "indent=", cState_indent_set, 1); rb_define_method(cState, "space", cState_space, 0); rb_define_method(cState, "space=", cState_space_set, 1); rb_define_method(cState, "space_before", cState_space_before, 0); rb_define_method(cState, "space_before=", cState_space_before_set, 1); rb_define_method(cState, "object_nl", cState_object_nl, 0); rb_define_method(cState, "object_nl=", cState_object_nl_set, 1); rb_define_method(cState, "array_nl", cState_array_nl, 0); rb_define_method(cState, "array_nl=", cState_array_nl_set, 1); rb_define_method(cState, "max_nesting", cState_max_nesting, 0); rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1); rb_define_method(cState, "check_circular?", cState_check_circular_p, 0); rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0); rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0); rb_define_method(cState, "quirks_mode?", cState_quirks_mode_p, 0); rb_define_method(cState, "quirks_mode", cState_quirks_mode_p, 0); rb_define_method(cState, "quirks_mode=", cState_quirks_mode_set, 1); rb_define_method(cState, "depth", cState_depth, 0); rb_define_method(cState, "depth=", cState_depth_set, 1); rb_define_method(cState, "configure", cState_configure, 1); rb_define_alias(cState, "merge", "configure"); rb_define_method(cState, "to_h", cState_to_h, 0); rb_define_method(cState, "[]", cState_aref, 1); rb_define_method(cState, "generate", cState_generate, 1); mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods"); mObject = rb_define_module_under(mGeneratorMethods, "Object"); rb_define_method(mObject, "to_json", mObject_to_json, -1); mHash = rb_define_module_under(mGeneratorMethods, "Hash"); rb_define_method(mHash, "to_json", mHash_to_json, -1); mArray = rb_define_module_under(mGeneratorMethods, "Array"); rb_define_method(mArray, "to_json", mArray_to_json, -1); mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum"); rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1); mBignum = rb_define_module_under(mGeneratorMethods, "Bignum"); rb_define_method(mBignum, "to_json", mBignum_to_json, -1); mFloat = rb_define_module_under(mGeneratorMethods, "Float"); rb_define_method(mFloat, "to_json", mFloat_to_json, -1); mString = rb_define_module_under(mGeneratorMethods, "String"); rb_define_singleton_method(mString, "included", mString_included_s, 1); rb_define_method(mString, "to_json", mString_to_json, -1); rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1); rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0); mString_Extend = rb_define_module_under(mString, "Extend"); rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1); mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass"); rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1); mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass"); rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1); mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass"); rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1); CRegexp_MULTILINE = rb_const_get(rb_cRegexp, rb_intern("MULTILINE")); i_to_s = rb_intern("to_s"); i_to_json = rb_intern("to_json"); i_new = rb_intern("new"); i_indent = rb_intern("indent"); i_space = rb_intern("space"); i_space_before = rb_intern("space_before"); i_object_nl = rb_intern("object_nl"); i_array_nl = rb_intern("array_nl"); i_max_nesting = rb_intern("max_nesting"); i_allow_nan = rb_intern("allow_nan"); i_ascii_only = rb_intern("ascii_only"); i_quirks_mode = rb_intern("quirks_mode"); i_depth = rb_intern("depth"); i_pack = rb_intern("pack"); i_unpack = rb_intern("unpack"); i_create_id = rb_intern("create_id"); i_extend = rb_intern("extend"); i_key_p = rb_intern("key?"); i_aref = rb_intern("[]"); i_send = rb_intern("__send__"); i_respond_to_p = rb_intern("respond_to?"); i_match = rb_intern("match"); i_keys = rb_intern("keys"); i_dup = rb_intern("dup"); #ifdef HAVE_RUBY_ENCODING_H CEncoding_UTF_8 = rb_funcall(rb_path2class("Encoding"), rb_intern("find"), 1, rb_str_new2("utf-8")); i_encoding = rb_intern("encoding"); i_encode = rb_intern("encode"); #endif i_SAFE_STATE_PROTOTYPE = rb_intern("SAFE_STATE_PROTOTYPE"); CJSON_SAFE_STATE_PROTOTYPE = Qnil; }
brexocoin/brexocoin
src/chainparamsseeds.h
#ifndef BREXO_CHAINPARAMSSEEDS_H #define BREXO_CHAINPARAMSSEEDS_H /** * List of fixed seed nodes for the brexocoin network * AUTOGENERATED by contrib/seeds/generate-seeds.py * * Each line contains a 16-byte IPv6 address and a port. * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly. */ static SeedSpec6 pnSeed6_main[] = { {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x33,0x44,0x91,0x7d}, 5302}, {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x33,0x9e,0x4f,0x74}, 5302}, {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x33,0x0f,0x26,0xd6}, 5302}, {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x25,0x3b,0x30,0x3d}, 5302}, {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x5b,0x79,0x4a,0x0c}, 5302} }; static SeedSpec6 pnSeed6_test[] = { }; #endif // BREXO_CHAINPARAMSSEEDS_H
nequeo/sockets
NequeoSocketsEx/NequeoSocketsEx/NetworkUtils.h
/* * ofxNetworkUtils.h * * Created on: 25/09/2010 * Author: arturo */ #pragma once #include <cerrno> #include "Constants.h" #include "Utils.h" #ifdef TARGET_WIN32 #define ENOTCONN WSAENOTCONN #define EWOULDBLOCK WSAEWOULDBLOCK #define ENOBUFS WSAENOBUFS #define ECONNRESET WSAECONNRESET #define ESHUTDOWN WSAESHUTDOWN #define EAFNOSUPPORT WSAEAFNOSUPPORT #define EPROTONOSUPPORT WSAEPROTONOSUPPORT #define EINPROGRESS WSAEINPROGRESS #define EISCONN WSAEISCONN #define ENOTSOCK WSAENOTSOCK #define EOPNOTSUPP WSAEOPNOTSUPP #define ETIMEDOUT WSAETIMEDOUT #define EADDRNOTAVAIL WSAEADDRNOTAVAIL #define ECONNREFUSED WSAECONNREFUSED #define ENETUNREACH WSAENETUNREACH #define EADDRINUSE WSAEADDRINUSE #define EADDRINUSE WSAEADDRINUSE #define EALREADY WSAEALREADY #define ENOPROTOOPT WSAENOPROTOOPT #define EMSGSIZE WSAEMSGSIZE #define ECONNABORTED WSAECONNABORTED #endif #define ofxNetworkCheckError() ofxNetworkCheckErrno(__FILE__,ofToString(__LINE__)) inline int ofxNetworkCheckErrno(const string & file, const string & line){ #ifdef TARGET_WIN32 int err = WSAGetLastError(); #else int err = errno; #endif switch(err){ case 0: break; case EBADF: ofLogError("ofxNetwork") << file << ": " << line << " EBADF: invalid socket"; break; case ECONNRESET: ofLogError("ofxNetwork") << file << ": " << line << " ECONNRESET: connection closed by peer"; break; case EINTR: ofLogError("ofxNetwork") << file << ": " << line << " EINTR: receive interrupted by a signal, before any data available"; break; case ENOTCONN: ofLogError("ofxNetwork") << file << ": " << line << " ENOTCONN: trying to receive before establishing a connection"; break; case ENOTSOCK: ofLogError("ofxNetwork") << file << ": " << line << " ENOTSOCK: socket argument is not a socket"; break; case EOPNOTSUPP: ofLogError("ofxNetwork") << file << ": " << line << " EOPNOTSUPP: specified flags not valid for this socket"; break; case ETIMEDOUT: ofLogError("ofxNetwork") << file << ": " << line << " ETIMEDOUT: timeout"; break; case EIO: ofLogError("ofxNetwork") << file << ": " << line << " EIO: io error"; break; case ENOBUFS: ofLogError("ofxNetwork") << file << ": " << line << " ENOBUFS: insufficient buffers to complete the operation"; break; case ENOMEM: ofLogError("ofxNetwork") << file << ": " << line << " ENOMEM: insufficient memory to complete the request"; break; case EADDRNOTAVAIL: ofLogError("ofxNetwork") << file << ": " << line << " EADDRNOTAVAIL: the specified address is not available on the remote machine"; break; case EAFNOSUPPORT: ofLogError("ofxNetwork") << file << ": " << line << " EAFNOSUPPORT: the namespace of the addr is not supported by this socket"; break; case EISCONN: ofLogError("ofxNetwork") << file << ": " << line << " EISCONN: the socket is already connected"; break; case ECONNREFUSED: ofLogError("ofxNetwork") << file << ": " << line << " ECONNREFUSED: the server has actively refused to establish the connection"; break; case ENETUNREACH: ofLogError("ofxNetwork") << file << ": " << line << " ENETUNREACH: the network of the given addr isn't reachable from this host"; break; case EADDRINUSE: ofLogError("ofxNetwork") << file << ": " << line << " EADDRINUSE: the socket address of the given addr is already in use"; break; case EINPROGRESS: ofLogWarning("ofxNetwork") << file << ": " << line << " EINPROGRESS: the socket is non-blocking and the connection could not be established immediately"; break; case EALREADY: ofLogError("ofxNetwork") << file << ": " << line << " EALREADY: the socket is non-blocking and already has a pending connection in progress"; break; case ENOPROTOOPT: ofLogError("ofxNetwork") << file << ": " << line << " ENOPROTOOPT: the optname doesn't make sense for the given level"; break; case EPROTONOSUPPORT: ofLogError("ofxNetwork") << file << ": " << line << " EPROTONOSUPPORT: the protocol or style is not supported by the namespace specified"; break; case EMFILE: ofLogError("ofxNetwork") << file << ": " << line << " EMFILE: the process already has too many file descriptors open"; break; case ENFILE: ofLogError("ofxNetwork") << file << ": " << line << " ENFILE: the system already has too many file descriptors open"; break; case EACCES: ofLogError("ofxNetwork") << file << ": " << line << " EACCES: the process does not have the privilege to create a socket of the specified style or protocol"; break; case EMSGSIZE: ofLogError("ofxNetwork") << file << ": " << line << " EMSGSIZE: the socket type requires that the message be sent atomically, but the message is too large for this to be possible"; break; case EPIPE: ofLogError("ofxNetwork") << file << ": " << line << " EPIPE: this socket was connected but the connection is now broken"; break; case EINVAL: ofLogError("ofxNetwork") << file << ": " << line << " EINVAL: invalid argument"; break; case EAGAIN: //ofLogError("ofxNetwork") << file << ": " << line << " EAGAIN: try again"; break; #ifdef TARGET_WIN32 case WSAEWOULDBLOCK: // represents "resource temporarily unavailable", can be ignored break; #endif default: ofLogError("ofxNetwork") << file << ": " << line << " unknown error: " << err << " see errno.h for description of the error"; break; } return err; }
nequeo/sockets
NequeoSocketsEx/NequeoSocketsEx/Network.h
<reponame>nequeo/sockets<filename>NequeoSocketsEx/NequeoSocketsEx/Network.h #pragma once #include "TCPClient.h" #include "TCPManager.h" #include "TCPServer.h" #include "UDPManager.h"
2bbb/ofxMioAlpha
src/ofxMioAlphaInterface.h
// // ofxMioAlphaInterface.h // // Created by ISHII 2bit on 2014/06/06. // // #ifndef __ofxMioAlphaInterface__ #define __ofxMioAlphaInterface__ #include "ofMain.h" class ofxMioAlphaInterface { public: virtual void findDevice(const string &uuid, bool isInTarget) {}; virtual void receiveHeartRate(const string &uuid, int heartRate) = 0; virtual void updateConnectionState(const string &uuid, bool isConnected) = 0; }; #endif
2bbb/ofxMioAlpha
src/BluetoothManager.h
<gh_stars>1-10 // // ofxBluetoothManager.h // // Created by ISHII 2bit on 2014/02/01. // Copyright (c) 2014 buffer Renaiss co., ltd. All rights reserved. // #import <Foundation/Foundation.h> #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE # import <CoreBluetooth/CoreBluetooth.h> #elif TARGET_OS_MAC # import <IOBluetooth/IOBluetooth.h> #endif extern NSString * const BMBluetoothDeviceFoundNotification; extern NSString * const BMBluetoothUpdateValueNotification; extern NSString * const BMBluetoothConnectedNotification; extern NSString * const BMBluetoothDisconnectedNotification; extern NSString * const BMHeartRateBPMKey; extern NSString * const BMDeviceKey; extern NSString * const BMDeviceIsInTargetsKey; extern NSString * const BMLocalName; @interface BluetoothManager : NSObject < CBCentralManagerDelegate, CBPeripheralDelegate > { CBCentralManager *centralManager; __strong CBPeripheral *aPeripheral; NSMutableArray *targetUUIDs; NSMutableDictionary *peripherals; CBUUID *targetServiceCharacteristic; NSMutableArray *targetLocalNames; } + (BluetoothManager *)sharedManager; - (void)addTargetUUID:(NSString *)uuid; - (BOOL)scan; - (void)stopScan; - (void)disconnect; @end
2bbb/ofxMioAlpha
src/ofxMioAlphaBridge.h
// // ofxMioAlphaBridge.h // // Created by ISHII 2bit on 2014/06/06. // // #pragma once #import "ofxMioAlphaInterface.h" #import <Foundation/Foundation.h> @interface ofxMioAlphaBridge : NSObject { ofxMioAlphaInterface *interface; } - (instancetype)initWithInterface:(ofxMioAlphaInterface *)interface; @end
2bbb/ofxMioAlpha
example/ofApp.h
<reponame>2bbb/ofxMioAlpha #pragma once #include "ofMain.h" #include "ofxMioAlpha.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void exit() { mio.disconnect(); } private: ofxMioAlpha mio; bool bStartScan; vector<string> uuids; };
2bbb/ofxMioAlpha
src/ofxMioAlpha.h
<reponame>2bbb/ofxMioAlpha // // ofxMioAlpha.h // // Created by ISHII 2bit // #pragma once #include "ofxMioAlphaInterface.h" class ofxMioAlpha : public ofxMioAlphaInterface { public: ofxMioAlpha(); virtual ~ofxMioAlpha(); void setup(ofxMioAlphaInterface *interface = NULL); void addDeviceUUID(const string &uuid); bool startScan(); void stopScan(); void disconnect(); vector<int> getLatestHeartBeatsFromDevice(const string &uuid); bool isConnectedToDevice(const string &uuid) const; const vector<string> &getConnectedDeviceUUIDs() const; const vector<string> &getUnknownDeviceUUIDs() const; void findDevice(const string &uuid, bool isInTarget); void receiveHeartRate(const string &uuid, int heartRate); void updateConnectionState(const string &uuid, bool isConnected); private: map<string, bool> deviceConnectionInfos; map<string, vector<int> > latestHeartRates; vector<string> connectedDeviceUUIDs; vector<string> unknownDeviceUUIDs; ofxMioAlphaInterface *interface; void *bridge; };
Meru852/ecctools
modmath.c
<gh_stars>1-10 /* Developed by <NAME> email: <EMAIL> gcc -o keymath keymath.c -lgmp */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <gmp.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include "util.h" #include "gmpecc.h" #include "base58/libbase58.h" #include "rmd160/rmd160.h" #include "sha256/sha256.h" const char *version = "0.1.211009"; const char *EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char *EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char *EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char *EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; char *str_output = NULL; char *str_input = NULL; char *str_publickey_ptr = NULL; char str_publickey[132]; char str_rmd160[41]; char str_address[41]; mpz_t A,B,C; int FLAG_NUMBER = 0; mpz_t inversemultiplier,number; int main(int argc, char **argv) { char buffer_input[1024]; mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x , EC_constant_Gx, 16); mpz_init_set_str(G.y , EC_constant_Gy, 16); mpz_init_set_ui(A,0); mpz_init_set_ui(B,0); mpz_init_set_ui(C,0); mpz_init(number); mpz_init(inversemultiplier); if(argc < 4) { printf("Missing parameters\n"); exit(0); } mpz_set_str(A,argv[1],0); mpz_set_str(B,argv[3],0); switch(argv[2][0]) { case '+': mpz_add(C,A,B); mpz_mod(C,C,EC.n); break; case '-': mpz_sub(C,A,B); mpz_mod(C,C,EC.n); break; case '/': mpz_invert(inversemultiplier,B,EC.n); mpz_mul(C,A,inversemultiplier); mpz_mod(C,C,EC.n); break; case 'x': mpz_mul(C,A,B); mpz_mod(C,C,EC.n); break; } gmp_printf("Result: %Zx\n\n",C); }
Meru852/ecctools
calculatefromkey.c
/* develop by <NAME> Twitter: @albertobsd email: <EMAIL> */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <gmp.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include "util.h" #include "gmpecc.h" #include "base58/libbase58.h" #include "rmd160/rmd160.h" #include "sha256/sha256.h" const char *EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char *EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char *EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char *EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; void generate_publickey_and_address(struct Point *publickey,bool compress,char *dst_publickey,char *dst_address); int main(int argc, char **argv) { mpz_t key; struct Point publickey; char value[65]; char str_publickey[131]; char str_address[50]; char *hextemp,*aux,*public_address; mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x , EC_constant_Gx, 16); mpz_init_set_str(G.y , EC_constant_Gy, 16); init_doublingG(&G); mpz_init(publickey.x); mpz_init(publickey.y); mpz_init(key); if(argc != 2) { exit(0); } mpz_set_str(key,argv[1],16); Scalar_Multiplication(G,&publickey,key); gmp_printf("privatekey: %0.64Zx\n",key); generate_publickey_and_address(&publickey,true,str_publickey,str_address); printf("publickey compressed: %s\n",str_publickey); printf("public address compressed %s\n",str_address); generate_publickey_and_address(&publickey,false,str_publickey,str_address); printf("publickey uncompressed: %s\n",str_publickey); printf("public address uncompressed %s\n",str_address); return 0; } void generate_publickey_and_address(struct Point *publickey,bool compress,char *dst_publickey,char *dst_address) { char bin_publickey[65]; char bin_sha256[32]; char bin_digest[60]; size_t pubaddress_size = 50; memset(dst_address,0,50); memset(dst_publickey,0,131); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (dst_publickey,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(dst_publickey,67,"03%0.64Zx",publickey->x); } hexs2bin(dst_publickey,bin_publickey); sha256(bin_publickey, 33, bin_sha256); } else { gmp_snprintf(dst_publickey,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); hexs2bin(dst_publickey,bin_publickey); sha256(bin_publickey, 65, bin_sha256); } RMD160Data((const unsigned char*)bin_sha256,32, bin_digest+1); /* Firts byte 0, this is for the Address begining with 1.... */ bin_digest[0] = 0; /* Double sha256 checksum */ sha256(bin_digest, 21, bin_digest+21); sha256(bin_digest+21, 32, bin_digest+21); /* Get the address */ if(!b58enc(dst_address,&pubaddress_size,bin_digest,25)){ fprintf(stderr,"error b58enc\n"); } }
Meru852/ecctools
rehashaddress.c
<gh_stars>1-10 /* Developed by <NAME> email: <EMAIL> Generate N deterministic privatekeys, publickey and legacy address from a password or passphrase, after M rehash of the given password Examples: Generate 1 privatekey and his address after 0 rehashes: ./rehashaddress -p "3'W-CB7;>bRMzH<zyE5~Woh=_O>#eX" -n 1 -m 0 Generate 10 privatekeys and his address after 1 million of rehahes ./rehashaddress -p "}78~Et=jPQP5}MVVj2fc0X38{~I}?c" -n 10 -m 100000 Generate 5 privatekeys and his addrtess after 1337 rehash ./rehashaddress -p "JA,af>9oY2M~8ni0G=S.IKBMb)vNmt" -n 5 -m 1337 Miscellaneous Password: <PASSWORD> 0 rehashes is the sha256("secret") 1 rehashes is the sha256(sha256("secret")), in this case is the hash sha256 of the binary value of the sha256("secret") 2 rehashes is the sha256(sha256(sha256("secret"))).... and so on Please for "m" don't use those values 0 or 1 million or even 1337 use your own lucky number less than 2^31 around 2 billions Please for the password or passphrase use Complex password with more than 30 characters and don't use common passphrases in any language even for dead languages or fictional languages. And please dont forget your password I'm no responsable for any weak password or privateke use or generated by this code THIS SOFTWARE IS PROVIDED ``AS IS AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <gmp.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include "util.h" #include "gmpecc.h" #include "base58/libbase58.h" #include "rmd160/rmd160.h" #include "sha256/sha256.h" const char *EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char *EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char *EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char *EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; int FLAG_N = 0,FLAG_M = 0,FLAG_P = 0; void generate_straddress(struct Point *publickey,bool compress,char *dst); void generate_strrmd160(struct Point *publickey,bool compress,char *dst); void generate_strpublickey(struct Point *publickey,bool compress,char *dst); int main(int argc, char **argv) { struct Point publickey; mpz_t privatekey; int n,m,i,l; char bin_hash[32]; char str_hash[65]; char str_publickey[131]; char str_address[50]; char c; while ((c = getopt(argc, argv, "p:n:m:")) != -1) { switch(c) { case 'p': printf("[I] Password: %s\n",optarg); l = strlen(optarg); sha256(optarg, l, bin_hash); FLAG_P = 1; break; case 'n': n = (int) strtol(optarg,NULL,10); printf("[I] n: %i\n",n); FLAG_N = 1; break; case 'm': m = (int) strtol(optarg,NULL,10); printf("[I] m: %i\n",m); FLAG_M = 1; break; } } if(!(FLAG_P && FLAG_N && FLAG_M)) { fprintf(stderr,"[E] Missing parameter\n"); exit(0); } mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x , EC_constant_Gx, 16); mpz_init_set_str(G.y , EC_constant_Gy, 16); init_doublingG(&G); mpz_init(privatekey); mpz_init(publickey.y); mpz_init(publickey.x); i = 0; while(i < m ) { sha256(bin_hash, 32, bin_hash); i++; } i = 0; while(i < n ) { tohex_dst(bin_hash,32,str_hash); mpz_set_str(privatekey,str_hash,16); printf("Privatekey: %s\n",str_hash); Scalar_Multiplication(G,&publickey,privatekey); generate_strpublickey(&publickey,true,str_publickey); generate_straddress(&publickey,true,str_address); printf("Compress publickey: %s\n",str_publickey); printf("Compress address: %s\n",str_address); generate_strpublickey(&publickey,false,str_publickey); generate_straddress(&publickey,false,str_address); printf("Uncompress publickey: %s\n",str_publickey); printf("Uncompress address: %s\n",str_address); sha256(bin_hash, 32, bin_hash); i++; } } void generate_strpublickey(struct Point *publickey,bool compress,char *dst) { memset(dst,0,132); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (dst,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(dst,67,"03%0.64Zx",publickey->x); } } else { gmp_snprintf(dst,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); } } void generate_straddress(struct Point *publickey,bool compress,char *dst) { char str_publickey[131]; char bin_publickey[65]; char bin_sha256[32]; char bin_digest[60]; size_t pubaddress_size = 42; memset(dst,0,42); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (str_publickey,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(str_publickey,67,"03%0.64Zx",publickey->x); } hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 33, bin_sha256); } else { gmp_snprintf(str_publickey,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 65, bin_sha256); } RMD160Data((const unsigned char*)bin_sha256,32, bin_digest+1); /* Firts byte 0, this is for the Address begining with 1.... */ bin_digest[0] = 0; /* Double sha256 checksum */ sha256(bin_digest, 21, bin_digest+21); sha256(bin_digest+21, 32, bin_digest+21); /* Get the address */ if(!b58enc(dst,&pubaddress_size,bin_digest,25)){ fprintf(stderr,"error b58enc\n"); } }
Meru852/ecctools
keydivision.c
<reponame>Meru852/ecctools<gh_stars>1-10 /* Developed by <NAME> email: <EMAIL> gcc -o keydivision keydivision.c -lgmp */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <gmp.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include "util.h" #include "gmpecc.h" #include "base58/libbase58.h" #include "rmd160/rmd160.h" #include "sha256/sha256.h" const char *version = "0.1.211009"; const char *EC_constant_N = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"; const char *EC_constant_P = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"; const char *EC_constant_Gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const char *EC_constant_Gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"; const char *formats[3] = {"publickey","rmd160","address"}; const char *looks[2] = {"compress","uncompress"}; void showhelp(); void set_format(char *param); void set_look(char *param); void set_publickey(char *param); void set_divisor(char *param); void generate_straddress(struct Point *publickey,bool compress,char *dst); void generate_strrmd160(struct Point *publickey,bool compress,char *dst); void generate_strpublickey(struct Point *publickey,bool compress,char *dst); void Scalar_Multiplication_custom(struct Point P, struct Point *R, mpz_t m); char *str_output = NULL; char *str_input = NULL; char *str_publickey_ptr = NULL; char str_publickey[132]; char str_rmd160[41]; char str_address[41]; struct Point target_publickey,dst_publickey,temp_point; int FLAG_PUBLIC = 0; int FLAG_FORMART = 0; int FLAG_HIDECOMMENT = 0; int FLAG_LOOK = 0; int FLAG_MODE = 0; int FLAG_N; int FLAG_DIVISOR = 0; int FLAG_PUBLIC_FILE = 0; int N = 1,M; mpz_t divisor,inversemultiplier,base_key,sum_key,dst_key; gmp_randstate_t state; int main(int argc, char **argv) { char buffer_input[1024]; char *temp; FILE *OUTPUT,*INPUT; char c; int i = 0,entrar; mpz_init_set_str(EC.p, EC_constant_P, 16); mpz_init_set_str(EC.n, EC_constant_N, 16); mpz_init_set_str(G.x , EC_constant_Gx, 16); mpz_init_set_str(G.y , EC_constant_Gy, 16); init_doublingG(&G); mpz_init_set_ui(target_publickey.x,0); mpz_init_set_ui(target_publickey.y,0); mpz_init_set_ui(dst_publickey.x,0); mpz_init_set_ui(dst_publickey.y,0); mpz_init_set_ui(temp_point.x,0); mpz_init_set_ui(temp_point.y,0); while ((c = getopt(argc, argv, "hvxRd:n:i:o:p:r:f:l:")) != -1) { switch(c) { case 'd': set_divisor((char *)optarg); break; case 'x': FLAG_HIDECOMMENT = 1; break; case 'h': showhelp(); exit(0); break; case 'n': N = strtol((char *)optarg,NULL,10); if(N<= 0) { fprintf(stderr,"[E] invalid bit N number %s, setting default N = 1\n",optarg); N = 1; } FLAG_N = 1; break; case 'o': str_output = (char *)optarg; break; case 'i': FLAG_PUBLIC_FILE = 1; str_input = (char *)optarg; break; case 'p': str_publickey_ptr = optarg; FLAG_PUBLIC = 1; break; case 'v': printf("version %s\n",version); exit(0); break; case 'l': set_look((char *)optarg); break; case 'f': set_format((char *)optarg); break; } } if(FLAG_DIVISOR == 0 ) { mpz_init_set_ui(divisor,2); } mpz_init(inversemultiplier); mpz_invert(inversemultiplier,divisor,EC.n); gmp_printf("inversemultiplier : %Zx\n",inversemultiplier); if(str_output) { OUTPUT = fopen(str_output,"a"); if(OUTPUT == NULL) { fprintf(stderr,"can't opent file %s\n",str_output); OUTPUT = stdout; } } else { OUTPUT = stdout; } if( (FLAG_PUBLIC || FLAG_PUBLIC_FILE)) { if(FLAG_PUBLIC_FILE){ INPUT = fopen(str_input,"r"); if(INPUT == NULL) { fprintf(stderr,"Can't open the file %s\n",str_input); exit(0); } } entrar = 1; while(entrar) { if(FLAG_PUBLIC){ set_publickey(str_publickey_ptr); } else { temp = fgets(buffer_input,1024,INPUT); if(temp != buffer_input) { exit(0); } trim(buffer_input," \r\n\t"); set_publickey(buffer_input); } mpz_set(temp_point.x,target_publickey.x); mpz_set(temp_point.y,target_publickey.y); i = 0; while( i < N) { /* Magic occurs here */ Scalar_Multiplication_custom(temp_point, &dst_publickey,inversemultiplier); /*Here is the "division" in ECC a division is multiplation by the inverse of the divisor */ switch(FLAG_FORMART) { case 0: //Publickey generate_strpublickey(&dst_publickey,FLAG_LOOK == 0,str_publickey); fprintf(OUTPUT,"%s\n",str_publickey); break; case 1: //rmd160 generate_strrmd160(&dst_publickey,FLAG_LOOK == 0,str_rmd160); fprintf(OUTPUT,"%s\n",str_rmd160); break; case 2: //address generate_straddress(&target_publickey,FLAG_LOOK == 0,str_address); fprintf(OUTPUT,"%s\n",str_address); break; } mpz_set(temp_point.x,dst_publickey.x); mpz_set(temp_point.y,dst_publickey.y); i++; } if(FLAG_PUBLIC){ entrar = 0; } else { if(feof(INPUT)){ entrar = 0; } } } } else { fprintf(stderr,"Version: %s\n",version); fprintf(stderr,"[E] there are some missing parameter\n"); showhelp(); } /* Why we clean the variables if we are going to quit? */ mpz_clear(dst_publickey.x); mpz_clear(dst_publickey.y); mpz_clear(base_key); mpz_clear(sum_key); return 0; } void showhelp() { printf("\nUsage:\n-h\t\tshow this help\n"); printf("-d num\tNumber divisor\n"); printf("-f format\tOutput format <publickey, rmd160, address>. Default: publickey\n"); printf("-l look\t\tOutput <compress, uncompress>. Default: compress\n"); printf("-n num\tNumber of consecutive divisions. Default 1\n"); printf("-i file\t\tInput file, input file with public keys to be divided"); printf("-o file\t\tOutput file, if you omit this option the out will go to the standar output\n"); printf("-p key\t\tPublickey to be substracted compress or uncompress\n"); printf("Developed by albertobsd\n\n"); } void set_publickey(char *param) { char hexvalue[65]; char *dest; int len; len = strlen(param); dest = (char*) calloc(len+1,1); if(dest == NULL) { fprintf(stderr,"[E] Error calloc\n"); exit(0); } memset(hexvalue,0,65); memcpy(dest,param,len); trim(dest," \t\n\r"); len = strlen(dest); switch(len) { case 66: mpz_set_str(target_publickey.x,dest+2,16); break; case 130: memcpy(hexvalue,dest+2,64); mpz_set_str(target_publickey.x,hexvalue,16); memcpy(hexvalue,dest+66,64); mpz_set_str(target_publickey.y,hexvalue,16); break; } if(mpz_cmp_ui(target_publickey.y,0) == 0) { mpz_t mpz_aux,mpz_aux2,Ysquared; mpz_init(mpz_aux); mpz_init(mpz_aux2); mpz_init(Ysquared); mpz_pow_ui(mpz_aux,target_publickey.x,3); mpz_add_ui(mpz_aux2,mpz_aux,7); mpz_mod(Ysquared,mpz_aux2,EC.p); mpz_add_ui(mpz_aux,EC.p,1); mpz_fdiv_q_ui(mpz_aux2,mpz_aux,4); mpz_powm(target_publickey.y,Ysquared,mpz_aux2,EC.p); mpz_sub(mpz_aux, EC.p,target_publickey.y); switch(dest[1]) { case '2': if(mpz_tstbit(target_publickey.y, 0) == 1) { mpz_set(target_publickey.y,mpz_aux); } break; case '3': if(mpz_tstbit(target_publickey.y, 0) == 0) { mpz_set(target_publickey.y,mpz_aux); } break; default: fprintf(stderr,"[E] Some invalid bit in the publickey: %s\n",dest); exit(0); break; } mpz_clear(mpz_aux); mpz_clear(mpz_aux2); mpz_clear(Ysquared); } free(dest); } void set_format(char *param) { int index = indexOf(param,formats,3); if(index == -1) { fprintf(stderr,"[E] Unknow format: %s\n",param); } else { FLAG_FORMART = index; } } void set_look(char *param) { int index = indexOf(param,looks,2); if(index == -1) { fprintf(stderr,"[E] Unknow look: %s\n",param); } else { FLAG_LOOK = index; } } void set_divisor(char *param) { if(param[0] == '0' && param[0] == 'x'){ mpz_init_set_str(divisor,param,16); } else { mpz_init_set_str(divisor,param,16); } FLAG_DIVISOR = 1; } void generate_strpublickey(struct Point *publickey,bool compress,char *dst) { memset(dst,0,131); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (dst,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(dst,67,"03%0.64Zx",publickey->x); } } else { gmp_snprintf(dst,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); } } void generate_strrmd160(struct Point *publickey,bool compress,char *dst) { char str_publickey[131]; char bin_publickey[65]; char bin_sha256[32]; char bin_rmd160[20]; memset(dst,0,42); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (str_publickey,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(str_publickey,67,"03%0.64Zx",publickey->x); } hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 33, bin_sha256); } else { gmp_snprintf(str_publickey,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 65, bin_sha256); } RMD160Data((const unsigned char*)bin_sha256,32, bin_rmd160); tohex_dst(bin_rmd160,20,dst); } void generate_straddress(struct Point *publickey,bool compress,char *dst) { char str_publickey[131]; char bin_publickey[65]; char bin_sha256[32]; char bin_digest[60]; size_t pubaddress_size = 42; memset(dst,0,42); if(compress) { if(mpz_tstbit(publickey->y, 0) == 0) { // Even gmp_snprintf (str_publickey,67,"02%0.64Zx",publickey->x); } else { gmp_snprintf(str_publickey,67,"03%0.64Zx",publickey->x); } hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 33, bin_sha256); } else { gmp_snprintf(str_publickey,131,"04%0.64Zx%0.64Zx",publickey->x,publickey->y); hexs2bin(str_publickey,bin_publickey); sha256(bin_publickey, 65, bin_sha256); } RMD160Data((const unsigned char*)bin_sha256,32, bin_digest+1); /* Firts byte 0, this is for the Address begining with 1.... */ bin_digest[0] = 0; /* Double sha256 checksum */ sha256(bin_digest, 21, bin_digest+21); sha256(bin_digest+21, 32, bin_digest+21); /* Get the address */ if(!b58enc(dst,&pubaddress_size,bin_digest,25)){ fprintf(stderr,"error b58enc\n"); } } void Scalar_Multiplication_custom(struct Point P, struct Point *R, mpz_t m) { struct Point Q, T; long no_of_bits, loop; mpz_init(Q.x); mpz_init(Q.y); mpz_init(T.x); mpz_init(T.y); no_of_bits = mpz_sizeinbase(m, 2); mpz_set_ui(R->x, 0); mpz_set_ui(R->y, 0); if(mpz_cmp_ui(m, 0) != 0) { mpz_set(Q.x, P.x); mpz_set(Q.y, P.y); if(mpz_tstbit(m, 0) == 1){ mpz_set(R->x, P.x); mpz_set(R->y, P.y); } for(loop = 1; loop < no_of_bits; loop++) { Point_Doubling(&Q, &T); mpz_set(Q.x, T.x); mpz_set(Q.y, T.y); mpz_set(T.x, R->x); mpz_set(T.y, R->y); if(mpz_tstbit(m, loop)) Point_Addition(&T, &Q, R); } } mpz_clear(Q.x); mpz_clear(Q.y); mpz_clear(T.x); mpz_clear(T.y); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/knapsack.c
#include<stdio.h> int max (int a,int b) { if (a>b) return a; else return b; } void knapsack(int m,int n,int w[],int p[]) { int v[100][200],x[10],i,j,sum=0; for(i=0;i<=n;i++) v[i][0]=0; for(j=0;j<=m;j++) v[0][j]=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(j>=w[i]) v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]); else v[i][j]=v[i-1][j]; for(i=1;i<=n;i++) x[i]=0; i=n; j=m; while(i>0 && j>0) { if(v[i][j]!=v[i-1][j]) { x[i]=1; j=j-w[i]; } i--; } printf("\n the optional set of items are :\n"); for(i=1;i<=n;i++) { if(x[i]==1) { printf("%d \t ",i); sum=sum+p[i]; } } printf("\n total profit is %d",sum); } void main() { int w[10],p[10],m,n,j,i; printf("enter the number of items"); scanf("%d",&n); printf("enter the weights of the items \n "); for(i=1;i<=n;i++) scanf("%d",&w[i]); printf("enter profit of items \n"); for(i=1;i<=n;i++) scanf("%d",&p[i]); printf("enter capacity \n"); scanf("%d",&m); knapsack(m,n,w,p); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/nqueen.c
<reponame>mvnsia/4th_Sem_Ise<filename>4rth-Sem-Ise/DAA LAB/nqueen.c<gh_stars>0 #include <stdio.h> int N; int board[20][20]; int is_attack(int i,int j) { int k,l; for(k=0;k<N;k++) { if((board[i][k] == 1) || (board[k][j] == 1)) return 1; } for(k=0;k<N;k++) { for(l=0;l<N;l++) { if(((k+l) == (i+j)) || ((k-l) == (i-j))) { if(board[k][l] == 1) return 1; } } } return 0; } int N_queen(int n) { int i,j; if(n==0) return 1; for(i=0;i<N;i++) { for(j=0;j<N;j++) { if((!is_attack(i,j)) && (board[i][j]!=1)) { board[i][j] = 1; if(N_queen(n-1)==1) return 1; board[i][j] = 0; } } } return 0; } int main() { printf("Enter the value of N for NxN chessboard\n"); scanf("%d",&N); int i,j; for(i=0;i<N;i++) { for(j=0;j<N;j++) { board[i][j]=0; } } N_queen(N); for(i=0;i<N;i++) { for(j=0;j<N;j++) printf("%d\t",board[i][j]); printf("\n"); } }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/dijkstra.c
<gh_stars>0 #include<stdio.h> void dijkstra(int source,int cost[20][20],int visited[20],int d[20],int n) { int i,j,min,u,w; for(i=1;i<=n;i++) { visited[i]=0; d[i]=cost[source][i]; } visited[source]=1; d[source]=0; for(j=2;j<=n;j++) { min=111; for(i=1;i<=n;i++) { if(!visited[i]) { if(d[i]<min) { min=d[i]; u=i; } } } visited[u]=1; for(w=1;w<=n;w++) { if(cost[u][w]!=111&&visited[w]==0) { if(d[w]>cost[u][w]+d[u]) d[w]=cost[u][w]+d[u]; } } } } void main() { int n,i,j,visited[20],source,cost[20][20],d[20]; printf("Enter the number of vertices:\n"); scanf("%d",&n); printf("Enter the cost matrix:\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); printf("Enter the source node\n"); scanf("%d",&source); dijkstra(source,cost,visited,d,n); for(i=1;i<=n;i++) if(i!=source) printf("\nShortest path from %d to %d is %d ",source,i,d[i]); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/bubblesort.c
<gh_stars>0 #include<stdio.h> #include<time.h> void main() { int i,n,j,temp; int a[100000]; printf("enter the size of the array \n"); scanf("%d",&n); for(i=n;i>=1;i--) a[n-i]=i; clock_t start,end; double cpu_time; start=clock(); for(i=0;i<n;i++) { for(j=0;j<n-1-i;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } end=clock(); cpu_time=((double)(end-start))/CLOCKS_PER_SEC; printf("time is %f",cpu_time); for(i=0;i<n;i++) printf(" %d",a[i]); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/warshall.c
#include<stdio.h> void warshall(int r[10][10],int n) { int i,j,k; for(k=0;k<n;k++) for(i=0;i<n;i++) for(j=0;j<n;j++) r[i][j]=(r[i][j]|r[i][k]&r[k][j]); } int main() { int r[10][10],i,j,n; printf("Enter the number of vertices\n"); scanf("%d",&n); printf("Enter adjacency matrix \n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&r[i][j]); warshall(r,n); printf("Transitive closure is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d \t",r[i][j]); printf("\n"); } return 0; }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/prim.c
<reponame>mvnsia/4th_Sem_Ise<filename>4rth-Sem-Ise/DAA LAB/prim.c #include<stdio.h> int a,b,u,v,n,i,j,ne=1,source; int visited[20]={0},min,mincost=0,cost[20][20]; int main() { printf("Enter the number of nodes\n"); scanf("%d",&n); printf("Enter the cost matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } printf("Enter the source node\n"); scanf("%d",&source); visited[source]=1; while(ne<n) { for(i=1,min=999;i<=n;i++) for(j=1;j<=n;j++) if(cost[i][j]<min) if(visited[i]!=0) { min=cost[i][j]; a=u=i; b=v=j; } if(visited[u]==0 || visited[v]==0) { printf("Edge %d:(%d->%d) cost:%d\n",ne++,a,b,min); mincost+=min; visited[b]=1; } cost[a][b]=cost[b][a]=999; } printf("Minimum cost=%d\n",mincost); return 0; }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/kruskal.c
<gh_stars>0 #include<stdio.h> int ne=1,min_cost=0; void main() { int n,i,j,min,cost[20][20],a,u,b,v,parent[20]; printf("Number of vertices : \n "); scanf("%d",&n); printf("Enter the cost matrix \n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); for(i=1;i<=n;i++) parent[i]=0; printf("The edges of spanning tree are: \n "); while(ne<n) { min=111; for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(cost[i][j]<min) { min=cost[i][j]; a=u=i; b=v=j; } } while(parent[u]) u=parent[u]; while(parent[v]) v=parent[v]; if(u!=v) { printf(" \n Edge %d \t %d -> %d =%d \n",ne++,a,b,min); min_cost+=min; parent[v]=u; } printf("Testing \n "); cost[a][b]=cost[b][a]=111; } printf("Min cost is %d \n ",min_cost); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/selctionsort.c
<gh_stars>0 #include<stdio.h> #include<time.h> void main() { int i,n,j,min,temp; int a[10000]; printf("enter the size of the array \n"); scanf("%d",&n); for(i=n;i>=1;i--) a[n-i]=i; clock_t start,end; double cpu_time; start=clock(); for(i=0;i<=n-2;i++) { min=i; for(j=i+1;j<=n-1;j++) { if(a[j]<a[min]) min=j; } temp=a[min]; a[min]=a[i]; a[i]=temp; } end=clock(); cpu_time=((double)(end-start))/CLOCKS_PER_SEC; printf("time is %f",cpu_time); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/heapsort.c
<filename>4rth-Sem-Ise/DAA LAB/heapsort.c #include<stdio.h> #include<time.h> #include<math.h> int h[50]; void heapify(int h[],int n) { int i,j,n1,k,heap,v; n1=n; for(i=n/2;i>=1;i--) { k=i; v=h[k]; heap=0; while(!(heap)&&(2*k)<=n1) { j=2*k; if(j<n1) if(h[j]<h[j+1]) j=j+1; if(v>=h[j]) heap=1; else { h[k]=h[j]; k=j; } } h[k]=v; } } void main() { int i,n,size,t; printf("Enter the value of n \n"); scanf("%d",&n); printf("Enter the array elements \n"); for(i=1;i<=n;i++) scanf("%d",&h[i]); heapify(h,n); printf("Elements heapified \n"); for(i=1;i<=n;i++) printf("%d \t",h[i]); for(i=n;i>=1;i--) { t=h[1]; h[1]=h[i]; h[i]=t; size=i-1; heapify(h,size); } printf("ROtated elements are: \n"); for(i=1;i<=n;i++) printf("%d \t",h[i]); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/DFS.c
#include<stdio.h> int count =0; int dfs(int [20][20],int,int[20],int); void main() { int n,a[20][20],i,j,visited[20],source,visitedorder[20]; printf("Enter the no of vertices\n"); scanf("%d",&n); printf("Enter the adjacency matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); for(i=1;i<=n;i++) visited[i]=0; printf("Enter source node\n"); scanf("%d",&source); for(i=1;i<=n;i++) if(visited[i]==0) dfs(a,n,visited,i); for(i=1;i<=n;i++) { visitedorder[visited[i]]=i; } printf("DFS traversal= \n"); for(i=1;i<=n;i++) { printf("%c \t",visitedorder[i]+64); } } int dfs(int a[20][20],int n,int visited[20],int source) { count++; int v; visited[source]=count; for(v=1;v<=n;v++) { if(a[source][v]==1&&visited[v]==0) { dfs(a,n,visited,v); } } }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/mergesort.c
<filename>4rth-Sem-Ise/DAA LAB/mergesort.c<gh_stars>0 #include<stdio.h> #include<time.h> //char a[100]; int a[10000]; int i,j,l,h; void merge( int l,int mid,int h) { //char B[100]; int B[10000]; for(i=l;i<=h;i++) B[i]=a[i]; i=l; j=mid+1; int k=l; while(i<=mid&&j<=h) { if(B[i]<=B[j]) a[k++]=B[i++]; else a[k++]=B[j++]; } while(i<=mid) a[k++]=B[i++]; } void mergesort(int l,int h) { int mid; if(l<h) { mid=(l+h)/2; mergesort(l,mid); mergesort(mid+1,h); merge(l,mid,h); } } void main() { int n; printf("enter the size of the array \n"); scanf("%d",&n); printf("enter the elements to be sorted \n"); for(i=n;i>=1;i--) a[n-i]=i; //for(i=0;i<n;i++) //scanf("%s",&a[i]); clock_t start,end; double cpu_time; start=clock(); l=0; h=n-1; mergesort(l,h); //printf("elements are : \n "); //for(i=0;i<n;i++) //printf(" %c \n ",a[i]); end=clock(); cpu_time=((double)(end-start))/CLOCKS_PER_SEC; printf("time is %f",cpu_time); }
mvnsia/4th_Sem_Ise
4rth-Sem-Ise/DAA LAB/quicksort.c
<filename>4rth-Sem-Ise/DAA LAB/quicksort.c #include<stdio.h> #include<time.h> #include<stdlib.h> void swap(int* a,int* b) { int temp; temp=*a; *a=*b; *b=temp; } int Partition(int A[],int low,int high) { int temp,key=A[low],j=high,i=low+1; while(i<=j) { while(A[i]<=key)i++; while(A[j]>key)j--; if(i<j) swap(&A[i],&A[j]); } swap(&A[low],&A[j]); return j; } void QuickSort(int A[],int low,int high) { if(low<=high) { int pos=Partition(A,low,high); QuickSort(A,low,pos-1); QuickSort(A,pos+1,high); } } int main() { int i,j,n; clock_t start,end; printf("Enter the no. of elements: "); scanf("%d",&n); int A[n]; for(i=0;i<n;i++) A[i]=rand()%100; start=clock(); QuickSort(A,0,n-1); end=clock(); double timetaken=((double)(end-start))/CLOCKS_PER_SEC; /*for(i=0;i<n;i++) printf("%d\n",A[i]);*/ printf("Time taken=%lf",timetaken); return 0; }
shadyproject/xnuspy
module/el1/xnuspy_ctl/debug.c
<reponame>shadyproject/xnuspy #include <mach/mach.h> #include <stdbool.h> #include <stdint.h> #include "../../common/xnuspy_structs.h" #include "debug.h" #include "externs.h" #include "mem.h" void desc_freelist(void){ lck_rw_lock_shared(xnuspy_rw_lck); SPYDBG("[Freelist] "); if(STAILQ_EMPTY(&freelist)){ lck_rw_done(xnuspy_rw_lck); SPYDBG("Empty\n"); return; } SPYDBG("FRONT: "); struct stailq_entry *entry; STAILQ_FOREACH(entry, &freelist, link) SPYDBG("%#llx <- ", entry->elem); SPYDBG("\n"); lck_rw_done(xnuspy_rw_lck); } void desc_orphan_mapping(struct orphan_mapping *om){ if(!om){ SPYDBG("%s: NULL\n", __func__); return; } SPYDBG("This orphan mapping is at %#llx\n", om); SPYDBG("Mapping addr: %#llx\n", om->mapping_addr); SPYDBG("Mapping size: %#llx\n", om->mapping_size); SPYDBG("Mapping memory object: %#llx\n", om->memory_object); } /* XXX ONLY meant to be called from xnuspy_gc_thread, hence the lack * of locking. */ void desc_unmaplist(void){ SPYDBG("[Unmaplist] "); if(STAILQ_EMPTY(&unmaplist)){ SPYDBG("Empty\n"); return; } SPYDBG("FRONT: "); struct stailq_entry *entry; STAILQ_FOREACH(entry, &unmaplist, link) SPYDBG("%#llx <- ", entry->elem); SPYDBG("\n"); } void desc_usedlist(void){ lck_rw_lock_shared(xnuspy_rw_lck); SPYDBG("[Usedlist] "); if(STAILQ_EMPTY(&usedlist)){ lck_rw_done(xnuspy_rw_lck); SPYDBG("Empty\n"); return; } struct stailq_entry *entry; STAILQ_FOREACH(entry, &usedlist, link) SPYDBG("%#llx -> ", entry->elem); SPYDBG("\n"); lck_rw_done(xnuspy_rw_lck); } void desc_xnuspy_mapping_metadata(struct xnuspy_mapping_metadata *mm){ SPYDBG("Mapping metadata refcnt: %lld\n", mm->refcnt); SPYDBG("Owner: %d\n", mm->owner); SPYDBG("Memory object: %#llx\n", mm->memory_object); SPYDBG("Shared mapping addr/size: %#llx/%#llx\n", mm->mapping_addr, mm->mapping_size); SPYDBG("Death callback: "); if(mm->death_callback) SPYDBG("%#llx\n", mm->death_callback); else SPYDBG("none\n"); } void desc_xnuspy_tramp(struct xnuspy_tramp *t, uint32_t orig_tramp_len){ SPYDBG("This xnuspy_tramp is @ %#llx\n", (uint64_t)t); SPYDBG("Replacement: %#llx\n", t->replacement); SPYDBG("Replacement trampoline:\n"); for(int i=0; i<sizeof(t->tramp)/sizeof(t->tramp[0]); i++) SPYDBG("\ttramp[%d] %#x\n", i, t->tramp[i]); SPYDBG("Original trampoline:\n"); for(int i=0; i<orig_tramp_len; i++) SPYDBG("\ttramp[%d] %#x\n", i, t->orig[i]); if(!t->tramp_metadata) SPYDBG("NULL tramp metadata\n"); else{ SPYDBG("Hooked function: %#llx [unslid=%#llx]\n", t->tramp_metadata->hooked, t->tramp_metadata->hooked - kernel_slide); SPYDBG("Original instruction: %#x\n", t->tramp_metadata->orig_instr); } if(!t->mapping_metadata) SPYDBG("NULL mapping metadata\n"); else desc_xnuspy_mapping_metadata(t->mapping_metadata); }
shadyproject/xnuspy
module/el1/xnuspy_ctl/mem.c
#include <mach/mach.h> #include <stdbool.h> #include <stdint.h> #include <unistd.h> #include "externs.h" #include "pte.h" __attribute__ ((naked)) uint64_t kvtophys(uint64_t kaddr){ asm volatile("" "mrs x1, DAIF\n" "msr DAIFSet, #0xf\n" "at s1e1r, x0\n" "mrs x2, par_el1\n" "msr DAIF, x1\n" "tbnz x2, 0x0, 5f\n" "and x2, x2, 0xfffffffff000\n" "and x1, x0, 0x3fff\n" "orr x0, x2, x1\n" "b 3f\n" "5:\n" "mov x0, xzr\n" "3:\n" "ret\n" ); } __attribute__ ((naked)) uint64_t uvtophys(uint64_t kaddr){ asm volatile("" "mrs x1, DAIF\n" "msr DAIFSet, #0xf\n" "at s1e0r, x0\n" "mrs x2, par_el1\n" "msr DAIF, x1\n" "tbnz x2, 0x0, 5f\n" "and x2, x2, 0xfffffffff000\n" "and x1, x0, 0x3fff\n" "orr x0, x2, x1\n" "b 3f\n" "5:\n" "mov x0, xzr\n" "3:\n" "ret\n" ); } /* Write to static kernel memory, using bcopy_phys. * * Parameters: * dst: kernel virtual address of destination * buf: kernel virtual address of data * sz: how many bytes 'buf' is * * Returns: nothing */ void kwrite_static(void *dst, void *buf, size_t sz){ uint64_t dst_phys = kvtophys((uint64_t)dst); uint64_t buf_phys = kvtophys((uint64_t)buf); bcopy_phys(buf_phys, dst_phys, sz); } static int protect_common(uint64_t vaddr, uint64_t size, vm_prot_t prot, uint32_t el){ /* memory must be readable */ if(!(prot & VM_PROT_READ)) return 1; /* Round size up to the nearest page if not already a multiple of PAGE_SIZE */ if(size & 0xfff) size = (size + PAGE_SIZE) & ~(PAGE_SIZE - 1); uint64_t target_region_cur = vaddr & ~(PAGE_SIZE - 1); uint64_t target_region_end = (vaddr + size) & ~(PAGE_SIZE - 1); /* Determine the equivalent PTE protections of 'prot'. Assume caller only * wants read permissions. */ uint64_t new_pte_ap; if(el == 0) new_pte_ap = ARM_PTE_AP(AP_RORO); else new_pte_ap = ARM_PTE_AP(AP_RONA); if(prot & VM_PROT_WRITE){ if(el == 0) new_pte_ap = ARM_PTE_AP(AP_RWRW); else new_pte_ap = ARM_PTE_AP(AP_RWNA); } while(target_region_cur < target_region_end){ pte_t *ptep; if(el == 0) ptep = el0_ptep((void *)target_region_cur); else ptep = el1_ptep((void *)target_region_cur); pte_t new_pte = (*ptep & ~ARM_PTE_APMASK) | new_pte_ap; new_pte &= ~(ARM_PTE_NX | ARM_PTE_PNX); if(prot & VM_PROT_EXECUTE){ if(el == 0) new_pte |= ARM_PTE_PNX; else new_pte |= ARM_PTE_NX; } kwrite_static(ptep, &new_pte, sizeof(new_pte)); target_region_cur += PAGE_SIZE; } tlb_flush(); return 0; } /* Change protections of kernel memory at the page table level. * * Parameters: * kaddr: kernel virtual address of target * size: the number of bytes in the target region * prot: protections to apply * * Returns: * zero if successful, non-zero otherwise */ int kprotect(void *kaddr, uint64_t size, vm_prot_t prot){ return protect_common((uint64_t)kaddr, size, prot, 1); } /* Change protections of user memory at the page table level. * * Parameters: * uaddr: EL0 virtual address of target * size: the number of bytes in the target region * prot: protections to apply * * Returns: * zero if successful, non-zero otherwise */ int uprotect(void *uaddr, uint64_t size, vm_prot_t prot){ return protect_common((uint64_t)uaddr, size, prot, 0); } void kwrite_instr(uint64_t dst, uint32_t instr){ kprotect((void *)dst, sizeof(uint32_t), VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE); *(uint32_t *)dst = instr; asm volatile("dc cvau, %0" : : "r" (dst)); asm volatile("dsb ish"); asm volatile("ic ivau, %0" : : "r" (dst)); asm volatile("dsb ish"); asm volatile("isb sy"); kprotect((void *)dst, sizeof(uint32_t), VM_PROT_READ | VM_PROT_EXECUTE); } struct unifiedhdr { size_t allocsz; }; void *unified_kalloc(size_t sz){ struct unifiedhdr *hdr; size_t allocsz = sizeof(*hdr) + sz; if(iOS_version == iOS_13_x) hdr = kalloc_canblock(&allocsz, 0, NULL); else hdr = kalloc_external(allocsz); if(!hdr) return NULL; hdr->allocsz = allocsz; return hdr + 1; } void unified_kfree(void *ptr){ if(!ptr) return; /* future-proofing */ struct unifiedhdr *hdr = (struct unifiedhdr *)((uintptr_t)ptr - sizeof(*hdr)); if(iOS_version == iOS_13_x) kfree_addr(hdr); else kfree_ext(NULL, hdr, hdr->allocsz); }
shadyproject/xnuspy
module/preboot_hook.c
#include <mach-o/nlist.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <sys/sysctl.h> #include "common/asm.h" #include "common/asm_support.h" #include "common/common.h" #include "common/pongo.h" #include "common/xnuspy_structs.h" #include "el1/hook_system_check_sysctlbyname_hook_instrs.h" #include "el1/xnuspy_ctl_tramp_instrs.h" #include "pf/offsets.h" #include "pf/pf_common.h" static uint64_t g_xnuspy_ctl_addr = 0; /* address of start of __TEXT_EXEC in xnuspy_ctl image */ static uint64_t g_xnuspy_ctl_img_codestart = 0; /* how many bytes to we need to mark as executable inside xnuspy_ctl_tramp? */ static uint64_t g_xnuspy_ctl_img_codesz = 0; static uint64_t g_xnuspy_tramp_mem_addr = 0; static uint64_t g_xnuspy_tramp_mem_end = 0; /* Assume we're in range until we do the check */ static uint64_t g_hookme_in_range = 1; uint64_t *xnuspy_cache_base = NULL; #define WRITE_INSTR_TO_SCRATCH_SPACE(opcode) \ do { \ if(num_free_instrs < 2){ \ printf("xnuspy: ran out\n" \ " of executable scratch\n" \ " space in function %s\n", \ __func__); \ xnuspy_fatal_error(); \ } \ *scratch_space = (opcode); \ scratch_space++; \ num_free_instrs--; \ } while (0) \ #define XNUSPY_CACHE_WRITE(thing) \ do { \ *xnuspy_cache_cursor++ = (thing); \ } while (0) \ static struct xnuspy_ctl_kernel_symbol { const char *symbol; uint64_t *valp; } g_xnuspy_ctl_needed_symbols[] = { { "_allprocp", &g_allproc_addr }, { "_bcopy_phys", &g_bcopy_phys_addr }, { "_copyin", &g_copyin_addr }, { "_copyinstr", &g_copyinstr_addr }, { "_copyout", &g_copyout_addr }, { "_current_proc", &g_current_proc_addr }, { "_hookme_in_range", &g_hookme_in_range }, { "_iOS_version", &g_kern_version_major }, { "_IOSleep", &g_IOSleep_addr }, { "_ipc_port_release_send", &g_ipc_port_release_send_addr }, { "_kalloc_canblock", &g_kalloc_canblock_addr }, { "_kalloc_external", &g_kalloc_external_addr }, { "_kernel_mapp", &g_kernel_map_addr }, { "_kernel_slide", &kernel_slide }, { "_kernel_thread_start", &g_kernel_thread_start_addr }, { "_kfree_addr", &g_kfree_addr_addr }, { "_kfree_ext", &g_kfree_ext_addr }, { "_kprintf", &g_kprintf_addr }, { "_lck_grp_alloc_init", &g_lck_grp_alloc_init_addr }, { "_lck_grp_free", &g_lck_grp_free_addr }, { "_lck_mtx_unlock", &g_lck_mtx_unlock_addr }, { "_lck_rw_alloc_init", &g_lck_rw_alloc_init_addr }, { "_lck_rw_done", &g_lck_rw_done_addr }, { "_lck_rw_free", &g_lck_rw_free_addr }, { "_lck_rw_lock_exclusive", &g_lck_rw_lock_exclusive_addr }, { "_lck_rw_lock_shared", &g_lck_rw_lock_shared_addr }, { "_lck_rw_lock_shared_to_exclusive", &g_lck_rw_lock_shared_to_exclusive_addr }, { "__mach_make_memory_entry_64", &g_mach_make_memory_entry_64_addr }, { "_mach_vm_map_external", &g_mach_vm_map_external_addr }, { "_offsetof_struct_thread_map", &g_offsetof_struct_thread_map }, { "_phystokv", &g_phystokv_addr }, { "_proc_list_lock", &g_proc_list_lock_addr }, { "_proc_list_mlockp", &g_proc_list_mlock_addr }, { "_proc_pid", &g_proc_pid_addr }, { "_proc_ref_locked", &g_proc_ref_locked_addr }, { "_proc_rele_locked", &g_proc_rele_locked_addr }, { "_proc_uniqueid", &g_proc_uniqueid_addr }, { "_thread_deallocate", &g_thread_deallocate_addr }, { "__thread_terminate", &g_thread_terminate_addr }, { "__vm_deallocate", &g_vm_deallocate_addr }, { "_vm_map_unwire", &g_vm_map_unwire_addr }, { "_vm_map_wire_external", &g_vm_map_wire_external_addr }, { "_xnuspy_tramp_mem", &g_xnuspy_tramp_mem_addr }, { "_xnuspy_tramp_mem_end", &g_xnuspy_tramp_mem_end }, }; static void anything_missing(void){ static int printed_err_hdr = 0; #define chk(expression, msg) \ do { \ if(expression){ \ if(!printed_err_hdr){ \ printf("xnuspy: error(s) before\n" \ " we continue:\n"); \ printed_err_hdr = 1; \ } \ printf(" "msg); \ } \ } while (0) \ chk(!g_sysent_addr, "sysent not found\n"); if(g_kern_version_major == iOS_13_x){ chk(!g_kalloc_canblock_addr, "kalloc_canblock not found\n"); chk(!g_kfree_addr_addr, "kfree_addr not found\n"); } else{ chk(!g_kalloc_external_addr, "kalloc_external not found\n"); chk(!g_kfree_ext_addr, "kfree_ext not found\n"); } chk(!g_sysctl__kern_children_addr, "sysctl__kern_children\n" " not found\n"); chk(!g_sysctl_register_oid_addr, "sysctl_register_oid not found\n"); chk(!g_sysctl_handle_long_addr, "sysctl_handle_long not found\n"); chk(!g_name2oid_addr, "name2oid not found\n"); chk(!g_sysctl_geometry_lock_addr, "sysctl_geometry_lock not found\n"); chk(!g_lck_rw_done_addr, "lck_rw_done not found\n"); chk(!g_h_s_c_sbn_branch_addr, "did not find hscsbn branch addr\n"); chk(!g_h_s_c_sbn_epilogue_addr, "hscsbn epilogue not found\n"); chk(!g_lck_grp_alloc_init_addr, "lck_grp_alloc_init not found\n"); chk(!g_lck_rw_alloc_init_addr, "lck_rw_alloc_init not found\n"); chk(!g_exec_scratch_space_addr, "unused executable code not found\n"); chk(!g_bcopy_phys_addr, "bcopy_phys not found\n"); chk(!g_phystokv_addr, "phystokv not found\n"); chk(!g_copyin_addr, "copyin not found\n"); chk(!g_copyout_addr, "copyout not found\n"); chk(!g_IOSleep_addr, "IOSleep not found\n"); chk(!g_kprintf_addr, "kprintf not found\n"); chk(!g_vm_map_unwire_addr, "vm_map_unwire not found\n"); chk(!g_vm_deallocate_addr, "vm_deallocate not found\n"); chk(!g_kernel_map_addr, "kernel_map not found\n"); chk(!g_kernel_thread_start_addr, "kernel_thread_start not found\n"); chk(!g_thread_deallocate_addr, "thread_deallocate not found\n"); chk(!g_mach_make_memory_entry_64_addr, "mach_make_memory_entry_64 not found\n"); chk(!g_offsetof_struct_thread_map, "offsetof(struct thread, map) not found\n"); chk(!g_current_proc_addr, "current_proc not found\n"); chk(!g_proc_list_lock_addr, "proc_list_lock not found\n"); chk(!g_proc_ref_locked_addr, "proc_ref_locked not found\n"); chk(!g_proc_list_mlock_addr, "address of proc_list_mlock not found\n"); chk(!g_lck_mtx_unlock_addr, "lck_mtx_unlock not found\n"); chk(!g_proc_rele_locked_addr, "proc_rele_locked not found\n"); chk(!g_proc_uniqueid_addr, "proc_uniqueid not found\n"); chk(!g_proc_pid_addr, "proc_pid not found\n"); chk(!g_allproc_addr, "address of allproc not found\n"); chk(!g_lck_rw_lock_shared_addr, "lck_rw_lock_shared not found\n"); chk(!g_lck_rw_lock_shared_to_exclusive_addr, "lck_rw_lock_shared_to_exclusive not found\n"); chk(!g_lck_rw_lock_exclusive_addr, "lck_rw_lock_exclusive not found\n"); chk(!g_vm_map_wire_external_addr, "vm_map_wire_external not found\n"); chk(!g_mach_vm_map_external_addr, "mach_vm_map_external not found\n"); chk(!g_ipc_port_release_send_addr, "ipc_port_release_send not found\n"); chk(!g_lck_rw_free_addr, "lck_rw_free not found\n"); chk(!g_lck_grp_free_addr, "lck_grp_free not found\n"); chk(!g_patched_doprnt_hide_pointers, "doprnt_hide_pointers wasn't patched\n"); chk(!g_copyinstr_addr, "copyinstr not found\n"); chk(!g_thread_terminate_addr, "thread_terminate not found\n"); /* Specific to A10+. On A9(x), we don't need to keep TCR_EL1.HPD0 and * TCR_EL1.HPD1 set */ if(socnum >= 0x8010){ chk(!g_patched_pinst_set_tcr, "pinst_set_tcr wasn't patched\n"); chk(!g_patched_all_msr_tcr_el1_x18, "did not patch all msr tcr_el1, x18\n"); } /* if we printed the error header, something is missing */ if(printed_err_hdr) xnuspy_fatal_error(); } static void initialize_xnuspy_cache(void){ uint64_t *xnuspy_cache_cursor = xnuspy_cache_base; XNUSPY_CACHE_WRITE(g_sysctl__kern_children_addr); XNUSPY_CACHE_WRITE(g_sysctl_register_oid_addr); XNUSPY_CACHE_WRITE(g_sysctl_handle_long_addr); XNUSPY_CACHE_WRITE(g_name2oid_addr); XNUSPY_CACHE_WRITE(g_sysctl_geometry_lock_addr); XNUSPY_CACHE_WRITE(g_lck_rw_lock_shared_addr); XNUSPY_CACHE_WRITE(g_lck_rw_done_addr); /* DID_REGISTER_SYSCTL, used inside hook_system_check_sysctlbyname_hook, * initialize to false */ XNUSPY_CACHE_WRITE(0); XNUSPY_CACHE_WRITE(g_h_s_c_sbn_epilogue_addr); XNUSPY_CACHE_WRITE(g_xnuspy_sysctl_mib_ptr); XNUSPY_CACHE_WRITE(g_xnuspy_sysctl_mib_count_ptr); XNUSPY_CACHE_WRITE(g_xnuspy_ctl_callnum); XNUSPY_CACHE_WRITE(g_kern_version_major); XNUSPY_CACHE_WRITE(g_xnuspy_ctl_addr); XNUSPY_CACHE_WRITE(g_xnuspy_ctl_img_codestart); XNUSPY_CACHE_WRITE(g_xnuspy_ctl_img_codesz); /* XNUSPY_CTL_IS_RX, used inside xnuspy_ctl_tramp.s, initialize to false */ XNUSPY_CACHE_WRITE(0); XNUSPY_CACHE_WRITE(g_phystokv_addr); XNUSPY_CACHE_WRITE(g_bcopy_phys_addr); if(g_kern_version_major == iOS_13_x){ XNUSPY_CACHE_WRITE(g_kalloc_canblock_addr); XNUSPY_CACHE_WRITE(g_kfree_addr_addr); } else{ XNUSPY_CACHE_WRITE(g_kalloc_external_addr); XNUSPY_CACHE_WRITE(g_kfree_ext_addr); } puts("xnuspy: initialized xnuspy cache"); } static uint32_t *install_h_s_c_sbn_hook(uint32_t *scratch_space, uint64_t *num_free_instrsp){ uint64_t num_free_instrs = *num_free_instrsp; uint64_t h_s_c_sbn_hook_len = g_hook_system_check_sysctlbyname_hook_len / sizeof(uint32_t); uint32_t *h_s_c_sbn_hook_cursor = (uint32_t *)g_hook_system_check_sysctlbyname_hook; uint32_t *h_s_c_sbn_hook_end = h_s_c_sbn_hook_cursor + h_s_c_sbn_hook_len; uint64_t h_s_c_sbn_hook_addr = xnu_ptr_to_va(scratch_space); uint32_t *h_s_c_sbn_branch_from = xnu_va_to_ptr(g_h_s_c_sbn_branch_addr); uint32_t *h_s_c_sbn_branch_from_orig = h_s_c_sbn_branch_from; while(h_s_c_sbn_hook_cursor < h_s_c_sbn_hook_end){ if(*(uint64_t *)h_s_c_sbn_hook_cursor == QWORD_PLACEHOLDER) *(uint64_t *)h_s_c_sbn_hook_cursor = xnu_ptr_to_va(xnuspy_cache_base); else if(*h_s_c_sbn_hook_cursor == OPCODE_PLACEHOLDER) *h_s_c_sbn_hook_cursor = *h_s_c_sbn_branch_from++; WRITE_INSTR_TO_SCRATCH_SPACE(*h_s_c_sbn_hook_cursor++); } /* Use x8 */ write_blr(8, h_s_c_sbn_branch_from_orig, h_s_c_sbn_hook_addr); *num_free_instrsp = num_free_instrs; return scratch_space; } static uint32_t *write_xnuspy_ctl_tramp_instrs(uint32_t *scratch_space, uint64_t *num_free_instrsp){ uint64_t num_free_instrs = *num_free_instrsp; uint64_t xnuspy_ctl_tramp_len = g_xnuspy_ctl_tramp_len / sizeof(uint32_t); uint32_t *xnuspy_ctl_tramp_cursor = (uint32_t *)g_xnuspy_ctl_tramp; uint32_t *xnuspy_ctl_tramp_end = xnuspy_ctl_tramp_cursor + xnuspy_ctl_tramp_len; while(xnuspy_ctl_tramp_cursor < xnuspy_ctl_tramp_end){ if(*(uint64_t *)xnuspy_ctl_tramp_cursor == QWORD_PLACEHOLDER) *(uint64_t *)xnuspy_ctl_tramp_cursor = xnu_ptr_to_va(xnuspy_cache_base); WRITE_INSTR_TO_SCRATCH_SPACE(*xnuspy_ctl_tramp_cursor++); } *num_free_instrsp = num_free_instrs; return scratch_space; } /* This function will replace an _enosys sysent with the address of * xnuspy_ctl_tramp. For the reason we need a trampoline, see * module/el1/xnuspy_ctl_tramp.s */ static uint32_t *install_xnuspy_ctl_tramp(uint32_t *scratch_space, uint64_t *num_free_instrsp){ struct sysent *sysent_stream = (struct sysent *)g_sysent_addr; bool tagged_ptr = false; uint16_t old_tag = 0; uint32_t limit = 1000; for(uint32_t i=0; i<limit; i++){ uint64_t sy_call = sysent_stream->sy_call; /* tagged pointer */ if((sy_call & 0xffff000000000000) != 0xffff000000000000){ old_tag = (sy_call >> 48); sy_call |= 0xffff000000000000; sy_call += kernel_slide; tagged_ptr = true; } /* mov w0, ENOSYS; ret */ if(*(uint64_t *)xnu_va_to_ptr(sy_call) == 0xd65f03c0528009c0){ g_xnuspy_ctl_callnum = i; uint64_t new_sy_call; /* sy_call */ if(!tagged_ptr) new_sy_call = xnu_ptr_to_va(scratch_space); else{ uint64_t untagged = (xnu_ptr_to_va(scratch_space) & 0xffffffffffff) - kernel_slide; /* re-tag */ new_sy_call = untagged | ((uint64_t)old_tag << 48); } sysent_stream->sy_call = new_sy_call; /* no 32 bit processes on iOS 11+, so no argument munger */ sysent_stream->sy_arg_munge32 = NULL; /* this syscall will return an integer */ sysent_stream->sy_return_type = 1; /* _SYSCALL_RET_INT_T */ /* this syscall has four arguments */ sysent_stream->sy_narg = 4; /* four 64 bit arguments, so arguments total 32 bytes */ sysent_stream->sy_arg_bytes = sizeof(uint64_t) * sysent_stream->sy_narg; return write_xnuspy_ctl_tramp_instrs(scratch_space, num_free_instrsp); } sysent_stream++; } puts("xnuspy: didn't"); puts(" find a sysent entry"); puts(" with enosys?"); xnuspy_fatal_error(); } static void initialize_xnuspy_callnum_sysctl_offsets(void){ uint32_t *sysctl_mibp = (uint32_t *)((uint8_t *)xnuspy_cache_base + (PAGE_SIZE / 2)); uint32_t *sysctl_mib_countp = (uint32_t *)(sysctl_mibp + CTL_MAXNAME); g_xnuspy_sysctl_mib_ptr = xnu_ptr_to_va(sysctl_mibp); g_xnuspy_sysctl_mib_count_ptr = xnu_ptr_to_va(sysctl_mib_countp); } static void initialize_xnuspy_ctl_image_koff(char *ksym, uint64_t *va){ const size_t num_needed_symbols = sizeof(g_xnuspy_ctl_needed_symbols) / sizeof(*g_xnuspy_ctl_needed_symbols); for(size_t i=0; i<num_needed_symbols; i++){ if(strcmp(ksym, g_xnuspy_ctl_needed_symbols[i].symbol) == 0){ *va = *g_xnuspy_ctl_needed_symbols[i].valp; return; } } } /* fill in all our kernel offsets in __koff, initialize g_xnuspy_ctl_addr * and g_xnuspy_ctl_img_codesz */ static void process_xnuspy_ctl_image(void *xnuspy_ctl_image){ struct mach_header_64 *mh = xnuspy_ctl_image; struct load_command *lc = (struct load_command *)(mh + 1); struct symtab_command *st = NULL; for(int i=0; i<mh->ncmds; i++){ if(lc->cmd == LC_SYMTAB) st = (struct symtab_command *)lc; else if(lc->cmd == LC_SEGMENT_64){ struct segment_command_64 *sc = (struct segment_command_64 *)lc; if(strcmp(sc->segname, "__TEXT_EXEC") == 0){ g_xnuspy_ctl_img_codestart = xnu_ptr_to_va(mh) + sc->vmaddr; g_xnuspy_ctl_img_codesz = sc->vmsize; } } if(st && g_xnuspy_ctl_img_codesz) break; lc = (struct load_command *)((uint8_t *)lc + lc->cmdsize); } if(!st || !g_xnuspy_ctl_img_codesz){ printf("xnuspy: could not find\n"); if(!st) printf(" symtab\n"); if(!g_xnuspy_ctl_img_codesz) printf(" g_xnuspy_ctl_img_codesz\n"); printf(" This may be happening\n" " due to a short read,\n" " try adding some code to\n" " module/el1/xnuspy_ctl/xnuspy_ctl.c\n" " to increase image size.\n"); xnuspy_fatal_error(); } struct nlist_64 *symtab = (struct nlist_64 *)((uint8_t *)xnuspy_ctl_image + st->symoff); char *strtab = (char *)xnuspy_ctl_image + st->stroff; for(int i=0; i<st->nsyms; i++){ char *sym = strtab + symtab[i].n_un.n_strx; uint64_t *va = (uint64_t *)((uint8_t *)xnuspy_ctl_image + symtab[i].n_value); if(strcmp(sym, "_xnuspy_ctl") == 0) g_xnuspy_ctl_addr = xnu_ptr_to_va(va); else if(strcmp(sym, "__hookme") == 0){ uint64_t _hookme_kva = xnu_ptr_to_va(va); uint64_t ceil = g_xnuspy_tramp_mem_end; int64_t dist = ceil - _hookme_kva; if(dist < 0) dist = -dist; if(dist > 0x8000000){ g_hookme_in_range = 0; printf("xnuspy: hookme is unable\n" " to be hooked, XNUSPY_CALL_HOOKME\n" " is disabled.\n"); } /* In case we've already seen _hookme_in_range, initialize this * symbol again */ initialize_xnuspy_ctl_image_koff("_hookme_in_range", &g_hookme_in_range); } else{ initialize_xnuspy_ctl_image_koff(sym, va); } } } #ifndef XNUSPY_TRAMP_PAGES #define XNUSPY_TRAMP_PAGES 1 #endif void (*next_preboot_hook)(void); void xnuspy_preboot_hook(void){ anything_missing(); uint64_t xnuspy_tramp_mem_size = PAGE_SIZE * XNUSPY_TRAMP_PAGES; void *xnuspy_tramp_mem = alloc_static(xnuspy_tramp_mem_size); if(!xnuspy_tramp_mem){ puts("xnuspy: alloc_static"); puts(" returned NULL while"); puts(" allocating xnuspy"); puts(" trampoline mem"); xnuspy_fatal_error(); } memset(xnuspy_tramp_mem, 0, xnuspy_tramp_mem_size); /* For every function which gets hooked, a single unconditional * immediate branch is written targeting some point on the * xnuspy_tramp_page. So that page must be within 128MB from the first * code in the kernelcache. If it's is not within that range, we cannot * assume every branch will fall within 128MB, and will fall back to * the unused r-x page we found earlier. We need to figure out the * address of the first page of code. */ /* I hope this is right */ struct segment_command_64 *__PRELINK_TEXT = macho_get_segment(mh_execute_header, "__PRELINK_TEXT"); struct segment_command_64 *__TEXT_EXEC = macho_get_segment(mh_execute_header, "__TEXT_EXEC"); struct section_64 *sec64 = (struct section_64 *)(__TEXT_EXEC + 1); /* codestart already slid on all kernels when reading from __TEXT:HEADER */ uint64_t codestart = UINT64_MAX; for(uint32_t i=0; i<__TEXT_EXEC->nsects; i++){ if(sec64->addr < codestart) codestart = sec64->addr; sec64++; } /* Old style kc */ if(__PRELINK_TEXT && __PRELINK_TEXT->vmsize > 0){ struct segment_command_64 *__PRELINK_INFO = macho_get_segment(mh_execute_header, "__PRELINK_INFO"); if(!__PRELINK_INFO){ printf("xnuspy: no prelink info\n" " segment???\n"); xnuspy_fatal_error(); } struct section_64 *__info = macho_get_section(__PRELINK_INFO, "__info"); if(!__info){ printf("xnuspy: no prelink info\n" " dict?\n"); xnuspy_fatal_error(); } /* __info->addr already slid */ char *infodict = xnu_va_to_ptr(__info->addr); char *cursor; while((cursor = strstr(infodict, "_PrelinkExecutableLoadAddr"))){ char *loadaddr_s = strstr(cursor, "0xfffffff"); if(!loadaddr_s) goto next; uint64_t loadaddr = strtoul(loadaddr_s, NULL, 0) + kernel_slide; struct mach_header_64 *mh64 = xnu_va_to_ptr(loadaddr); __TEXT_EXEC = macho_get_segment(mh64, "__TEXT_EXEC"); if(__TEXT_EXEC) break; next: infodict = cursor + 1; } struct section_64 *__text = macho_get_section(__TEXT_EXEC, "__text"); if(!__text){ printf("xnuspy: no __text section\n" " in __TEXT_EXEC??\n"); xnuspy_fatal_error(); } /* __text->addr not slid */ if(__text->addr + kernel_slide < codestart) codestart = __text->addr + kernel_slide; } uint64_t ceil = xnu_ptr_to_va(xnuspy_tramp_mem) + xnuspy_tramp_mem_size; uint64_t dist = ceil - codestart; bool fallback = false; if(dist > 0x8000000){ printf("xnuspy: distance from first\n" " code to end of tramp mem is larger\n" " than 128 MB. Falling back to\n" " the unused r-x page already in\n" " the kernelcache. As a result,\n" " there are less hooks you can\n" " install simultaneously.\n"); fallback = true; } else{ g_xnuspy_tramp_mem_addr = xnu_ptr_to_va(xnuspy_tramp_mem); g_xnuspy_tramp_mem_end = g_xnuspy_tramp_mem_addr + xnuspy_tramp_mem_size; } xnuspy_cache_base = alloc_static(PAGE_SIZE); if(!xnuspy_cache_base){ puts("xnuspy: alloc_static"); puts(" returned NULL while"); puts(" allocating for xnuspy"); puts(" cache"); xnuspy_fatal_error(); } void *xnuspy_ctl_image = alloc_static(loader_xfer_recv_count); if(!xnuspy_ctl_image){ puts("xnuspy: alloc_static"); puts(" returned NULL while"); puts(" allocating pages for"); puts(" xnuspy_ctl image"); xnuspy_fatal_error(); } memcpy(xnuspy_ctl_image, loader_xfer_recv_data, loader_xfer_recv_count); uint64_t num_free_instrs = g_exec_scratch_space_size / sizeof(uint32_t); uint32_t *scratch_space = xnu_va_to_ptr(g_exec_scratch_space_addr); scratch_space = install_h_s_c_sbn_hook(scratch_space, &num_free_instrs); scratch_space = install_xnuspy_ctl_tramp(scratch_space, &num_free_instrs); if(fallback){ /* Use the rest of the scratch space for the xnuspy_tramp structs. * This page will be marked as rwx inside xnuspy_init */ uint8_t *rxpage_unaligned = (uint8_t *)scratch_space; uint8_t *rxpage = (uint8_t *)(((uintptr_t)rxpage_unaligned + 8) & ~7); uint8_t *rxpage_end = (uint8_t *)(((uintptr_t)rxpage + PAGE_SIZE) & ~(PAGE_SIZE - 1)); /* We do this so checkra1n kpf doesn't use this space for shellcode */ memset(rxpage_unaligned, '$', rxpage_end - rxpage_unaligned); g_xnuspy_tramp_mem_addr = xnu_ptr_to_va(rxpage); g_xnuspy_tramp_mem_end = xnu_ptr_to_va(rxpage_end); } process_xnuspy_ctl_image(xnuspy_ctl_image); initialize_xnuspy_callnum_sysctl_offsets(); initialize_xnuspy_cache(); if(next_preboot_hook) next_preboot_hook(); }
mike-burns/pick
pty.c
<gh_stars>100-1000 #include "config.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/wait.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> __dead static void child(int, int, int, char **); static void parent(int, int, const char *); static char *parsekeys(const char *); static void sighandler(int); __dead static void usage(void); /* * Mandatory environment variables required by pick to operate correctly. * Any existing value will be overwritten. */ static const char *pickenv[] = { "LC_ALL", "en_US.UTF-8", "TERM", "xterm", NULL, }; static int gotsig; int main(int argc, char *argv[]) { char *keys = NULL; pid_t pid; int c, master, slave, status; while ((c = getopt(argc, argv, "k:")) != -1) switch (c) { case 'k': keys = parsekeys(optarg); break; default: usage(); } argc -= optind; argv += optind; if (argc == 0) usage(); if (signal(SIGCHLD, sighandler) == SIG_ERR) err(1, "signal"); if ((master = posix_openpt(O_RDWR)) == -1) err(1, "posix_openpt"); if (grantpt(master) == -1) err(1, "grantpt"); if (unlockpt(master) == -1) err(1, "unlockpt"); if ((slave = open(ptsname(master), O_RDWR)) == -1) err(1, "%s", ptsname(master)); switch ((pid = fork())) { case -1: err(1, "fork"); /* NOTREACHED */ case 0: child(master, slave, argc, argv); /* NOTREACHED */ default: parent(master, slave, keys != NULL ? keys : ""); /* Wait and exit with code of the child process. */ waitpid(pid, &status, 0); if (WIFSIGNALED(status)) exit(128 + WTERMSIG(status)); if (WIFEXITED(status)) exit(WEXITSTATUS(status)); } free(keys); return 0; } __dead static void usage(void) { fprintf(stderr, "usage: pick-test [-k path] -- utility " "[argument ...]\n"); exit(1); } static char * parsekeys(const char *path) { FILE *fh; char *buf; size_t len = 0; size_t size = 16; int c, esc, ctrl; if ((fh = fopen(path, "r")) == NULL) err(1, "fopen: %s", path); if ((buf = malloc(size)) == NULL) err(1, NULL); ctrl = esc = 0; while ((c = fgetc(fh)) != EOF) { if (c == '\\') { esc = 1; } else if (!esc && c == ' ') { continue; } else if (c == '^') { ctrl = 'A' - 1; continue; } else { buf[len++] = c - ctrl; ctrl = esc = 0; } if (size <= len) { if ((buf = reallocarray(buf, 2, size)) == NULL) err(1, NULL); size *= 2; } } if (ferror(fh)) err(1, "fgetc: %s", path); fclose(fh); buf[len] = '\0'; return buf; } static void sighandler(int sig) { gotsig = sig == SIGCHLD; } __dead static void child(int master, int slave, int argc, char **argv) { const char **env; char *cmd = NULL; struct winsize ws; size_t siz = 0; int fd; close(master); /* Disconnect the controlling tty, if present. */ if ((fd = open("/dev/tty", O_RDWR | O_NOCTTY)) >= 0) { /* Ignore any error. */ (void)ioctl(fd, TIOCNOTTY, NULL); close(fd); } /* Make the current process the session leader. */ if (setsid() == -1) err(1, "setsid"); /* Connect the slave as the controlling tty. */ if (ioctl(slave, TIOCSCTTY, NULL) == -1) err(1, "TIOCSCTTY"); /* * Set window size to known dimensions, necessary in order to deduce * when scrolling should occur. */ memset(&ws, 0, sizeof(ws)); ws.ws_col = 80, ws.ws_row = 24; if (ioctl(slave, TIOCSWINSZ, &ws) == -1) err(1, "TIOCSWINSZ"); for (env = pickenv; *env != NULL; env += 2) if (setenv(env[0], env[1], 1) == -1) err(1, "setenv: %s", env[0]); /* Join command. */ for (; argc > 0; argc--, argv++) { size_t len; if (siz > 0) { cmd[siz] = ' '; siz++; } len = strlen(argv[0]); cmd = reallocarray(cmd, 1, siz + len + 1); if (cmd == NULL) err(1, NULL); memcpy(&cmd[siz], argv[0], len); siz += len; cmd[siz] = '\0'; } execlp("sh", "sh", "-c", cmd, NULL); err(1, "sh"); } static void parent(int master, int slave, const char *keys) { char buf[BUFSIZ]; fd_set rfd; struct timeval timeout; size_t len; size_t written = 0; len = strlen(keys); memset(&timeout, 0, sizeof(timeout)); timeout.tv_sec = 2; while (gotsig == 0) { FD_ZERO(&rfd); FD_SET(master, &rfd); switch (select(master + 1, &rfd, NULL, NULL, &timeout)) { case -1: if (errno == EINTR) continue; err(1, "select"); /* NOTREACHED */ case 0: errx(1, "time limit exceeded"); /* NOTREACHED */ default: if (!FD_ISSET(master, &rfd)) continue; } /* * Read and discard output from child process, necessary since * it flushes. */ if (read(master, buf, sizeof(buf)) == -1) err(1, "read"); /* * When the pick process has flushed its output we can ensure * the call to tcsetattr has been completed and canonical mode * is disabled. At this point input can be written without any * line editing taking place. */ if (written < len) { ssize_t n; n = write(master, keys + written, len - written); if (n == -1) err(1, "write"); written += n; } } /* * If the last slave file descriptor closes while a read call is in * progress, the read may fail with EIO. To avoid that happening in the * above loop, this copy of the slave file descriptor is left open until * now. */ close(slave); }
jinhwang15/FBMessengerShareLocation
FBMessengerShareLocation/Pods/Headers/Public/FBSDKMessengerShareKit/FBSDKMessengerShareKit/FBSDKMessengerUrlHandler.h
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import <Foundation/Foundation.h> @class FBSDKMessengerURLHandler, FBSDKMessengerURLHandlerReplyContext, FBSDKMessengerURLHandlerOpenFromComposerContext, FBSDKMessengerURLHandlerCancelContext; @protocol FBSDKMessengerURLHandlerDelegate <NSObject> @optional /*! @abstract This is called after FBSDKMessengerURLHandler has received a reply from messenger @param messengerURLHandler The handler that handled the URL @param context The data passed from Messenger */ - (void)messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler didHandleReplyWithContext:(FBSDKMessengerURLHandlerReplyContext *)context; /*! @abstract This is called after a user tapped this app from the composer in Messenger @param messengerURLHandler The handler that handled the URL @param context The data passed from Messenger */ - (void) messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler didHandleOpenFromComposerWithContext:(FBSDKMessengerURLHandlerOpenFromComposerContext *)context; /*! @abstract This is called after a user canceled a share and Messenger redirected here @param messengerURLHandler The handler that handled the URL @param context The data passed from Messenger */ - (void)messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler didHandleCancelWithContext:(FBSDKMessengerURLHandlerCancelContext *)context; @end /*! @class FBSDKMessengerURLHandler @abstract FBSDKMessengerURLHandler is used to handle incoming URLs from Messenger. */ @interface FBSDKMessengerURLHandler : NSObject /*! @abstract Determines whether an incoming URL can be handled by this class @param url The URL passed in from the source application @param sourceApplication The bundle id representing the source application @return YES if this URL can be handled */ - (BOOL)canOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication; /*! @abstract Attempts to handle the Messenger URL and returns YES if and only if successful. This should be called from the AppDelegate's -openURL: method @param url The URL passed in from the source application @param sourceApplication The bundle id representing the source application @return YES if this successfully handled the URL */ - (BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication; @property (nonatomic, weak) id<FBSDKMessengerURLHandlerDelegate> delegate; @end
jinhwang15/FBMessengerShareLocation
FBMessengerShareLocation/Pods/Target Support Files/Pods-FBMessengerShareLocation/Pods-FBMessengerShareLocation-environment.h
<reponame>jinhwang15/FBMessengerShareLocation // To check if a library is compiled with CocoaPods you // can use the `COCOAPODS` macro definition which is // defined in the xcconfigs so it is available in // headers also when they are imported in the client // project. // Bolts #define COCOAPODS_POD_AVAILABLE_Bolts #define COCOAPODS_VERSION_MAJOR_Bolts 1 #define COCOAPODS_VERSION_MINOR_Bolts 1 #define COCOAPODS_VERSION_PATCH_Bolts 5 // Bolts/AppLinks #define COCOAPODS_POD_AVAILABLE_Bolts_AppLinks #define COCOAPODS_VERSION_MAJOR_Bolts_AppLinks 1 #define COCOAPODS_VERSION_MINOR_Bolts_AppLinks 1 #define COCOAPODS_VERSION_PATCH_Bolts_AppLinks 5 // Bolts/Tasks #define COCOAPODS_POD_AVAILABLE_Bolts_Tasks #define COCOAPODS_VERSION_MAJOR_Bolts_Tasks 1 #define COCOAPODS_VERSION_MINOR_Bolts_Tasks 1 #define COCOAPODS_VERSION_PATCH_Bolts_Tasks 5 // FBSDKCoreKit #define COCOAPODS_POD_AVAILABLE_FBSDKCoreKit #define COCOAPODS_VERSION_MAJOR_FBSDKCoreKit 4 #define COCOAPODS_VERSION_MINOR_FBSDKCoreKit 1 #define COCOAPODS_VERSION_PATCH_FBSDKCoreKit 0 // FBSDKCoreKit/arc #define COCOAPODS_POD_AVAILABLE_FBSDKCoreKit_arc #define COCOAPODS_VERSION_MAJOR_FBSDKCoreKit_arc 4 #define COCOAPODS_VERSION_MINOR_FBSDKCoreKit_arc 1 #define COCOAPODS_VERSION_PATCH_FBSDKCoreKit_arc 0 // FBSDKCoreKit/no-arc #define COCOAPODS_POD_AVAILABLE_FBSDKCoreKit_no_arc #define COCOAPODS_VERSION_MAJOR_FBSDKCoreKit_no_arc 4 #define COCOAPODS_VERSION_MINOR_FBSDKCoreKit_no_arc 1 #define COCOAPODS_VERSION_PATCH_FBSDKCoreKit_no_arc 0 // FBSDKLoginKit #define COCOAPODS_POD_AVAILABLE_FBSDKLoginKit #define COCOAPODS_VERSION_MAJOR_FBSDKLoginKit 4 #define COCOAPODS_VERSION_MINOR_FBSDKLoginKit 1 #define COCOAPODS_VERSION_PATCH_FBSDKLoginKit 0 // FBSDKMessengerShareKit #define COCOAPODS_POD_AVAILABLE_FBSDKMessengerShareKit #define COCOAPODS_VERSION_MAJOR_FBSDKMessengerShareKit 1 #define COCOAPODS_VERSION_MINOR_FBSDKMessengerShareKit 2 #define COCOAPODS_VERSION_PATCH_FBSDKMessengerShareKit 1
jinhwang15/FBMessengerShareLocation
FBMessengerShareLocation/FBMessengerShareLocation/MessengerShareLocation-BridgingHeader.h
// // MessengerShareLocation-BridgingHeader.h // FBMessengerShareLocation // // Created by <NAME> on 16/05/15. // Copyright (c) 2015 msdeveloper. All rights reserved. // #ifndef FBMessengerShareLocation_MessengerShareLocation_BridgingHeader_h #define FBMessengerShareLocation_MessengerShareLocation_BridgingHeader_h #import <FBSDKCoreKit/FBSDKCoreKit.h> #import <FBSDKLoginKit/FBSDKLoginKit.h> #import <FBSDKMessengerShareKit/FBSDKMessengerShareKit.h> #endif
SJ-magic-youtube-VisualProgrammer/74_oF_SpreadParticle_musicSync
ofApp.h
/************************************************************ ************************************************************/ #pragma once /************************************************************ ************************************************************/ #include "ofMain.h" #include "sj_common.h" #include "fft.h" #include "DrawFFT.h" #include "DrawBackImage.h" #include "DrawLogo.h" #include "DrawSpreadParticle.h" /************************************************************ ************************************************************/ class ofApp : public ofBaseApp{ private: /**************************************** ****************************************/ enum{ MAIN_WINDOW__WIDTH = 1280, // 切れの良い解像度でないと、ofSaveScreen()での画面保存が上手く行かなかった(真っ暗な画面が保存されるだけ). MAIN_WINDOW__HEIGHT = 720, }; /**************************************** ****************************************/ FFT fft_thread; // VISUALIZE Visualize; DRAW_FFT DrawFFT; DRAW_BACK_IMG DrawBackImg; DRAW_LOGO DrawLogo; DRAW_SPREAD_PARTICLE DrawSpreadParticle; ofSoundStream *soundStream; bool b_EnableAudioOut; int soundStream_Input_DeviceId; int soundStream_Output_DeviceId; ofFbo fbo_WorkSpace; /**************************************** ****************************************/ void setup_Gui(); void setup_sound(); void ClearFbo(ofFbo& fbo); public: /**************************************** ****************************************/ ofApp(int _soundStream_Input_DeviceId, int _soundStream_Output_DeviceId); ~ofApp(); void setup(); void update(); void draw(); void exit(); void audioIn(ofSoundBuffer & buffer); void audioOut(ofSoundBuffer & buffer); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); };
SJ-magic-youtube-VisualProgrammer/74_oF_SpreadParticle_musicSync
DrawFFT.h
<filename>DrawFFT.h /************************************************************ ************************************************************/ #pragma once /************************************************************ ************************************************************/ #include <ofMain.h> #include "fft.h" #include <ofxVboSet.h> #include "sj_common.h" /************************************************************ ************************************************************/ /************************************************** **************************************************/ class DRAW_FFT{ private: /**************************************** ****************************************/ ofx__VBO_SET VboSet__FFT; ofTrueTypeFont font; /**************************************** ****************************************/ void Refresh_vboVerts__FFT(const FFT& fft); void Refresh_vboColor__FFT(const FFT& fft); public: /**************************************** ****************************************/ DRAW_FFT(); ~DRAW_FFT(); void setup(const FFT& fft); void update(const FFT& fft); void draw(ofFbo& fbo, const FFT& fft); };
SJ-magic-youtube-VisualProgrammer/74_oF_SpreadParticle_musicSync
DrawSpreadParticle.h
<gh_stars>0 /************************************************************ ************************************************************/ #pragma once /************************************************************ ************************************************************/ #include <ofMain.h> #include "fft.h" #include <ofxVboSet.h> #include "sj_common.h" /************************************************************ ************************************************************/ /************************************************** **************************************************/ class PARTICLE{ private: ofVec2f pos; ofVec2f dir; ofVec2f Size; float col_Alpha; bool IsScreenOut(); public: PARTICLE(); ~PARTICLE(); void init(); void Proceed(float vel, float dt); void Proceed_RandomAmount(); float get_ColAlpha() { return col_Alpha; } ofVec2f getPos_LeftLow(){ ofVec2f point; point.x = pos.x - Size.x/2; point.y = pos.y + Size.y/2; return point; } ofVec2f getPos_LeftUp(){ ofVec2f point; point.x = pos.x - Size.x/2; point.y = pos.y - Size.y/2; return point; } ofVec2f getPos_RightUp(){ ofVec2f point; point.x = pos.x + Size.x/2; point.y = pos.y - Size.y/2; return point; } ofVec2f getPos_RightLow(){ ofVec2f point; point.x = pos.x + Size.x/2; point.y = pos.y + Size.y/2; return point; } }; /************************************************** **************************************************/ class DRAW_SPREAD_PARTICLE{ private: /**************************************** ****************************************/ enum{ // NUM_CLOUDS = 500, NUM_CLOUDS = 1000, NUM_VBO_VERTS = NUM_CLOUDS * 4, // GL_QUADS }; /**************************************** ****************************************/ vector <PARTICLE> clouds; ofx__VBO_SET VboSet__SpreadParticle; ofImage TextureImg[NUM_TEXTURES_SPREADPARTICLE]; float vel_SpreadParticle; float t_Last = 0; /**************************************** ****************************************/ void Refresh_vboVerts__SpreadParticle(); void Refresh_vboColor__SpreadParticle(); void Refresh_vboTexCoords__SpreadParticle(); public: /**************************************** ****************************************/ DRAW_SPREAD_PARTICLE(); ~DRAW_SPREAD_PARTICLE(); void setup(const FFT& fft); void update(const FFT& fft); void draw(ofFbo& fbo, const FFT& fft); };
i-vishi/ds-and-algo
Binary Tree - Inorder Traversal/C/inorderBinaryTree.c
<gh_stars>1-10 /* Author: <NAME> * Created: 06-28-2021 11:05:28 */ #include <stdio.h> #include <stdlib.h> // Binary Tree Node typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // function to get a new tree node TreeNode *newNode(int val) { TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; node->left = NULL; node->right = NULL; return node; } // function to get inorder traversal of binary tree void getInorderTraversal(TreeNode *root, int *ans, int *pos) { if (root == NULL) return; getInorderTraversal(root->left, ans, pos); ans[*pos] = root->val; (*pos)++; getInorderTraversal(root->right, ans, pos); } // main function to test above function int main() { TreeNode *root = newNode(1); TreeNode *n2 = newNode(23); TreeNode *n3 = newNode(13); TreeNode *n4 = newNode(44); root->left = n2; root->right = n3; n2->right = n4; int *res = malloc(100 * sizeof(int)); int pos = 0; getInorderTraversal(root, res, &pos); printf("Inorder is : "); for (int i = 0; i < pos; i++) { printf("%d ", res[i]); } printf("\n"); return 0; }
i-vishi/ds-and-algo
Sort - Quick/C/quickSort.c
/* Author: <NAME> * Created: 13-01-2021 09:45:23 */ #include <stdio.h> // helper function to get pivot int partition(int a[], int l, int h) { int p = a[h]; int i = l; for (int j = l; j <= h - 1; j++) { if (a[j] < p) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; i++; } } int tmp = a[i]; a[i] = a[h]; a[h] = tmp; return i; } // function to sort an array using quick sort void quickSort(int a[], int l, int h) { if (l < h) { int pivot = partition(a, l, h); quickSort(a, l, pivot - 1); quickSort(a, pivot + 1, h); } } // main function to test above function int main() { int arr[] = {5, 46, 12, 53, 29, 6, 1, 42}; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted Array :\t"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }