repo_name
stringlengths
5
85
path
stringlengths
3
252
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
922
999k
license
stringclasses
15 values
kristapsdz/letskencrypt-portable
http.c
1
18646
/* $Id$ */ /* * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <sys/socket.h> #include <sys/param.h> #include <arpa/inet.h> #if TLS_API < 20160801 # include <sys/stat.h> # include <sys/mman.h> #endif #include <assert.h> #include <ctype.h> #include <err.h> #if TLS_API < 20160801 # include <fcntl.h> #endif #include <limits.h> #include <netdb.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <tls.h> #include <unistd.h> #include "http.h" #include "extern.h" #ifndef DEFAULT_CA_FILE # define DEFAULT_CA_FILE "/etc/ssl/cert.pem" #endif /* * A buffer for transferring HTTP/S data. */ struct httpxfer { char *hbuf; /* header transfer buffer */ size_t hbufsz; /* header buffer size */ int headok; /* header has been parsed */ char *bbuf; /* body transfer buffer */ size_t bbufsz; /* body buffer size */ int bodyok; /* body has been parsed */ char *headbuf; /* lookaside buffer for headers */ struct httphead *head; /* parsed headers */ size_t headsz; /* number of headers */ }; /* * An HTTP/S connection object. */ struct http { int fd; /* connected socket */ short port; /* port number */ struct source src; /* endpoint (raw) host */ char *path; /* path to request */ char *host; /* name of endpoint host */ struct tls *ctx; /* if TLS */ writefp writer; /* write function */ readfp reader; /* read function */ }; struct httpcfg { struct tls_config *tlscfg; }; static ssize_t dosysread(char *buf, size_t sz, const struct http *http) { ssize_t rc; rc = read(http->fd, buf, sz); if (rc < 0) warn("%s: read", http->src.ip); return (rc); } static ssize_t dosyswrite(const void *buf, size_t sz, const struct http *http) { ssize_t rc; rc = write(http->fd, buf, sz); if (rc < 0) warn("%s: write", http->src.ip); return(rc); } static ssize_t dotlsread(char *buf, size_t sz, const struct http *http) { ssize_t rc; do { rc = tls_read(http->ctx, buf, sz); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_read: %s", http->src.ip, tls_error(http->ctx)); return (rc); } static ssize_t dotlswrite(const void *buf, size_t sz, const struct http *http) { ssize_t rc; do { rc = tls_write(http->ctx, buf, sz); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_write: %s", http->src.ip, tls_error(http->ctx)); return (rc); } /* * Free the resources of an http_init() object. */ void http_uninit(struct httpcfg *p) { if (NULL == p) return; if (NULL != p->tlscfg) tls_config_free(p->tlscfg); free(p); } /* * Work around the "lazy-loading" problem in earlier versions of libtls. * In these systems, using tls_config_set_ca_file() would only cause the * file location to be copied. * It would then be used after the pledge and/or chroot. * We work around this by loading the file directly. */ #if TLS_API < 20160801 static int http_config_set_ca_file(struct httpcfg *p) { int fd, rc = 0; struct stat st; void *buf; if (-1 == (fd = open(DEFAULT_CA_FILE, O_RDONLY, 0))) { warn("%s", DEFAULT_CA_FILE); return(0); } else if (-1 == fstat(fd, &st)) { warn("%s", DEFAULT_CA_FILE); close(fd); return(0); } buf = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (MAP_FAILED == buf) { warn("%s", DEFAULT_CA_FILE); close(fd); return(0); } if (-1 == tls_config_set_ca_mem(p->tlscfg, buf, st.st_size)) warn("%s: tls_config_set_ca_file", DEFAULT_CA_FILE); else rc = 1; munmap(buf, st.st_size); close(fd); return(rc); } #endif /* * This function allocates a configuration shared among multiple * connections. * It will generally be called once, then used in a series of * connections. * Returns the configuration object or NULL on errors. * A returned object must be freed with http_deinit(). */ struct httpcfg * http_init(void) { struct httpcfg *p; /* Can be called more than once. */ if (-1 == tls_init()) { warn("tls_init"); return (NULL); } if (NULL == (p = malloc(sizeof(struct httpcfg)))) { warn("calloc"); return (NULL); } else if (NULL == (p->tlscfg = tls_config_new())) { warn("tls_config_new"); goto err; } tls_config_set_protocols(p->tlscfg, TLS_PROTOCOLS_ALL); #if TLS_API < 20160801 if ( ! http_config_set_ca_file(p)) goto err; #else if (-1 == tls_config_set_ca_file(p->tlscfg, DEFAULT_CA_FILE)) { warn("tls_config_set_ca_file: %s", tls_config_error(p->tlscfg)); goto err; } #endif if (-1 == tls_config_set_ciphers(p->tlscfg, "compat")) { #if TLS_API < 20160801 warn("tls_config_set_ciphers"); #else warn("tls_config_set_ciphers: %s", tls_config_error(p->tlscfg)); #endif goto err; } return (p); err: http_uninit(p); return (NULL); } static ssize_t http_read(char *buf, size_t sz, const struct http *http) { ssize_t ssz, xfer; xfer = 0; do { if ((ssz = http->reader(buf, sz, http)) < 0) return (-1); if (0 == ssz) break; xfer += ssz; sz -= ssz; buf += ssz; } while (ssz > 0 && sz > 0); return (xfer); } static int http_write(const char *buf, size_t sz, const struct http *http) { ssize_t ssz, xfer; xfer = sz; while (sz > 0) { if ((ssz = http->writer(buf, sz, http)) < 0) return (-1); sz -= ssz; buf += (size_t)ssz; } return (xfer); } void http_disconnect(struct http *http) { int rc; if (NULL != http->ctx) { do { rc = tls_close(http->ctx); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_close: %s", http->src.ip, tls_error(http->ctx)); if (-1 == close(http->fd)) warn("%s: close", http->src.ip); tls_free(http->ctx); } else if (-1 != http->fd) { /* Non-TLS connection. */ if (-1 == close(http->fd)) warn("%s: close", http->src.ip); } http->fd = -1; http->ctx = NULL; } void http_free(struct http *http) { if (NULL == http) return; http_disconnect(http); free(http->host); free(http->path); free(http->src.ip); free(http); } struct http * http_alloc(struct httpcfg *cfg, const struct source *addrs, size_t addrsz, const char *host, short port, const char *path) { struct sockaddr_storage ss; int family, fd, c; socklen_t len; size_t cur, i = 0; struct http *http; /* Do this while we still have addresses to connect. */ again: if (i == addrsz) return (NULL); cur = i++; /* Convert to PF_INET or PF_INET6 address from string. */ memset(&ss, 0, sizeof(struct sockaddr_storage)); if (4 == addrs[cur].family) { family = PF_INET; ((struct sockaddr_in *)&ss)->sin_family = AF_INET; ((struct sockaddr_in *)&ss)->sin_port = htons(port); c = inet_pton(AF_INET, addrs[cur].ip, &((struct sockaddr_in *)&ss)->sin_addr); len = sizeof(struct sockaddr_in); } else if (6 == addrs[cur].family) { family = PF_INET6; ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6; ((struct sockaddr_in6 *)&ss)->sin6_port = htons(port); c = inet_pton(AF_INET6, addrs[cur].ip, &((struct sockaddr_in6 *)&ss)->sin6_addr); len = sizeof(struct sockaddr_in6); } else { warnx("%s: unknown family", addrs[cur].ip); goto again; } if (c < 0) { warn("%s: inet_ntop", addrs[cur].ip); goto again; } else if (0 == c) { warnx("%s: inet_ntop", addrs[cur].ip); goto again; } /* Create socket and connect. */ fd = socket(family, SOCK_STREAM, 0); if (-1 == fd) { warn("%s: socket", addrs[cur].ip); goto again; } else if (-1 == connect(fd, (struct sockaddr *)&ss, len)) { warn("%s: connect", addrs[cur].ip); close(fd); goto again; } /* Allocate the communicator. */ http = calloc(1, sizeof(struct http)); if (NULL == http) { warn("calloc"); close(fd); return (NULL); } http->fd = fd; http->port = port; http->src.family = addrs[cur].family; http->src.ip = strdup(addrs[cur].ip); http->host = strdup(host); http->path = strdup(path); if (NULL == http->src.ip || NULL == http->host || NULL == http->path) { warn("strdup"); goto err; } /* If necessary, do our TLS setup. */ if (443 != port) { http->writer = dosyswrite; http->reader = dosysread; return (http); } http->writer = dotlswrite; http->reader = dotlsread; if (NULL == (http->ctx = tls_client())) { warn("tls_client"); goto err; } else if (-1 == tls_configure(http->ctx, cfg->tlscfg)) { warnx("%s: tls_configure: %s", http->src.ip, tls_error(http->ctx)); goto err; } if (0 != tls_connect_socket (http->ctx, http->fd, http->host)) { warnx("%s: tls_connect_socket: %s, %s", http->src.ip, http->host, tls_error(http->ctx)); goto err; } return (http); err: http_free(http); return (NULL); } struct httpxfer * http_open(const struct http *http, const void *p, size_t psz) { char *req; int c; struct httpxfer *trans; if (NULL == p) { c = asprintf(&req, "GET %s HTTP/1.0\r\n" "Host: %s\r\n" "\r\n", http->path, http->host); } else { c = asprintf(&req, "POST %s HTTP/1.0\r\n" "Host: %s\r\n" "Content-Length: %zu\r\n" "\r\n", http->path, http->host, psz); } if (-1 == c) { warn("asprintf"); return (NULL); } else if ( ! http_write(req, c, http)) { free(req); return (NULL); } else if (NULL != p && ! http_write(p, psz, http)) { free(req); return (NULL); } free(req); trans = calloc(1, sizeof(struct httpxfer)); if (NULL == trans) warn("calloc"); return (trans); } void http_close(struct httpxfer *x) { if (NULL == x) return; free(x->hbuf); free(x->bbuf); free(x->headbuf); free(x->head); free(x); } /* * Read the HTTP body from the wire. * If invoked multiple times, this will return the same pointer with the * same data (or NULL, if the original invocation returned NULL). * Returns NULL if read or allocation errors occur. * You must not free the returned pointer. */ char * http_body_read(const struct http *http, struct httpxfer *trans, size_t *sz) { char buf[BUFSIZ]; ssize_t ssz; void *pp; size_t szp; if (NULL == sz) sz = &szp; /* Have we already parsed this? */ if (trans->bodyok > 0) { *sz = trans->bbufsz; return (trans->bbuf); } else if (trans->bodyok < 0) return (NULL); *sz = 0; trans->bodyok = -1; do { /* If less than sizeof(buf), at EOF. */ if ((ssz = http_read(buf, sizeof(buf), http)) < 0) return (NULL); else if (0 == ssz) break; pp = realloc(trans->bbuf, trans->bbufsz + ssz); if (NULL == pp) { warn("realloc"); return (NULL); } trans->bbuf = pp; memcpy(trans->bbuf + trans->bbufsz, buf, ssz); trans->bbufsz += ssz; } while (sizeof(buf) == ssz); trans->bodyok = 1; *sz = trans->bbufsz; return (trans->bbuf); } struct httphead * http_head_get(const char *v, struct httphead *h, size_t hsz) { size_t i; for (i = 0; i < hsz; i++) { if (strcmp(h[i].key, v)) continue; return (&h[i]); } return (NULL); } /* * Look through the headers and determine our HTTP code. * This will return -1 on failure, otherwise the code. */ int http_head_status(const struct http *http, struct httphead *h, size_t sz) { int rc; unsigned int code; struct httphead *st; if (NULL == (st = http_head_get("Status", h, sz))) { warnx("%s: no status header", http->src.ip); return (-1); } rc = sscanf(st->val, "%*s %u %*s", &code); if (rc < 0) { warn("sscanf"); return (-1); } else if (1 != rc) { warnx("%s: cannot convert status header", http->src.ip); return (-1); } return (code); } /* * Parse headers from the transfer. * Malformed headers are skipped. * A special "Status" header is added for the HTTP status line. * This can only happen once http_head_read has been called with * success. * This can be invoked multiple times: it will only parse the headers * once and after that it will just return the cache. * You must not free the returned pointer. * If the original header parse failed, or if memory allocation fails * internally, this returns NULL. */ struct httphead * http_head_parse(const struct http *http, struct httpxfer *trans, size_t *sz) { size_t hsz, szp; struct httphead *h; char *cp, *ep, *ccp, *buf; if (NULL == sz) sz = &szp; /* * If we've already parsed the headers, return the * previously-parsed buffer now. * If we have errors on the stream, return NULL now. */ if (NULL != trans->head) { *sz = trans->headsz; return (trans->head); } else if (trans->headok <= 0) return (NULL); if (NULL == (buf = strdup(trans->hbuf))) { warn("strdup"); return (NULL); } hsz = 0; cp = buf; do { if (NULL != (cp = strstr(cp, "\r\n"))) cp += 2; hsz++; } while (NULL != cp); /* * Allocate headers, then step through the data buffer, parsing * out headers as we have them. * We know at this point that the buffer is nil-terminated in * the usual way. */ h = calloc(hsz, sizeof(struct httphead)); if (NULL == h) { warn("calloc"); free(buf); return (NULL); } *sz = hsz; hsz = 0; cp = buf; do { if (NULL != (ep = strstr(cp, "\r\n"))) { *ep = '\0'; ep += 2; } if (0 == hsz) { h[hsz].key = "Status"; h[hsz++].val = cp; continue; } /* Skip bad headers. */ if (NULL == (ccp = strchr(cp, ':'))) { warnx("%s: header without separator", http->src.ip); continue; } *ccp++ = '\0'; while (isspace((int)*ccp)) ccp++; h[hsz].key = cp; h[hsz++].val = ccp; } while (NULL != (cp = ep)); trans->headbuf = buf; trans->head = h; trans->headsz = hsz; return (h); } /* * Read the HTTP headers from the wire. * If invoked multiple times, this will return the same pointer with the * same data (or NULL, if the original invocation returned NULL). * Returns NULL if read or allocation errors occur. * You must not free the returned pointer. */ char * http_head_read(const struct http *http, struct httpxfer *trans, size_t *sz) { char buf[BUFSIZ]; ssize_t ssz; char *ep; void *pp; size_t szp; if (NULL == sz) sz = &szp; /* Have we already parsed this? */ if (trans->headok > 0) { *sz = trans->hbufsz; return (trans->hbuf); } else if (trans->headok < 0) return (NULL); *sz = 0; ep = NULL; trans->headok = -1; /* * Begin by reading by BUFSIZ blocks until we reach the header * termination marker (two CRLFs). * We might read into our body, but that's ok: we'll copy out * the body parts into our body buffer afterward. */ do { /* If less than sizeof(buf), at EOF. */ if ((ssz = http_read(buf, sizeof(buf), http)) < 0) return (NULL); else if (0 == ssz) break; pp = realloc(trans->hbuf, trans->hbufsz + ssz); if (NULL == pp) { warn("realloc"); return (NULL); } trans->hbuf = pp; memcpy(trans->hbuf + trans->hbufsz, buf, ssz); trans->hbufsz += ssz; /* Search for end of headers marker. */ ep = memmem(trans->hbuf, trans->hbufsz, "\r\n\r\n", 4); } while (NULL == ep && sizeof(buf) == ssz); if (NULL == ep) { warnx("%s: partial transfer", http->src.ip); return (NULL); } *ep = '\0'; /* * The header data is invalid if it has any binary characters in * it: check that now. * This is important because we want to guarantee that all * header keys and pairs are properly nil-terminated. */ if (strlen(trans->hbuf) != (uintptr_t)(ep - trans->hbuf)) { warnx("%s: binary data in header", http->src.ip); return (NULL); } /* * Copy remaining buffer into body buffer. */ ep += 4; trans->bbufsz = (trans->hbuf + trans->hbufsz) - ep; trans->bbuf = malloc(trans->bbufsz); if (NULL == trans->bbuf) { warn("malloc"); return (NULL); } memcpy(trans->bbuf, ep, trans->bbufsz); trans->headok = 1; *sz = trans->hbufsz; return (trans->hbuf); } void http_get_free(struct httpget *g) { if (NULL == g) return; http_close(g->xfer); http_free(g->http); free(g); } struct httpget * http_get(struct httpcfg *cfg, const struct source *addrs, size_t addrsz, const char *domain, short port, const char *path, const void *post, size_t postsz) { struct http *h; struct httpxfer *x; struct httpget *g; struct httphead *head; size_t headsz, bodsz, headrsz; int code; char *bod, *headr; h = http_alloc(cfg, addrs, addrsz, domain, port, path); if (NULL == h) return (NULL); if (NULL == (x = http_open(h, post, postsz))) { http_free(h); return (NULL); } else if (NULL == (headr = http_head_read(h, x, &headrsz))) { http_close(x); http_free(h); return (NULL); } else if (NULL == (bod = http_body_read(h, x, &bodsz))) { http_close(x); http_free(h); return (NULL); } http_disconnect(h); if (NULL == (head = http_head_parse(h, x, &headsz))) { http_close(x); http_free(h); return (NULL); } else if ((code = http_head_status(h, head, headsz)) < 0) { http_close(x); http_free(h); return (NULL); } if (NULL == (g = calloc(1, sizeof(struct httpget)))) { warn("calloc"); http_close(x); http_free(h); return (NULL); } g->headpart = headr; g->headpartsz = headrsz; g->bodypart = bod; g->bodypartsz = bodsz; g->head = head; g->headsz = headsz; g->code = code; g->xfer = x; g->http = h; return (g); } #if 0 int main(void) { struct httpget *g; struct httphead *httph; size_t i, httphsz; struct source addrs[2]; size_t addrsz; #if 0 addrs[0].ip = "127.0.0.1"; addrs[0].family = 4; addrsz = 1; #else addrs[0].ip = "2a00:1450:400a:806::2004"; addrs[0].family = 6; addrs[1].ip = "193.135.3.123"; addrs[1].family = 4; addrsz = 2; #endif #if 0 g = http_get(addrs, addrsz, "localhost", 80, "/index.html"); #else g = http_get(addrs, addrsz, "www.google.ch", 80, "/index.html", NULL, 0); #endif if (NULL == g) errx(EXIT_FAILURE, "http_get"); httph = http_head_parse(g->http, g->xfer, &httphsz); warnx("code: %d", g->code); for (i = 0; i < httphsz; i++) warnx("head: [%s]=[%s]", httph[i].key, httph[i].val); http_get_free(g); return (EXIT_SUCCESS); } #endif
isc
cliffordwolf/picorv32
scripts/cxxdemo/syscalls.c
4
1805
// An extremely minimalist syscalls.c for newlib // Based on riscv newlib libgloss/riscv/sys_*.c // Written by Clifford Wolf. #include <sys/stat.h> #include <unistd.h> #include <errno.h> #define UNIMPL_FUNC(_f) ".globl " #_f "\n.type " #_f ", @function\n" #_f ":\n" asm ( ".text\n" ".align 2\n" UNIMPL_FUNC(_open) UNIMPL_FUNC(_openat) UNIMPL_FUNC(_lseek) UNIMPL_FUNC(_stat) UNIMPL_FUNC(_lstat) UNIMPL_FUNC(_fstatat) UNIMPL_FUNC(_isatty) UNIMPL_FUNC(_access) UNIMPL_FUNC(_faccessat) UNIMPL_FUNC(_link) UNIMPL_FUNC(_unlink) UNIMPL_FUNC(_execve) UNIMPL_FUNC(_getpid) UNIMPL_FUNC(_fork) UNIMPL_FUNC(_kill) UNIMPL_FUNC(_wait) UNIMPL_FUNC(_times) UNIMPL_FUNC(_gettimeofday) UNIMPL_FUNC(_ftime) UNIMPL_FUNC(_utime) UNIMPL_FUNC(_chown) UNIMPL_FUNC(_chmod) UNIMPL_FUNC(_chdir) UNIMPL_FUNC(_getcwd) UNIMPL_FUNC(_sysconf) "j unimplemented_syscall\n" ); void unimplemented_syscall() { const char *p = "Unimplemented system call called!\n"; while (*p) *(volatile int*)0x10000000 = *(p++); asm volatile ("ebreak"); __builtin_unreachable(); } ssize_t _read(int file, void *ptr, size_t len) { // always EOF return 0; } ssize_t _write(int file, const void *ptr, size_t len) { const void *eptr = ptr + len; while (ptr != eptr) *(volatile int*)0x10000000 = *(char*)(ptr++); return len; } int _close(int file) { // close is called before _exit() return 0; } int _fstat(int file, struct stat *st) { // fstat is called during libc startup errno = ENOENT; return -1; } void *_sbrk(ptrdiff_t incr) { extern unsigned char _end[]; // Defined by linker static unsigned long heap_end; if (heap_end == 0) heap_end = (long)_end; heap_end += incr; return (void *)(heap_end - incr); } void _exit(int exit_status) { asm volatile ("ebreak"); __builtin_unreachable(); }
isc
bnoordhuis/suv
deps/libuv/test/test-loop-handles.c
73
9821
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* Tests commented out with XXX are ones that are failing on Linux */ /* * Purpose of this test is to check semantics of starting and stopping * prepare, check and idle watchers. * * - A watcher must be able to safely stop or close itself; * - Once a watcher is stopped or closed its callback should never be called. * - If a watcher is closed, it is implicitly stopped and its close_cb should * be called exactly once. * - A watcher can safely start and stop other watchers of the same type. * - Prepare and check watchers are called once per event loop iterations. * - All active idle watchers are queued when the event loop has no more work * to do. This is done repeatedly until all idle watchers are inactive. * - If a watcher starts another watcher of the same type its callback is not * immediately queued. For check and prepare watchers, that means that if * a watcher makes another of the same type active, it'll not be called until * the next event loop iteration. For idle. watchers this means that the * newly activated idle watcher might not be queued immediately. * - Prepare, check, idle watchers keep the event loop alive even when they're * not active. * * This is what the test globally does: * * - prepare_1 is always active and counts event loop iterations. It also * creates and starts prepare_2 every other iteration. Finally it verifies * that no idle watchers are active before polling. * - prepare_2 is started by prepare_1 every other iteration. It immediately * stops itself. It verifies that a watcher is not queued immediately * if created by another watcher of the same type. * - There's a check watcher that stops the event loop after a certain number * of iterations. It starts a varying number of idle_1 watchers. * - Idle_1 watchers stop themselves after being called a few times. All idle_1 * watchers try to start the idle_2 watcher if it is not already started or * awaiting its close callback. * - The idle_2 watcher always exists but immediately closes itself after * being started by a check_1 watcher. It verifies that a watcher is * implicitly stopped when closed, and that a watcher can close itself * safely. * - There is a repeating timer. It does not keep the event loop alive * (ev_unref) but makes sure that the loop keeps polling the system for * events. */ #include "uv.h" #include "task.h" #include <math.h> #define IDLE_COUNT 7 #define ITERATIONS 21 #define TIMEOUT 100 static uv_prepare_t prepare_1_handle; static uv_prepare_t prepare_2_handle; static uv_check_t check_handle; static uv_idle_t idle_1_handles[IDLE_COUNT]; static uv_idle_t idle_2_handle; static uv_timer_t timer_handle; static int loop_iteration = 0; static int prepare_1_cb_called = 0; static int prepare_1_close_cb_called = 0; static int prepare_2_cb_called = 0; static int prepare_2_close_cb_called = 0; static int check_cb_called = 0; static int check_close_cb_called = 0; static int idle_1_cb_called = 0; static int idle_1_close_cb_called = 0; static int idles_1_active = 0; static int idle_2_cb_called = 0; static int idle_2_close_cb_called = 0; static int idle_2_cb_started = 0; static int idle_2_is_active = 0; static void timer_cb(uv_timer_t* handle, int status) { ASSERT(handle == &timer_handle); ASSERT(status == 0); } static void idle_2_close_cb(uv_handle_t* handle) { LOG("IDLE_2_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&idle_2_handle); ASSERT(idle_2_is_active); idle_2_close_cb_called++; idle_2_is_active = 0; } static void idle_2_cb(uv_idle_t* handle, int status) { LOG("IDLE_2_CB\n"); ASSERT(handle == &idle_2_handle); ASSERT(status == 0); idle_2_cb_called++; uv_close((uv_handle_t*)handle, idle_2_close_cb); } static void idle_1_cb(uv_idle_t* handle, int status) { int r; LOG("IDLE_1_CB\n"); ASSERT(handle != NULL); ASSERT(status == 0); ASSERT(idles_1_active > 0); /* Init idle_2 and make it active */ if (!idle_2_is_active && !uv_is_closing((uv_handle_t*)&idle_2_handle)) { r = uv_idle_init(uv_default_loop(), &idle_2_handle); ASSERT(r == 0); r = uv_idle_start(&idle_2_handle, idle_2_cb); ASSERT(r == 0); idle_2_is_active = 1; idle_2_cb_started++; } idle_1_cb_called++; if (idle_1_cb_called % 5 == 0) { r = uv_idle_stop((uv_idle_t*)handle); ASSERT(r == 0); idles_1_active--; } } static void idle_1_close_cb(uv_handle_t* handle) { LOG("IDLE_1_CLOSE_CB\n"); ASSERT(handle != NULL); idle_1_close_cb_called++; } static void prepare_1_close_cb(uv_handle_t* handle) { LOG("PREPARE_1_CLOSE_CB"); ASSERT(handle == (uv_handle_t*)&prepare_1_handle); prepare_1_close_cb_called++; } static void check_close_cb(uv_handle_t* handle) { LOG("CHECK_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&check_handle); check_close_cb_called++; } static void prepare_2_close_cb(uv_handle_t* handle) { LOG("PREPARE_2_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&prepare_2_handle); prepare_2_close_cb_called++; } static void check_cb(uv_check_t* handle, int status) { int i, r; LOG("CHECK_CB\n"); ASSERT(handle == &check_handle); ASSERT(status == 0); if (loop_iteration < ITERATIONS) { /* Make some idle watchers active */ for (i = 0; i < 1 + (loop_iteration % IDLE_COUNT); i++) { r = uv_idle_start(&idle_1_handles[i], idle_1_cb); ASSERT(r == 0); idles_1_active++; } } else { /* End of the test - close all handles */ uv_close((uv_handle_t*)&prepare_1_handle, prepare_1_close_cb); uv_close((uv_handle_t*)&check_handle, check_close_cb); uv_close((uv_handle_t*)&prepare_2_handle, prepare_2_close_cb); for (i = 0; i < IDLE_COUNT; i++) { uv_close((uv_handle_t*)&idle_1_handles[i], idle_1_close_cb); } /* This handle is closed/recreated every time, close it only if it is */ /* active.*/ if (idle_2_is_active) { uv_close((uv_handle_t*)&idle_2_handle, idle_2_close_cb); } } check_cb_called++; } static void prepare_2_cb(uv_prepare_t* handle, int status) { int r; LOG("PREPARE_2_CB\n"); ASSERT(handle == &prepare_2_handle); ASSERT(status == 0); /* prepare_2 gets started by prepare_1 when (loop_iteration % 2 == 0), */ /* and it stops itself immediately. A started watcher is not queued */ /* until the next round, so when this callback is made */ /* (loop_iteration % 2 == 0) cannot be true. */ ASSERT(loop_iteration % 2 != 0); r = uv_prepare_stop((uv_prepare_t*)handle); ASSERT(r == 0); prepare_2_cb_called++; } static void prepare_1_cb(uv_prepare_t* handle, int status) { int r; LOG("PREPARE_1_CB\n"); ASSERT(handle == &prepare_1_handle); ASSERT(status == 0); if (loop_iteration % 2 == 0) { r = uv_prepare_start(&prepare_2_handle, prepare_2_cb); ASSERT(r == 0); } prepare_1_cb_called++; loop_iteration++; printf("Loop iteration %d of %d.\n", loop_iteration, ITERATIONS); } TEST_IMPL(loop_handles) { int i; int r; r = uv_prepare_init(uv_default_loop(), &prepare_1_handle); ASSERT(r == 0); r = uv_prepare_start(&prepare_1_handle, prepare_1_cb); ASSERT(r == 0); r = uv_check_init(uv_default_loop(), &check_handle); ASSERT(r == 0); r = uv_check_start(&check_handle, check_cb); ASSERT(r == 0); /* initialize only, prepare_2 is started by prepare_1_cb */ r = uv_prepare_init(uv_default_loop(), &prepare_2_handle); ASSERT(r == 0); for (i = 0; i < IDLE_COUNT; i++) { /* initialize only, idle_1 handles are started by check_cb */ r = uv_idle_init(uv_default_loop(), &idle_1_handles[i]); ASSERT(r == 0); } /* don't init or start idle_2, both is done by idle_1_cb */ /* the timer callback is there to keep the event loop polling */ /* unref it as it is not supposed to keep the loop alive */ r = uv_timer_init(uv_default_loop(), &timer_handle); ASSERT(r == 0); r = uv_timer_start(&timer_handle, timer_cb, TIMEOUT, TIMEOUT); ASSERT(r == 0); uv_unref((uv_handle_t*)&timer_handle); r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); ASSERT(r == 0); ASSERT(loop_iteration == ITERATIONS); ASSERT(prepare_1_cb_called == ITERATIONS); ASSERT(prepare_1_close_cb_called == 1); ASSERT(prepare_2_cb_called == floor(ITERATIONS / 2.0)); ASSERT(prepare_2_close_cb_called == 1); ASSERT(check_cb_called == ITERATIONS); ASSERT(check_close_cb_called == 1); /* idle_1_cb should be called a lot */ ASSERT(idle_1_close_cb_called == IDLE_COUNT); ASSERT(idle_2_close_cb_called == idle_2_cb_started); ASSERT(idle_2_is_active == 0); MAKE_VALGRIND_HAPPY(); return 0; }
isc
ennis/autograph-pipelines
src/Engine/DebugOverlay.cpp
1
22413
#include <autograph/Engine/CVar.h> #include <autograph/Engine/DebugOverlay.h> #include <autograph/Engine/ImGuiUtils.h> #include <autograph/Engine/ImageUtils.h> #include <autograph/Engine/RenderUtils.h> #include <autograph/Engine/Shader.h> #include <autograph/Engine/imgui.h> #include <autograph/Gfx/GfxContext.h> #include <autograph/Gfx/Draw.h> #include <autograph/Gfx/GLHandle.h> #include <autograph/Gfx/Sampler.h> #include <autograph/Core/Support/Debug.h> #include <autograph/Core/Support/FileDialog.h> #include <autograph/Core/Support/ProjectRoot.h> #include <cinttypes> namespace ag { static const char *imageFileFilters = "png,jpg,jpeg,bmp,tga,psd,gif"; static constexpr Sampler::Desc nearestClampToEdge = Sampler::Desc{gl::NEAREST, gl::NEAREST, gl::CLAMP_TO_EDGE, gl::CLAMP_TO_EDGE, gl::CLAMP_TO_EDGE }; struct DebugOverlayGlobals { GPUPipeline textureViewShader = GPUPipeline{GPUPipelineType::Graphics, "shaders/default.lua:textureView"}; Sampler textureViewSampler; }; static DebugOverlayGlobals &getDebugGlobals() { static DebugOverlayGlobals g; static bool initialized = false; if (!initialized) { g.textureViewSampler = Sampler{ nearestClampToEdge }; initialized = true; } return g; } static const char *getInternalFormatName(gl::GLenum internalFormat) { switch (internalFormat) { case gl::R8: return "R8"; case gl::R8_SNORM: return "R8_SNORM"; case gl::R16: return "R16"; case gl::R16_SNORM: return "R16_SNORM"; case gl::RG8: return "RG8"; case gl::RG8_SNORM: return "RG8_SNORM"; case gl::RG16: return "RG16"; case gl::RG16_SNORM: return "RG16_SNORM"; case gl::R3_G3_B2: return "R3_G3_B2"; case gl::RGB4: return "RGB4"; case gl::RGB5: return "RGB5"; case gl::RGB8: return "RGB8"; case gl::RGB8_SNORM: return "RGB8_SNORM"; case gl::RGB10: return "RGB10"; case gl::RGB12: return "RGB12"; case gl::RGB16_SNORM: return "RGB16_SNORM"; case gl::RGBA2: return "RGBA2"; case gl::RGBA4: return "RGBA4"; case gl::RGB5_A1: return "RGB5_A1"; case gl::RGBA8: return "RGBA8"; case gl::RGBA8_SNORM: return "RGBA8_SNORM"; case gl::RGB10_A2: return "RGB10_A2"; case gl::RGB10_A2UI: return "RGB10_A2UI"; case gl::RGBA12: return "RGBA12"; case gl::RGBA16: return "RGBA16"; case gl::SRGB8: return "SRGB8"; case gl::SRGB8_ALPHA8: return "SRGB8_ALPHA8"; case gl::R16F: return "R16F"; case gl::RG16F: return "RG16F"; case gl::RGB16F: return "RGB16F"; case gl::RGBA16F: return "RGBA16F"; case gl::R32F: return "R32F"; case gl::RG32F: return "RG32F"; case gl::RGB32F: return "RGB32F"; case gl::RGBA32F: return "RGBA32F"; case gl::R11F_G11F_B10F: return "R11F_G11F_B10F"; case gl::RGB9_E5: return "RGB9_E5"; case gl::R8I: return "R8I"; case gl::R8UI: return "R8UI"; case gl::R16I: return "R16I"; case gl::R16UI: return "R16UI"; case gl::R32I: return "R32I"; case gl::R32UI: return "R32UI"; case gl::RG8I: return "RG8I"; case gl::RG8UI: return "RG8UI"; case gl::RG16I: return "RG16I"; case gl::RG16UI: return "RG16UI"; case gl::RG32I: return "RG32I"; case gl::RG32UI: return "RG32UI"; case gl::RGB8I: return "RGB8I"; case gl::RGB8UI: return "RGB8UI"; case gl::RGB16I: return "RGB16I"; case gl::RGB16UI: return "RGB16UI"; case gl::RGB32I: return "RGB32I"; case gl::RGB32UI: return "RGB32UI"; case gl::RGBA8I: return "RGBA8I"; case gl::RGBA8UI: return "RGBA8UI"; case gl::RGBA16I: return "RGBA16I"; case gl::RGBA16UI: return "RGBA16UI"; case gl::RGBA32I: return "RGBA32I"; case gl::RGBA32UI: return "RGBA32UI"; case gl::DEPTH_COMPONENT16: return "DEPTH_COMPONENT16"; case gl::DEPTH_COMPONENT24: return "DEPTH_COMPONENT24"; case gl::DEPTH_COMPONENT32: return "DEPTH_COMPONENT32"; case gl::DEPTH_COMPONENT32F: return "DEPTH_COMPONENT32F"; case gl::DEPTH24_STENCIL8: return "DEPTH24_STENCIL8"; case gl::DEPTH32F_STENCIL8: return "DEPTH32F_STENCIL8"; case gl::STENCIL_INDEX8: return "STENCIL_INDEX8"; case gl::COMPRESSED_RED: return "COMPRESSED_RED"; case gl::COMPRESSED_RG: return "COMPRESSED_RG"; case gl::COMPRESSED_RGB: return "COMPRESSED_RGB"; case gl::COMPRESSED_RGBA: return "COMPRESSED_RGBA"; case gl::COMPRESSED_SRGB: return "COMPRESSED_SRGB"; case gl::COMPRESSED_SRGB_ALPHA: return "COMPRESSED_SRGB_ALPHA"; case gl::COMPRESSED_RED_RGTC1: return "COMPRESSED_RED_RGTC1"; case gl::COMPRESSED_SIGNED_RED_RGTC1: return "COMPRESSED_SIGNED_RED_RGTC1"; case gl::COMPRESSED_RG_RGTC2: return "COMPRESSED_RG_RGTC2"; case gl::COMPRESSED_SIGNED_RG_RGTC2: return "COMPRESSED_SIGNED_RG_RGTC2"; case gl::COMPRESSED_RGBA_BPTC_UNORM: return "COMPRESSED_RGBA_BPTC_UNORM"; case gl::COMPRESSED_SRGB_ALPHA_BPTC_UNORM: return "COMPRESSED_SRGB_ALPHA_BPTC_UNORM"; case gl::COMPRESSED_RGB_BPTC_SIGNED_FLOAT: return "COMPRESSED_RGB_BPTC_SIGNED_FLOAT"; case gl::COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT: return "COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT"; case gl::COMPRESSED_RGB_S3TC_DXT1_EXT: return "COMPRESSED_RGB_S3TC_DXT1_EXT"; case gl::COMPRESSED_SRGB_S3TC_DXT1_EXT: return "COMPRESSED_SRGB_S3TC_DXT1_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT1_EXT: return "COMPRESSED_RGBA_S3TC_DXT1_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT3_EXT: return "COMPRESSED_RGBA_S3TC_DXT3_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT5_EXT: return "COMPRESSED_RGBA_S3TC_DXT5_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; default: return "<unknown GL internal format>"; } } static ImageFormat GLInternalFormatToImageFormat(gl::GLenum glfmt) { switch (glfmt) { case gl::SRGB8: return ImageFormat::R8G8B8_SRGB; case gl::SRGB8_ALPHA8: return ImageFormat::R8G8B8A8_SRGB; case gl::RGBA16F: return ImageFormat::R16G16B16A16_SFLOAT; case gl::RG16F: return ImageFormat::R16G16_SFLOAT; default: return ImageFormat::R8G8B8A8_SRGB; } } static void beginFixedTooltip(const char *id) { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::GetStyle().Colors[ImGuiCol_PopupBg]); ImGui::Begin(id, nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_NoResize); } static void endFixedTooltip() { ImGui::End(); ImGui::PopStyleColor(); } static void texturePreview(gl::GLuint textureObj, int w, int h, float lod, int xoffset, int yoffset, float zoomLevel, bool mirror = false, float range_min = 0.0f, float range_max = 1.0f) { ImGui::Dummy(ImVec2{(float)w, (float)h}); auto pos = ImGui::GetItemRectMin(); auto size = ImGui::GetItemRectSize(); gui::customRendering([=](const ImDrawList *parentList, const ImDrawCmd *cmd) { auto& fb = getGfxContext().getDefaultFramebuffer(); auto fb_width = fb.width(); auto fb_height = fb.height(); float uv_l = (float)xoffset / (float)w; float uv_t = 1.0f / zoomLevel; float uv_r = 1.0f / zoomLevel; float uv_b = (float)yoffset / (float)h; if (mirror) std::swap(uv_t, uv_b); ag::drawRect(fb, pos.x, pos.y, pos.x + size.x, pos.y + size.y, uv_l, uv_t, uv_r, uv_b, getDebugGlobals().textureViewShader, bind::scissor(0, (int)cmd->ClipRect.x, (int)(fb_height - cmd->ClipRect.w), (int)(cmd->ClipRect.z - cmd->ClipRect.x), (int)(cmd->ClipRect.w - cmd->ClipRect.y)), bind::texture(0, textureObj, getDebugGlobals().textureViewSampler.object()), bind::uniform_float("uLod", lod), bind::uniform_vec2("uRange", vec2(range_min, range_max)), bind::uniform_vec4("uBorder", vec4(0.1f, 0.1f, 0.1f, 1.0f))); }); } static void GLTextureViewWindow(gl::GLuint textureObj, int w, int h, gl::GLenum internalFormat, bool &opened) { auto internalFormatName = getInternalFormatName(internalFormat); auto windowName = fmt::format("Texture object {} ({}x{} {})", textureObj, w, h, internalFormatName); if (ImGui::Begin(windowName.c_str(), &opened, ImGuiWindowFlags_MenuBar)) { // ImGui::Image(reinterpret_cast<ImTextureID>(textureObj), ImVec2{ (float)w, // (float)h }); float range_min = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("range_min"), 0.0f); float range_max = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("range_max"), 1.0f); float zoomLevel = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("zoom_level"), 1.0f); bool mirror = ImGui::GetStateStorage()->GetBool(ImGui::GetID("mirror"), false); int xoff = ImGui::GetStateStorage()->GetInt(ImGui::GetID("xoff"), 0); int yoff = ImGui::GetStateStorage()->GetInt(ImGui::GetID("yoff"), 0); texturePreview(textureObj, w, h, 1.0f, xoff, yoff, zoomLevel, mirror, range_min, range_max); vec4 pixel; int mx, my; bool hovered = false; if (ImGui::IsItemHovered()) { hovered = true; auto pos = ImGui::GetMousePos(); auto ref = ImGui::GetItemRectMin(); mx = glm::clamp((int)(pos.x - ref.x), 0, w - 1); my = glm::clamp((int)(pos.y - ref.y), 0, h - 1); // TODO handle integer textures gl::GetTextureSubImage(textureObj, 0, mx, my, 0, 1, 1, 1, gl::RGBA, gl::FLOAT, 4 * 4, &pixel); } if (ImGui::BeginMenuBar()) { if (ImGui::Button(ICON_FA_SEARCH_MINUS)) { zoomLevel /= 2; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_SEARCH_PLUS)) { zoomLevel *= 2; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_ARROWS_ALT)) { zoomLevel = 1.0f; } ImGui::SameLine(); ImGui::Checkbox("Mirror", &mirror); ImGui::SameLine(); ImGui::PushItemWidth(130.0f); float zoomLevelPercent = zoomLevel * 100.0f; ImGui::SliderFloat("Zoom", &zoomLevelPercent, 1.0f, 400.0f, "%g %%"); zoomLevel = zoomLevelPercent / 100.0f; ImGui::SameLine(); ImGui::SliderFloat("Min", &range_min, 0.0f, 1.0f); ImGui::SameLine(); ImGui::SliderFloat("Max", &range_max, 0.0f, 1.0f); ImGui::PopItemWidth(); ImGui::SameLine(); if (hovered) { ImGui::PushItemWidth(-1.0f); ImGui::Text("%05i,%05i => [%.03f, %.03f, %.03f, %.03f]", mx, my, pixel.r, pixel.g, pixel.b, pixel.a); ImGui::PopItemWidth(); } ImGui::EndMenuBar(); } ImGui::GetStateStorage()->SetBool(ImGui::GetID("mirror"), mirror); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("range_min"), range_min); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("range_max"), range_max); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("zoom_level"), zoomLevel); ImGui::GetStateStorage()->SetInt(ImGui::GetID("xoff"), xoff); ImGui::GetStateStorage()->SetInt(ImGui::GetID("yoff"), yoff); } ImGui::End(); } static void saveGLTexture(const char *path, gl::GLuint textureObj, int w, int h, gl::GLenum internalFormat) { ImageFormat fmt; gl::GLenum extFormat; gl::GLenum components; int size; switch (internalFormat) { case gl::RGBA16F: fmt = ImageFormat::R16G16B16A16_SFLOAT; extFormat = gl::HALF_FLOAT; components = gl::RGBA; size = 8; break; case gl::RG16F: fmt = ImageFormat::R16G16_SFLOAT; extFormat = gl::HALF_FLOAT; components = gl::RG; size = 4; break; case gl::RGBA8_SNORM: fmt = ImageFormat::R8G8B8A8_SNORM; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; case gl::RGBA8: fmt = ImageFormat::R8G8B8A8_UNORM; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; case gl::SRGB8_ALPHA8: fmt = ImageFormat::R8G8B8A8_SRGB; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; default: errorMessage("saveGLTexture: texture format not supported ({})", getInternalFormatName(internalFormat)); return; } // allocate space for image auto bufsize = w * h * size; std::vector<char> pixels(bufsize); gl::GetTextureSubImage(textureObj, 0, 0, 0, 0, w, h, 1, components, extFormat, bufsize, pixels.data()); saveImageByPath(path, pixels.data(), w, h, fmt, fmt); } static void GLTextureGUI(gl::GLuint textureObj) { int w, h; gl::GLint internalFormat; gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_WIDTH, &w); gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_HEIGHT, &h); gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_INTERNAL_FORMAT, &internalFormat); auto imguiState = ImGui::GetStateStorage(); auto id = ImGui::GetID("texview"); bool opened = imguiState->GetBool(id); if (ImGui::Button("Toggle view texture")) { opened = true; } if (opened) { GLTextureViewWindow(textureObj, w, h, internalFormat, opened); } imguiState->SetBool(id, opened); if (ImGui::Button("Load texture...")) { auto file = openFileDialog(imageFileFilters, getProjectRootDirectory().c_str()); if (file) { try { auto img = loadImage(file->c_str()); if (img.desc.width == w && img.desc.height == h) { // dimensions match, continue // as usual, let OpenGL do the pixel conversion gl::TextureSubImage2D(textureObj, 0, 0, 0, w, h, gl::RGBA, gl::UNSIGNED_INT_8_8_8_8, img.data.get()); } else { errorMessage("Error loading texture: mismatched dimensions ({}x{})", img.desc.width, img.desc.height); } } catch (std::exception &e) { errorMessage("Error loading image file: {}", e.what()); } } } ImGui::SameLine(); if (ImGui::Button("Save texture...")) { auto file = saveFileDialog(imageFileFilters, getProjectRootDirectory().c_str()); if (file) { try { // allocate space for image saveGLTexture(file->c_str(), textureObj, w, h, internalFormat); } catch (std::exception &e) { errorMessage("Error saving image file: {}", e.what()); } } } // auto& defaultFbo = gl::getDefaultFramebuffer(); // int screenW = defaultFbo.width(); // int screenH = defaultFbo.height(); // getRenderUtils().drawSprite(gl::getDefaultFramebuffer(), 0.0f, 0.0f, // (float)w, (float)h, textureObj); } static void GLObjectListGUI() { ImGui::Begin("GL objects"); static int selected = -1; auto objCount = getGLObjectCount(); if (selected >= objCount) selected = objCount - 1; ////////////////////////////////////////// ImGui::BeginChild("Object list", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, ImGui::GetContentRegionAvail().y), true, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(3); ImGui::Text("Object ID"); ImGui::NextColumn(); ImGui::Text("Type"); ImGui::NextColumn(); ImGui::Text("Frame created"); ImGui::NextColumn(); ImGui::Separator(); for (int i = 0; i < objCount; ++i) { ImGui::PushID(i); auto obj = getGLObjectData(i); auto objStr = fmt::format("({}):{}", obj->type, obj->obj); bool isSelected = selected == i; if (ImGui::Selectable(objStr.c_str(), &isSelected, ImGuiSelectableFlags_SpanAllColumns)) { selected = i; } ImGui::NextColumn(); ImGui::Text("%s", getGLObjectTypeName(obj->type)); ImGui::NextColumn(); ImGui::Text("%" PRIi64, obj->creationFrame); ImGui::NextColumn(); ImGui::PopID(); } ImGui::EndChild(); ////////////////////////////////////////// if (selected != -1) { ImGui::SameLine(); ImGui::BeginChild("Object GUI", ImVec2(0, 300), false); auto obj = getGLObjectData(selected); if (obj->type == gl::TEXTURE) GLTextureGUI(obj->obj); ImGui::EndChild(); } ImGui::End(); } using NameValuePair = std::pair<const char *, gl::GLenum>; static void ComboGLenum(const char *label, gl::GLenum *outValue, span<const NameValuePair> values) { auto enumToIndex = [&](gl::GLenum e) { int i = 0; for (auto &p : values) { if (p.second == e) return i; ++i; } return -1; }; int curIdx = enumToIndex(*outValue); ImGui::Combo(label, &curIdx, [](void *data, int idx, const char **out_text) { auto values = *static_cast<span<NameValuePair> *>(data); if (idx < (int)values.size()) { *out_text = values[idx].first; return true; } return false; }, &values, (int)values.size()); *outValue = values[curIdx].second; } /*static void pipelineStateGUI(PipelineState *ps) { ////////////////////////////////////////////////////// // Depth-stencil if (ImGui::CollapsingHeader("Depth-stencil state")) { ImGui::Checkbox("Depth test enabled", &ps->drawStates.depthStencilState.depthTestEnable); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("gl::Enable(gl::DEPTH_TEST)"); } ImGui::Checkbox("Depth write enabled", &ps->drawStates.depthStencilState.depthWriteEnable); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Write to the depth buffer"); } static const NameValuePair depthTestFuncNames[] = { {"gl::NEVER", gl::NEVER}, {"gl::LESS", gl::LESS}, {"gl::EQUAL", gl::EQUAL}, {"gl::LEQUAL", gl::LEQUAL}, {"gl::GREATER", gl::GREATER}, {"gl::NOTEQUAL", gl::NOTEQUAL}, {"gl::GEQUAL", gl::GEQUAL}, {"gl::ALWAYS", gl::ALWAYS}}; ComboGLenum("Depth test func", &ps->drawStates.depthStencilState.depthTestFunc, depthTestFuncNames); } ////////////////////////////////////////////////////// // Rasterizer if (ImGui::CollapsingHeader("Rasterizer state")) { static const NameValuePair fillModeNames[] = {{"gl::FILL", gl::FILL}, {"gl::LINE", gl::LINE}}; ComboGLenum("Fill mode", &ps->drawStates.rasterizerState.fillMode, fillModeNames); } ////////////////////////////////////////////////////// // Viewports if (ImGui::CollapsingHeader("Viewports")) { ImGui::Columns(5); ImGui::Text("Viewport index"); ImGui::NextColumn(); ImGui::Text("X"); ImGui::NextColumn(); ImGui::Text("Y"); ImGui::NextColumn(); ImGui::Text("W"); ImGui::NextColumn(); ImGui::Text("H"); ImGui::NextColumn(); ImGui::Separator(); for (int i = 0; i < 8; ++i) { ImGui::PushID(i); ImGui::Text("%i", i); ImGui::NextColumn(); ImGui::InputFloat("##X", &ps->drawStates.viewports[i].x); ImGui::NextColumn(); ImGui::InputFloat("##Y", &ps->drawStates.viewports[i].y); ImGui::NextColumn(); ImGui::InputFloat("##Z", &ps->drawStates.viewports[i].w); ImGui::NextColumn(); ImGui::InputFloat("##W", &ps->drawStates.viewports[i].h); ImGui::NextColumn(); ImGui::Separator(); ImGui::PopID(); } ImGui::Columns(1); } ////////////////////////////////////////////////////// // Shader sources if (ImGui::CollapsingHeader("Shader sources")) { if (ImGui::Button("Recompile")) { ps->shouldRecompile = true; } if (ImGui::Button("VS")) ImGui::OpenPopup("Vertex Shader"); ImGui::SameLine(); if (ImGui::Button("FS")) ImGui::OpenPopup("Fragment Shader"); ImGui::SameLine(); if (ImGui::Button("GS")) ImGui::OpenPopup("Geometry Shader"); ImGui::SameLine(); if (ImGui::Button("TCS")) ImGui::OpenPopup("Tess Control Shader"); ImGui::SameLine(); if (ImGui::Button("TES")) ImGui::OpenPopup("Tess Eval Shader"); if (ImGui::Button("CS")) ImGui::OpenPopup("Compute Shader"); ImVec2 shaderEditWinSize = ImVec2{200.0f, 400.0f}; size_t bufSize = 100000; auto shaderEditPopup = [&](const char *label, std::string &source) { if (ImGui::BeginResizablePopup(label, shaderEditWinSize)) { ImGui::PushItemWidth(-1); gui::inputTextMultilineString("", source, bufSize); ImGui::PopItemWidth(); ImGui::EndPopup(); } }; shaderEditPopup("Vertex Shader", ps->vertexShaderSource); shaderEditPopup("Fragment Shader", ps->fragmentShaderSource); shaderEditPopup("Geometry Shader", ps->geometryShaderSource); shaderEditPopup("Tess Control Shader", ps->tessControlShaderSource); shaderEditPopup("Tess Eval Shader", ps->tessEvalShaderSource); shaderEditPopup("Compute Shader", ps->computeShaderSource); } } static void pipelineStatesGUI() { ImGui::Begin("Shaders"); auto &pipelineStateCache = getPipelineStateCache(); if (ImGui::Button("Reload all (Ctrl+F5)")) { pipelineStateCache.reloadAll(); } int numPS = pipelineStateCache.getCachedPipelineStateCount(); for (int i = 0; i < numPS; ++i) { ImGui::PushID(i); auto ps = pipelineStateCache.getCachedPipelineState(i); if (ImGui::CollapsingHeader( fmt::format("#{} | {}", i, ps->origShaderID.c_str()).c_str())) { ImGui::Indent(20.0f); pipelineStateGUI(ps); ImGui::Unindent(20.0f); } ImGui::PopID(); } ImGui::End(); }*/ void drawDebugOverlay(double dt) { beginFixedTooltip("frame"); ImGui::TextDisabled("Frame time: %.06f ms (%.02f FPS)", dt * 1000.0f, 1.0f / dt); endFixedTooltip(); //pipelineStatesGUI(); GLObjectListGUI(); showCVarGui(); } } // namespace ag
mit
nevik-xx/psl1ght
tools/scetool/self.cpp
1
31118
/* * Copyright (c) 2011-2013 by naehrwert * This file is released under the GPLv2. */ #include <stdio.h> #include <stdlib.h> #include "types.h" #include "config.h" #include "util.h" #include "sce.h" #include "sce_inlines.h" #include "self.h" #include "elf.h" #include "elf_inlines.h" #include "tables.h" #include "sha1.h" #include "np.h" static void _get_shdr_flags(s8 *str, u64 flags) { memset(str, '-', 3); str[3] = 0; if(flags & SHF_WRITE) str[0] = 'W'; if(flags & SHF_ALLOC) str[1] = 'A'; if(flags & SHF_EXECINSTR) str[2] = 'E'; } static void _get_phdr_flags(s8 *str, u64 flags) { memset(str, '-', 3); str[3] = 0; if(flags & PF_X) str[0] = 'X'; if(flags & PF_W) str[1] = 'W'; if(flags & PF_R) str[2] = 'R'; } void _print_self_header(FILE *fp, self_header_t *h) { fprintf(fp, "[*] SELF Header:\n"); fprintf(fp, " Header Type 0x%016llX\n", h->header_type); fprintf(fp, " App Info Offset 0x%016llX\n", h->app_info_offset); fprintf(fp, " ELF Offset 0x%016llX\n", h->elf_offset); fprintf(fp, " PH Offset 0x%016llX\n", h->phdr_offset); fprintf(fp, " SH Offset 0x%016llX\n", h->shdr_offset); fprintf(fp, " Section Info Offset 0x%016llX\n", h->section_info_offset); fprintf(fp, " SCE Version Offset 0x%016llX\n", h->sce_version_offset); fprintf(fp, " Control Info Offset 0x%016llX\n", h->control_info_offset); fprintf(fp, " Control Info Size 0x%016llX\n", h->control_info_size); //fprintf(fp, " padding 0x%016llX\n", h->padding); } void _print_app_info(FILE *fp, app_info_t *ai) { const s8 *name; fprintf(fp, "[*] Application Info:\n"); name = _get_name(_auth_ids, ai->auth_id); if(name != NULL) { fprintf(fp, " Auth-ID "); _PRINT_RAW(fp, "0x%016llX ", ai->auth_id); fprintf(fp, "[%s]\n", name); } else fprintf(fp, " Auth-ID 0x%016llX\n", ai->auth_id); name = _get_name(_vendor_ids, ai->vendor_id); if(name != NULL) { fprintf(fp, " Vendor-ID "); _PRINT_RAW(fp, "0x%08X ", ai->vendor_id); fprintf(fp, "[%s]\n", name); } else fprintf(fp, " Vendor-ID 0x%08X\n", ai->vendor_id); name = _get_name(_self_types, ai->self_type); if(name != NULL) fprintf(fp, " SELF-Type [%s]\n", name); else fprintf(fp, " SELF-Type 0x%08X\n", ai->self_type); fprintf(fp, " Version %s\n", sce_version_to_str(ai->version)); //fprintf(fp, " padding 0x%016llX\n", ai->padding); } void _print_section_info_header(FILE *fp) { fprintf(fp, "[*] Section Infos:\n"); fprintf(fp, " Idx Offset Size Compressed unk0 unk1 Encrypted\n"); } void _print_section_info(FILE *fp, section_info_t *si, u32 idx) { fprintf(fp, " %03d %08X %08X %s %08X %08X %s\n", idx, (u32)si->offset, (u32)si->size, si->compressed == 2 ? "[YES]" : "[NO ]", si->unknown_0, si->unknown_1, si->encrypted == 1 ? "[YES]" : "[NO ]"); } void _print_sce_version(FILE *fp, sce_version_t *sv) { fprintf(fp, "[*] SCE Version:\n"); fprintf(fp, " Header Type 0x%08X\n", sv->header_type); fprintf(fp, " Present [%s]\n", sv->present == SCE_VERSION_PRESENT ? "TRUE" : "FALSE"); fprintf(fp, " Size 0x%08X\n", sv->size); fprintf(fp, " unknown_3 0x%08X\n", sv->unknown_3); } void _print_control_info(FILE *fp, control_info_t *ci) { const s8 *name; fprintf(fp, "[*] Control Info\n"); name = _get_name(_control_info_types, ci->type); if(name != NULL) fprintf(fp, " Type %s\n", name); else fprintf(fp, " Type 0x%08X\n", ci->type); fprintf(fp, " Size 0x%08X\n", ci->size); fprintf(fp, " Next [%s]\n", ci->next == 1 ? "TRUE" : "FALSE"); switch(ci->type) { case CONTROL_INFO_TYPE_FLAGS: _hexdump(fp, " Flags", 0, (u8 *)ci + sizeof(control_info_t), ci->size - sizeof(control_info_t), FALSE); break; case CONTROL_INFO_TYPE_DIGEST: if(ci->size == 0x30) { ci_data_digest_30_t *dig = (ci_data_digest_30_t *)((u8 *)ci + sizeof(control_info_t)); _hexdump(fp, " Digest", 0, dig->digest, 20, FALSE); } else if(ci->size == 0x40) { ci_data_digest_40_t *dig = (ci_data_digest_40_t *)((u8 *)ci + sizeof(control_info_t)); _es_ci_data_digest_40(dig); _hexdump(fp, " Digest 1 ", 0, dig->digest1, 20, FALSE); _hexdump(fp, " Digest 2 ", 0, dig->digest2, 20, FALSE); if(dig->fw_version != 0) fprintf(fp, " FW Version %d [%02d.%02d]\n", (u32)dig->fw_version, ((u32)dig->fw_version)/10000, (((u32)dig->fw_version)%10000)/100); } break; case CONTROL_INFO_TYPE_NPDRM: { ci_data_npdrm_t *np = (ci_data_npdrm_t *)((u8 *)ci + sizeof(control_info_t)); //Was already fixed in decrypt_header. //_es_ci_data_npdrm(np); fprintf(fp, " Magic 0x%08X [%s]\n", np->magic, (np->magic == NP_CI_MAGIC ? "OK" : "ERROR")); fprintf(fp, " unknown_0 0x%08X\n", np->unknown_0); fprintf(fp, " Licence Type 0x%08X\n", np->license_type); fprintf(fp, " App Type 0x%08X\n", np->app_type); fprintf(fp, " ContentID %s\n", np->content_id); _hexdump(fp, " Random Pad ", 0, np->rndpad, 0x10, FALSE); _hexdump(fp, " CID_FN Hash ", 0, np->hash_cid_fname, 0x10, FALSE); _hexdump(fp, " CI Hash ", 0, np->hash_ci, 0x10, FALSE); fprintf(fp, " unknown_1 0x%016llX\n", np->unknown_1); fprintf(fp, " unknown_2 0x%016llX\n", np->unknown_2); } break; } } static void _print_cap_flags_flags(FILE *fp, oh_data_cap_flags_t *cf) { if(cf->flags & 0x01) fprintf(fp, "0x01 "); if(cf->flags & 0x02) fprintf(fp, "0x02 "); if(cf->flags & 0x04) fprintf(fp, "0x04 "); if(cf->flags & CAP_FLAG_REFTOOL) fprintf(fp, "REFTOOL "); if(cf->flags & CAP_FLAG_DEBUG) fprintf(fp, "DEBUG "); if(cf->flags & CAP_FLAG_RETAIL) fprintf(fp, "RETAIL "); if(cf->flags & CAP_FLAG_SYSDBG) fprintf(fp, "SYSDBG "); } void _print_opt_header(FILE *fp, opt_header_t *oh) { const s8 *name; fprintf(fp, "[*] Optional Header\n"); name = _get_name(_optional_header_types, oh->type); if(name != NULL) fprintf(fp, " Type %s\n", name); else fprintf(fp, " Type 0x%08X\n", oh->type); fprintf(fp, " Size 0x%08X\n", oh->size); fprintf(fp, " Next [%s]\n", oh->next == 1 ? "TRUE" : "FALSE"); switch(oh->type) { case OPT_HEADER_TYPE_CAP_FLAGS: { oh_data_cap_flags_t *cf = (oh_data_cap_flags_t *)((u8 *)oh + sizeof(opt_header_t)); _IF_RAW(_hexdump(fp, " Flags", 0, (u8 *)cf, sizeof(oh_data_cap_flags_t), FALSE)); _es_oh_data_cap_flags(cf); fprintf(fp, " unknown_3 0x%016llX\n", cf->unk3); fprintf(fp, " unknown_4 0x%016llX\n", cf->unk4); fprintf(fp, " Flags 0x%016llX [ ", cf->flags); _print_cap_flags_flags(fp, cf); fprintf(fp, "]\n"); fprintf(fp, " unknown_6 0x%08X\n", cf->unk6); fprintf(fp, " unknown_7 0x%08X\n", cf->unk7); } break; #ifdef CONFIG_DUMP_INDIV_SEED case OPT_HEADER_TYPE_INDIV_SEED: { u8 *is = (u8 *)oh + sizeof(opt_header_t); _hexdump(fp, " Seed", 0, is, oh->size - sizeof(opt_header_t), TRUE); } break; #endif } } void _print_elf32_ehdr(FILE *fp, Elf32_Ehdr *h) { const s8 *name; fprintf(fp, "[*] ELF32 Header:\n"); name = _get_name(_e_types, h->e_type); if(name != NULL) fprintf(fp, " Type [%s]\n", name); else fprintf(fp, " Type 0x%04X\n", h->e_type); name = _get_name(_e_machines, h->e_machine); if(name != NULL) fprintf(fp, " Machine [%s]\n", name); else fprintf(fp, " Machine 0x%04X\n", h->e_machine); fprintf(fp, " Version 0x%08X\n", h->e_version); fprintf(fp, " Entry 0x%08X\n", h->e_entry); fprintf(fp, " Program Headers Offset 0x%08X\n", h->e_phoff); fprintf(fp, " Section Headers Offset 0x%08X\n", h->e_shoff); fprintf(fp, " Flags 0x%08X\n", h->e_flags); fprintf(fp, " Program Headers Count %04d\n", h->e_phnum); fprintf(fp, " Section Headers Count %04d\n", h->e_shnum); fprintf(fp, " SH String Index %04d\n", h->e_shstrndx); } void _print_elf64_ehdr(FILE *fp, Elf64_Ehdr *h) { const s8 *name; fprintf(fp, "[*] ELF64 Header:\n"); name = _get_name(_e_types, h->e_type); if(name != NULL) fprintf(fp, " Type [%s]\n", name); else fprintf(fp, " Type 0x%04X\n", h->e_type); name = _get_name(_e_machines, h->e_machine); if(name != NULL) fprintf(fp, " Machine [%s]\n", name); else fprintf(fp, " Machine 0x%04X\n", h->e_machine); fprintf(fp, " Version 0x%08X\n", h->e_version); fprintf(fp, " Entry 0x%016llX\n", h->e_entry); fprintf(fp, " Program Headers Offset 0x%016llX\n", h->e_phoff); fprintf(fp, " Section Headers Offset 0x%016llX\n", h->e_shoff); fprintf(fp, " Flags 0x%08X\n", h->e_flags); fprintf(fp, " Program Headers Count %04d\n", h->e_phnum); fprintf(fp, " Section Headers Count %04d\n", h->e_shnum); fprintf(fp, " SH String Index %04d\n", h->e_shstrndx); } void _print_elf32_shdr_header(FILE *fp) { fprintf(fp, "[*] ELF32 Section Headers:\n"); fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n"); } void _print_elf32_shdr(FILE *fp, Elf32_Shdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_shdr_flags(flags, h->sh_flags); fprintf(fp, " %03d %04X ", idx, h->sh_name); name = _get_name(_sh_types, h->sh_type); if(name != NULL) fprintf(fp, "%-13s ", name); else fprintf(fp, "%08X ", h->sh_type); fprintf(fp, "%s %05X %05X %05X %02X %05X %03d\n", flags, h->sh_addr, h->sh_offset, h->sh_size, h->sh_entsize, h->sh_addralign, h->sh_link); } void _print_elf64_shdr_header(FILE *fp) { fprintf(fp, "[*] ELF64 Section Headers:\n"); fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n"); } void _print_elf64_shdr(FILE *fp, Elf64_Shdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_shdr_flags(flags, h->sh_flags); fprintf(fp, " %03d %04X ", idx, h->sh_name); name = _get_name(_sh_types, h->sh_type); if(name != NULL) fprintf(fp, "%-13s ", name); else fprintf(fp, "%08X ", h->sh_type); fprintf(fp, "%s %08X %08X %08X %04X %08X %03d\n", flags, (u32)h->sh_addr, (u32)h->sh_offset, (u32)h->sh_size, (u32)h->sh_entsize, (u32)h->sh_addralign, h->sh_link); } void _print_elf32_phdr_header(FILE *fp) { fprintf(fp, "[*] ELF32 Program Headers:\n"); fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize Flags Align\n"); } void _print_elf32_phdr(FILE *fp, Elf32_Phdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_phdr_flags(flags, h->p_flags); fprintf(fp, " %03d ", idx); name = _get_name(_ph_types, h->p_type); if(name != NULL) fprintf(fp, "%-7s ", name); else fprintf(fp, "0x%08X ", h->p_type); fprintf(fp, "%05X %05X %05X %05X %05X %s %05X\n", h->p_offset, h->p_vaddr, h->p_paddr, h->p_filesz, h->p_memsz, flags, h->p_align); } void _print_elf64_phdr_header(FILE *fp) { fprintf(fp, "[*] ELF64 Program Headers:\n"); fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize PPU SPU RSX Align\n"); } void _print_elf64_phdr(FILE *fp, Elf64_Phdr *h, u32 idx) { const s8 *name; s8 ppu[4], spu[4], rsx[4]; _get_phdr_flags(ppu, h->p_flags); _get_phdr_flags(spu, h->p_flags >> 20); _get_phdr_flags(rsx, h->p_flags >> 24); fprintf(fp, " %03d ", idx); name = _get_name(_ph_types, h->p_type); if(name != NULL) fprintf(fp, "%-8s ", name); else fprintf(fp, "%08X ", h->p_type); fprintf(fp, "%08X %08X %08X %08X %08X %s %s %s %08X\n", (u32)h->p_offset, (u32)h->p_vaddr, (u32)h->p_paddr, (u32)h->p_filesz, (u32)h->p_memsz, ppu, spu, rsx, (u32)h->p_align); } BOOL self_print_info(FILE *fp, sce_buffer_ctxt_t *ctxt) { u32 i, self_type; const u8 *eident; //Check for SELF. if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF) return FALSE; //Print SELF infos. _print_self_header(fp, ctxt->self.selfh); _print_app_info(fp, ctxt->self.ai); if(ctxt->self.sv != NULL) _print_sce_version(fp, ctxt->self.sv); //Print control infos. if(ctxt->self.cis != NULL) LIST_FOREACH(iter, ctxt->self.cis) _print_control_info(fp, (control_info_t *)iter->value); //Print optional headers. if(ctxt->mdec == TRUE) { LIST_FOREACH(iter, ctxt->self.ohs) { #ifndef CONFIG_DUMP_INDIV_SEED if(((opt_header_t *)iter->value)->type != OPT_HEADER_TYPE_INDIV_SEED) _print_opt_header(fp, (opt_header_t *)iter->value); #else _print_opt_header(fp, (opt_header_t *)iter->value); #endif } } self_type = ctxt->self.ai->self_type; eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset; //SPU is 32 bit. if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32) { //32 bit ELF. Elf32_Ehdr *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _es_elf32_ehdr(eh); //Print section infos. _print_section_info_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_section_info(&ctxt->self.si[i]); _print_section_info(fp, &ctxt->self.si[i], i); } //Print ELF header. _print_elf32_ehdr(fp, eh); Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); //Print program headers. _print_elf32_phdr_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_elf32_phdr(&ph[i]); _print_elf32_phdr(fp, &ph[i], i); } if(eh->e_shnum > 0) { Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); //Print section headers. _print_elf32_shdr_header(fp); for(i = 0; i < eh->e_shnum; i++) { _es_elf32_shdr(&sh[i]); _print_elf32_shdr(fp, &sh[i], i); } } } else { //64 bit ELF. Elf64_Ehdr *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _es_elf64_ehdr(eh); //Print section infos. _print_section_info_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_section_info(&ctxt->self.si[i]); _print_section_info(fp, &ctxt->self.si[i], i); } //Print ELF header. _print_elf64_ehdr(stdout, eh); Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); //Print program headers. _print_elf64_phdr_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_elf64_phdr(&ph[i]); _print_elf64_phdr(fp, &ph[i], i); } if(eh->e_shnum > 0) { Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); //Print section headers. _print_elf64_shdr_header(fp); for(i = 0; i < eh->e_shnum; i++) { _es_elf64_shdr(&sh[i]); _print_elf64_shdr(fp, &sh[i], i); } } } return TRUE; } //TODO: maybe implement better. BOOL self_write_to_elf(sce_buffer_ctxt_t *ctxt, const s8 *elf_out) { FILE *fp; u32 i, self_type; const u8 *eident; //Check for SELF. if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF) return FALSE; if((fp = fopen(elf_out, "wb")) == NULL) return FALSE; self_type = ctxt->self.ai->self_type; eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset; //SPU is 32 bit. if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32) { #ifdef CONFIG_DUMP_INDIV_SEED /* //Print individuals seed. if(self_type == SELF_TYPE_ISO) { u8 *indiv_seed = (u8 *)ctxt->self.ish + sizeof(iseed_header_t); s8 ifile[256]; sprintf(ifile, "%s.indiv_seed.bin", elf_out); FILE *ifp = fopen(ifile, "wb"); fwrite(indiv_seed, sizeof(u8), ctxt->self.ish->size - sizeof(iseed_header_t), ifp); fclose(ifp); } */ #endif //32 bit ELF. Elf32_Ehdr ceh, *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _copy_es_elf32_ehdr(&ceh, eh); //Write ELF header. fwrite(eh, sizeof(Elf32_Ehdr), 1, fp); //Write program headers. Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); fwrite(ph, sizeof(Elf32_Phdr), ceh.e_phnum, fp); //Write program data. metadata_section_header_t *msh = ctxt->metash; for(i = 0; i < ctxt->metah->section_count; i++) { if(msh[i].type == METADATA_SECTION_TYPE_PHDR) { _es_elf32_phdr(&ph[msh[i].index]); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(u8), msh[i].data_size, fp); } } //Write section headers. if(ctxt->self.selfh->shdr_offset != 0) { Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); fseek(fp, ceh.e_shoff, SEEK_SET); fwrite(sh, sizeof(Elf32_Shdr), ceh.e_shnum, fp); } } else { //64 bit ELF. Elf64_Ehdr ceh, *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _copy_es_elf64_ehdr(&ceh, eh); //Write ELF header. fwrite(eh, sizeof(Elf64_Ehdr), 1, fp); //Write program headers. Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); fwrite(ph, sizeof(Elf64_Phdr), ceh.e_phnum, fp); //Write program data. metadata_section_header_t *msh = ctxt->metash; for(i = 0; i < ctxt->metah->section_count; i++) { if(msh[i].type == METADATA_SECTION_TYPE_PHDR) { if(msh[i].compressed == METADATA_SECTION_COMPRESSED) { _es_elf64_phdr(&ph[msh[i].index]); u8 *data = (u8 *)malloc(ph[msh[i].index].p_filesz); _zlib_inflate(ctxt->scebuffer + msh[i].data_offset, msh[i].data_size, data, ph[msh[i].index].p_filesz); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(data, sizeof(u8), ph[msh[i].index].p_filesz, fp); free(data); } else { _es_elf64_phdr(&ph[msh[i].index]); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(u8), msh[i].data_size, fp); } } } //Write section headers. if(ctxt->self.selfh->shdr_offset != 0) { Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); fseek(fp, ceh.e_shoff, SEEK_SET); fwrite(sh, sizeof(Elf64_Shdr), ceh.e_shnum, fp); } } fclose(fp); return TRUE; } /*! Static zero control flags. */ static u8 _static_control_flags[0x20] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /*! Static control digest1. */ static u8 _static_control_digest[0x14] = { 0x62, 0x7C, 0xB1, 0x80, 0x8A, 0xB9, 0x38, 0xE3, 0x2C, 0x8C, 0x09, 0x17, 0x08, 0x72, 0x6A, 0x57, 0x9E, 0x25, 0x86, 0xE4 }; static BOOL _create_control_infos(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { control_info_t *ci; u32 self_type = ctxt->self.ai->self_type; //Step 1. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: //TODO: <-- figure more out. { //Add control flags. ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_flags_t)); ci->type = CONTROL_INFO_TYPE_FLAGS; ci->size = sizeof(control_info_t) + sizeof(ci_data_flags_t); ci->next = 1; ci_data_flags_t *cif = (ci_data_flags_t *)((u8 *)ci + sizeof(control_info_t)); //Add default flags. if(sconf->ctrl_flags == NULL) memcpy(cif->data, _static_control_flags, 0x20); else memcpy(cif->data, sconf->ctrl_flags, 0x20); list_add_back(ctxt->self.cis, ci); } break; } //Step 2. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: { //Add digest 0x40. ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_digest_40_t)); ci->type = CONTROL_INFO_TYPE_DIGEST; ci->size = sizeof(control_info_t) + sizeof(ci_data_digest_40_t); if(self_type == SELF_TYPE_NPDRM) ci->next = 1; else ci->next = 0; ci_data_digest_40_t *cid = (ci_data_digest_40_t *)((u8 *)ci + sizeof(control_info_t)); memcpy(cid->digest1, _static_control_digest, 0x14); memset(cid->digest2, 0, 0x14); sha1(ctxt->makeself->elf, ctxt->makeself->elf_len, cid->digest2); //TODO: check that. if(self_type == SELF_TYPE_NPDRM) cid->fw_version = sce_hexver_to_decver(sconf->fw_version); else cid->fw_version = 0; //Fixup. _es_ci_data_digest_40(cid); list_add_back(ctxt->self.cis, ci); } break; } //Step 3. switch(self_type) { case SELF_TYPE_NPDRM: { //Add NPDRM control info. if(sconf->npdrm_config == NULL) return FALSE; ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_npdrm_t)); ci->type = CONTROL_INFO_TYPE_NPDRM; ci->size = sizeof(control_info_t) + sizeof(ci_data_npdrm_t); ci->next = 0; ci_data_npdrm_t *cinp = (ci_data_npdrm_t *)((u8 *)ci + sizeof(control_info_t)); //Create NPDRM control info. if(np_create_ci(sconf->npdrm_config, cinp) == FALSE) { free(ci); return FALSE; } list_add_back(ctxt->self.cis, ci); } break; } return TRUE; } static void _set_cap_flags(u32 self_type, oh_data_cap_flags_t *capf) { switch(self_type) { case SELF_TYPE_LV0: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_LV1: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_LV2: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_APP: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; capf->unk7 = 0x20000; break; case SELF_TYPE_ISO: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78; break; case SELF_TYPE_LDR: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78; break; case SELF_TYPE_NPDRM: capf->flags = CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x3B; capf->unk6 = 1; capf->unk7 = 0x2000; break; } _es_oh_data_cap_flags(capf); } static BOOL _create_optional_headers(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { opt_header_t *oh; u32 self_type = ctxt->self.ai->self_type; //Step 1. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: { //Add capability flags. oh = (opt_header_t *)malloc(sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t)); oh->type = OPT_HEADER_TYPE_CAP_FLAGS; oh->size = sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t); if(self_type == SELF_TYPE_ISO) oh->next = 1; else oh->next = 0; oh_data_cap_flags_t *capf = (oh_data_cap_flags_t *)((u8 *)oh + sizeof(opt_header_t)); //Add default flags. if(sconf->cap_flags == NULL) _set_cap_flags(self_type, capf); else memcpy(capf, sconf->cap_flags, 0x20); list_add_back(ctxt->self.ohs, oh); } break; } //Step 2. switch(self_type) { case SELF_TYPE_ISO: { //Add individuals seed. oh = (opt_header_t *)malloc(sizeof(opt_header_t) + 0x100); oh->type = OPT_HEADER_TYPE_INDIV_SEED; oh->size = sizeof(opt_header_t) + 0x100; oh->next = 0; u8 *is = (u8 *)oh + sizeof(opt_header_t); memset(is, 0, 0x100); #ifdef CONFIG_CUSTOM_INDIV_SEED if(sconf->indiv_seed != NULL) memcpy(is, sconf->indiv_seed, sconf->indiv_seed_size); #endif list_add_back(ctxt->self.ohs, oh); } break; } return TRUE; } static void _fill_sce_version(sce_buffer_ctxt_t *ctxt) { ctxt->self.sv->header_type = SUB_HEADER_TYPE_SCEVERSION; ctxt->self.sv->present = SCE_VERSION_NOT_PRESENT; ctxt->self.sv->size = sizeof(sce_version_t); ctxt->self.sv->unknown_3 = 0x00000000; } static void _add_phdr_section(sce_buffer_ctxt_t *ctxt, u32 p_type, u32 size, u32 idx) { //Offset gets set later. ctxt->self.si[idx].offset = 0; ctxt->self.si[idx].size = size; if(p_type == PT_LOAD || p_type == PT_PS3_PRX_RELOC || p_type == 0x700000A8) ctxt->self.si[idx].encrypted = 1; //Encrypted LOAD (?). else ctxt->self.si[idx].encrypted = 0; //No LOAD (?). ctxt->self.si[idx].compressed = SECTION_INFO_NOT_COMPRESSED; ctxt->self.si[idx].unknown_0 = 0; //Unknown. ctxt->self.si[idx].unknown_1 = 0; //Unknown. } static BOOL _add_shdrs_section(sce_buffer_ctxt_t *ctxt, u32 idx) { //Add a section for the section headers. if(ctxt->makeself->shdrs != NULL) { u32 shsize = ctxt->makeself->shsize; void *sec = _memdup(ctxt->makeself->shdrs, shsize); sce_add_data_section(ctxt, sec, shsize, FALSE); //Fill metadata section header. sce_set_metash(ctxt, METADATA_SECTION_TYPE_SHDR, FALSE, idx); return TRUE; } return FALSE; } static BOOL _build_self_32(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { u32 i; Elf32_Ehdr *ehdr; Elf32_Phdr *phdrs; //Elf32_Shdr *shdrs; //Copy ELF header. ctxt->makeself->ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr)); ctxt->makeself->ehsize = sizeof(Elf32_Ehdr); ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr)); _es_elf32_ehdr(ehdr); //Copy program headers. ctxt->makeself->phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum); ctxt->makeself->phsize = sizeof(Elf32_Phdr) * ehdr->e_phnum; phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum); //Copy section headers. if(ehdr->e_shnum != 0) { ctxt->makeself->shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum); ctxt->makeself->shsize = sizeof(Elf32_Shdr) * ehdr->e_shnum; //shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum); } //Allocate metadata section headers (one for each program header and one for the section headers). ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1)); //Copy sections, fill section infos and metadata section headers. ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum); for(i = 0; i < ehdr->e_phnum; i++) { _es_elf32_phdr(&phdrs[i]); void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz); //Never compress sections on SPU SELFs. sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, FALSE); //Add section info. _add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i); //Fill metadata section header. sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, phdrs[i].p_type == PT_LOAD ? TRUE : FALSE, i); } //Section info count. ctxt->makeself->si_cnt = ehdr->e_phnum; //Number of section infos that are present as data sections. ctxt->makeself->si_sec_cnt = ehdr->e_phnum; //Add a section for the section headers. if(sconf->add_shdrs == TRUE) if(_add_shdrs_section(ctxt, i) == TRUE) i++; //Metadata. ctxt->metah->section_count = i; return TRUE; } static BOOL _build_self_64(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { u32 i; Elf64_Ehdr *ehdr; Elf64_Phdr *phdrs; //Elf64_Shdr *shdrs; //Copy ELF header. ctxt->makeself->ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr)); ctxt->makeself->ehsize = sizeof(Elf64_Ehdr); ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr)); _es_elf64_ehdr(ehdr); //Copy program headers. ctxt->makeself->phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf64_Phdr) * ehdr->e_phnum); ctxt->makeself->phsize = sizeof(Elf64_Phdr) * ehdr->e_phnum; phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf64_Phdr) * ehdr->e_phnum); //Copy section headers. if(ehdr->e_shnum != 0) { ctxt->makeself->shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf64_Shdr) * ehdr->e_shnum); ctxt->makeself->shsize = sizeof(Elf64_Shdr) * ehdr->e_shnum; //shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf64_Shdr) * ehdr->e_shnum); } //Allocate metadata section headers (one for each program header and one for the section headers). ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1)); //Copy sections, fill section infos and metadata section headers. ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum); u32 loff = 0xFFFFFFFF, skip = 0; for(i = 0; i < ehdr->e_phnum; i++) { _es_elf64_phdr(&phdrs[i]); //Add section info. _add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i); //TODO: what if the size differs, why skip other program headers? //Fill metadata section header but skip identical program header offsets. if(sconf->skip_sections == TRUE && (phdrs[i].p_offset == loff || !(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8))) { const s8 *name = _get_name(_ph_types, phdrs[i].p_type); if(name != NULL) _LOG_VERBOSE("Skipped program header %-8s @ 0x%08X (0x%08X)\n", name, phdrs[i].p_offset, phdrs[i].p_filesz); else _LOG_VERBOSE("Skipped program header 0x%08X @ 0x%08X (0x%08X)\n", phdrs[i].p_type, phdrs[i].p_offset, phdrs[i].p_filesz); skip++; } else { void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz); //PPU sections may be compressed. sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, TRUE); sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, TRUE /*(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8) ? TRUE : FALSE*/, i - skip); } loff = phdrs[i].p_offset; } //Section info count. ctxt->makeself->si_cnt = ehdr->e_phnum; //Number of section infos that are present as data sections. ctxt->makeself->si_sec_cnt = i - skip; //Add a section for the section headers. if(sconf->add_shdrs == TRUE) if(_add_shdrs_section(ctxt, i - skip) == TRUE) i++; //Metadata. i -= skip; ctxt->metah->section_count = i; return TRUE; } BOOL self_build_self(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { //const u8 *eident; //Fill config values. ctxt->sceh->key_revision = sconf->key_revision; ctxt->self.ai->auth_id = sconf->auth_id; ctxt->self.ai->vendor_id = sconf->vendor_id; ctxt->self.ai->self_type = sconf->self_type; ctxt->self.ai->version = sconf->app_version; //Create control infos. if(_create_control_infos(ctxt, sconf) == FALSE) { printf("[*] Error: Could not create SELF control infos.\n"); return FALSE; } #ifdef CONFIG_CUSTOM_INDIV_SEED if(sconf->indiv_seed != NULL && sconf->self_type != SELF_TYPE_ISO) printf("[*] Warning: Skipping individuals seed for non-ISO SELF.\n"); #endif //Create optional headers. if(_create_optional_headers(ctxt, sconf) == FALSE) { printf("[*] Error: Could not create SELF optional headers.\n"); return FALSE; } //Set SCE version. _fill_sce_version(ctxt); //Check for 32 bit or 64 bit ELF. //eident = (const u8*)ctxt->makeself->elf; if(sconf->self_type == SELF_TYPE_LDR || sconf->self_type == SELF_TYPE_ISO /*|| eident[EI_CLASS] == ELFCLASS32*/) return _build_self_32(ctxt, sconf); return _build_self_64(ctxt, sconf); }
mit
aliakseis/LIII
src/3rdparty/torrent-rasterbar/bindings/python/src/fingerprint.cpp
1
1056
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/fingerprint.hpp> #include "boost_python.hpp" void bind_fingerprint() { using namespace boost::python; using namespace libtorrent; def("generate_fingerprint", &generate_fingerprint); #ifndef TORRENT_NO_DEPRECATE class_<fingerprint>("fingerprint", no_init) .def( init<char const*,int,int,int,int>( (arg("id"), "major", "minor", "revision", "tag") ) ) .def("__str__", &fingerprint::to_string) .def_readonly("name", &fingerprint::name) .def_readonly("major_version", &fingerprint::major_version) .def_readonly("minor_version", &fingerprint::minor_version) .def_readonly("revision_version", &fingerprint::revision_version) .def_readonly("tag_version", &fingerprint::tag_version) ; #endif }
mit
jediguy13/TFT_Touch_Shield_V1
TFT_T.cpp
1
11165
/* ST7781R TFT Library. 2011 Copyright (c) Seeed Technology Inc. Authors: Albert.Miao, Visweswara R (with initializtion code from TFT vendor) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Modified record: 2012.3.27 by Frankie.Chu Add funtion:setDisplayDirect. Add more conditional statements in funtions,fillRectangle,drawChar,drawString to deal with different directions displaying. 2015.12.1 by jediguy13 Add support for arduino due by changing bit mask things */ #include "TFT_T.h" void TFT::pushData(unsigned char data) { all_pin_output(); all_pin_low(); //for(int x=2; x<10; x++){digitalWrite(x,bitRead(data,x-2));} is slow REG_PIOB_ODSR |= (bitRead(data,0)<<25); //why is pin 2 here? REG_PIOC_ODSR |= (bitRead(data,1)<<28); //and why is pin 3 just 1 separate? REG_PIOC_ODSR |= (bitRead(data,2)<<26); REG_PIOC_ODSR |= (bitRead(data,3)<<25); REG_PIOC_ODSR |= (bitRead(data,4)<<24); REG_PIOC_ODSR |= (bitRead(data,5)<<23); REG_PIOC_ODSR |= (bitRead(data,6)<<22); REG_PIOC_ODSR |= (bitRead(data,7)<<21); } unsigned char TFT::getData(void) { unsigned char data=0; delay(1); for(int x=2; x<10; x++){bitWrite(data,x-2,digitalRead(x));} return data; } void TFT::sendCommand(unsigned int index) { CS_LOW; RS_LOW; RD_HIGH; WR_HIGH; WR_LOW; pushData(0); WR_HIGH; WR_LOW; pushData(index&0xff); WR_HIGH; CS_HIGH; } void TFT::sendData(unsigned int data) { CS_LOW; RS_HIGH; RD_HIGH; WR_LOW; pushData((data&0xff00)>>8); WR_HIGH; WR_LOW; pushData(data&0xff); WR_HIGH; CS_HIGH; } unsigned int TFT::readRegister(unsigned int index) { unsigned int data=0; CS_LOW; RS_LOW; RD_HIGH; all_pin_output(); WR_LOW; pushData(0); WR_HIGH; WR_LOW; pushData(index); WR_HIGH; all_pin_input(); all_pin_low(); RS_HIGH; RD_LOW; RD_HIGH; data |= getData()<<8; RD_LOW; RD_HIGH; data |= getData(); CS_HIGH; all_pin_output(); return data; } void TFT::init (void) { CS_OUTPUT; RD_OUTPUT; WR_OUTPUT; RS_OUTPUT; Tft.all_pin_output(); Tft.all_pin_low(); delay(100); sendCommand(0x0001); sendData(0x0100); sendCommand(0x0002); sendData(0x0700); sendCommand(0x0003); sendData(0x1030); sendCommand(0x0004); sendData(0x0000); sendCommand(0x0008); sendData(0x0302); sendCommand(0x000A); sendData(0x0000); sendCommand(0x000C); sendData(0x0000); sendCommand(0x000D); sendData(0x0000); sendCommand(0x000F); sendData(0x0000); delay(100); sendCommand(0x0030); sendData(0x0000); sendCommand(0x0031); sendData(0x0405); sendCommand(0x0032); sendData(0x0203); sendCommand(0x0035); sendData(0x0004); sendCommand(0x0036); sendData(0x0B07); sendCommand(0x0037); sendData(0x0000); sendCommand(0x0038); sendData(0x0405); sendCommand(0x0039); sendData(0x0203); sendCommand(0x003c); sendData(0x0004); sendCommand(0x003d); sendData(0x0B07); sendCommand(0x0020); sendData(0x0000); sendCommand(0x0021); sendData(0x0000); sendCommand(0x0050); sendData(0x0000); sendCommand(0x0051); sendData(0x00ef); sendCommand(0x0052); sendData(0x0000); sendCommand(0x0053); sendData(0x013f); delay(100); sendCommand(0x0060); sendData(0xa700); sendCommand(0x0061); sendData(0x0001); sendCommand(0x0090); sendData(0x003A); sendCommand(0x0095); sendData(0x021E); sendCommand(0x0080); sendData(0x0000); sendCommand(0x0081); sendData(0x0000); sendCommand(0x0082); sendData(0x0000); sendCommand(0x0083); sendData(0x0000); sendCommand(0x0084); sendData(0x0000); sendCommand(0x0085); sendData(0x0000); sendCommand(0x00FF); sendData(0x0001); sendCommand(0x00B0); sendData(0x140D); sendCommand(0x00FF); sendData(0x0000); delay(100); sendCommand(0x0007); sendData(0x0133); delay(50); exitStandBy(); sendCommand(0x0022); //paint screen black paintScreenBlack(); } void TFT::paintScreenBlack(void) { for(unsigned char i=0;i<2;i++) { for(unsigned int f=0;f<38400;f++) { sendData(BLACK); } } } void TFT::exitStandBy(void) { sendCommand(0x0010); sendData(0x14E0); delay(100); sendCommand(0x0007); sendData(0x0133); } void TFT::setOrientation(unsigned int HV)//horizontal or vertical { sendCommand(0x03); if(HV==1)//vertical { sendData(0x5038); } else//horizontal { sendData(0x5030); } sendCommand(0x0022); //Start to write to display RAM } void TFT::setDisplayDirect(unsigned char Direction) { DisplayDirect = Direction; } void TFT::setXY(unsigned int poX, unsigned int poY) { sendCommand(0x0020);//X sendData(poX); sendCommand(0x0021);//Y sendData(poY); sendCommand(0x0022);//Start to write to display RAM } void TFT::setPixel(unsigned int poX, unsigned int poY,unsigned int color) { setXY(poX,poY); sendData(color); } void TFT::drawCircle(int poX, int poY, int r,unsigned int color) { int x = -r, y = 0, err = 2-2*r, e2; do { setPixel(poX-x, poY+y,color); setPixel(poX+x, poY+y,color); setPixel(poX+x, poY-y,color); setPixel(poX-x, poY-y,color); e2 = err; if (e2 <= y) { err += ++y*2+1; if (-x == y && e2 <= x) e2 = 0; } if (e2 > x) err += ++x*2+1; } while (x <= 0); } void TFT::fillCircle(int poX, int poY, int r,unsigned int color) { int x = -r, y = 0, err = 2-2*r, e2; do { drawVerticalLine(poX-x,poY-y,2*y,color); drawVerticalLine(poX+x,poY-y,2*y,color); e2 = err; if (e2 <= y) { err += ++y*2+1; if (-x == y && e2 <= x) e2 = 0; } if (e2 > x) err += ++x*2+1; } while (x <= 0); } void TFT::drawLine(unsigned int x0,unsigned int y0,unsigned int x1,unsigned int y1,unsigned int color) { int x = x1-x0; int y = y1-y0; int dx = abs(x), sx = x0<x1 ? 1 : -1; int dy = -abs(y), sy = y0<y1 ? 1 : -1; int err = dx+dy, e2; /* error value e_xy */ for (;;){ /* loop */ setPixel(x0,y0,color); e2 = 2*err; if (e2 >= dy) { /* e_xy+e_x > 0 */ if (x0 == x1) break; err += dy; x0 += sx; } if (e2 <= dx) { /* e_xy+e_y < 0 */ if (y0 == y1) break; err += dx; y0 += sy; } } } void TFT::drawVerticalLine(unsigned int poX, unsigned int poY,unsigned int length,unsigned int color) { setXY(poX,poY); setOrientation(1); if(length+poY>MAX_Y) { length=MAX_Y-poY; } for(unsigned int i=0;i<length;i++) { sendData(color); } } void TFT::drawHorizontalLine(unsigned int poX, unsigned int poY,unsigned int length,unsigned int color) { setXY(poX,poY); setOrientation(0); if(length+poX>MAX_X) { length=MAX_X-poX; } for(unsigned int i=0;i<length;i++) { sendData(color); } } void TFT::drawRectangle(unsigned int poX, unsigned int poY, unsigned int length,unsigned int width,unsigned int color) { drawHorizontalLine(poX, poY, length, color); drawHorizontalLine(poX, poY+width, length, color); drawVerticalLine(poX, poY, width,color); drawVerticalLine(poX + length, poY, width,color); } void TFT::fillRectangle(unsigned int poX, unsigned int poY, unsigned int length, unsigned int width, unsigned int color) { for(unsigned int i=0;i<width;i++) { if(DisplayDirect == LEFT2RIGHT) drawHorizontalLine(poX, poY+i, length, color); else if (DisplayDirect == DOWN2UP) drawHorizontalLine(poX, poY-i, length, color); else if(DisplayDirect == RIGHT2LEFT) drawHorizontalLine(poX, poY-i, length, color); else if(DisplayDirect == UP2DOWN) drawHorizontalLine(poX, poY+i, length, color); } } void TFT::drawChar(unsigned char ascii,unsigned int poX, unsigned int poY,unsigned int size, unsigned int fgcolor) { setXY(poX,poY); if((ascii < 0x20)||(ascii > 0x7e))//Unsupported char. { ascii = '?'; } for(unsigned char i=0;i<8;i++) { unsigned char temp = pgm_read_byte(&simpleFont[ascii-0x20][i]); for(unsigned char f=0;f<8;f++) { if((temp>>f)&0x01) { if(DisplayDirect == LEFT2RIGHT) fillRectangle(poX+i*size, poY+f*size, size, size, fgcolor); else if(DisplayDirect == DOWN2UP) fillRectangle(poX+f*size, poY-i*size, size, size, fgcolor); else if(DisplayDirect == RIGHT2LEFT) fillRectangle(poX-i*size, poY-f*size, size, size, fgcolor); else if(DisplayDirect == UP2DOWN) fillRectangle(poX-f*size, poY+i*size, size, size, fgcolor); } } } } void TFT::drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor) { while(*string) { for(unsigned char i=0;i<8;i++) { drawChar(*string, poX, poY, size, fgcolor); } *string++; if(DisplayDirect == LEFT2RIGHT) { if(poX < MAX_X) { poX+=8*size; // Move cursor right } } else if(DisplayDirect == DOWN2UP) { if(poY > 0) { poY-=8*size; // Move cursor right } } else if(DisplayDirect == RIGHT2LEFT) { if(poX > 0) { poX-=8*size; // Move cursor right } } else if(DisplayDirect == UP2DOWN) { if(poY < MAX_Y) { poY+=8*size; // Move cursor right } } } } void TFT::all_pin_input(void) { for(int x=2; x<10; x++){pinMode(x,INPUT);} } void TFT::all_pin_output(void) { for(int x=2; x<10; x++){pinMode(x,OUTPUT);} } void TFT::all_pin_low(void) { for(int x=2; x<10; x++){digitalWrite(x,LOW);} } TFT Tft=TFT();
mit
csipiemonte/smartlab
reference-realtime/arduino-secure/libraries/SDPMessage/src/csvline.cpp
1
3215
/* * Copyright (C) 2014 CSP Innovazione nelle ICT s.c.a r.l. (http://www.csp.it/) * All rights reserved. * * All information contained herein is, and remains the property of * CSP Innovazione nelle ICT s.c.a r.l. and its suppliers, if any. * The intellectual and technical concepts contained herein are proprietary to * CSP Innovazione nelle ICT s.c.a r.l. and its suppliers and may be covered * by Italian and Foreign Patents, in process, and are protected by trade secret * or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from CSP Innovazione nelle ICT s.c.a r.l. * * cspvine.cpp * <description> * * Authors: * Marco Boeris Frusca <marco.boeris@csp.it> * */ #include "Arduino.h" #include "csvline.h" namespace sdp { namespace message { const size_t CSVLine::LINE_SIZE = 128; const char CSVLine::FS = ';'; CSVLine::CSVLine() : m_nf(0), m_fields(0), m_isCopy(false), m_line(0), m_length(0) { } CSVLine::CSVLine(const CSVLine& l) { m_nf = l.m_nf; m_length = l.m_length; m_line = l.m_line; m_fields = l.m_fields; m_isCopy = true; } CSVLine::~CSVLine() { if (m_fields != 0 && !m_isCopy) { delete[] m_fields; m_fields = 0; m_nf = 0; } if (m_line != 0 && !m_isCopy) { delete[] m_line; m_line = 0; } } void CSVLine::set(const char* line, size_t length) { size_t m_length = LINE_SIZE + 1; // Check line size if (length > strlen(line)) { length = strlen(line); } if (length < m_length) { m_length = length + 1; } if (m_line != 0) { delete[] m_line; m_line = 0; } if (m_fields != 0) { delete[] m_fields; m_fields = 0; } // Create line m_line = new char[m_length]; memset(m_line, 0, m_length); memcpy(m_line, line, m_length - 1); length = strlen(m_line); if (m_line[length - 1] == FS) { m_line[length -1] = 0; } m_nf = 0; for (size_t i = 0; i < m_length; i++) { if (m_line[i] == FS) { m_nf++; } } if (m_length > 2 && m_line[length - 1] != FS && m_line[length] == 0) { m_nf++; } m_fields = new size_t[m_nf]; memset(m_fields, 0, sizeof(size_t) * m_nf); size_t j = 0; size_t i = 0; for (; i < m_length; i++) { if (i == 0) { m_fields[j++] = i; } if ( i > 0 && j < m_nf && m_line[i -1] == FS) { m_line[i -1] = 0; m_fields[j++] = i; } } } bool CSVLine::getItemAsInt(size_t index, int &n) { char* field = getItem(index); return StringParser::toInt(field, n); } bool CSVLine::getItemAsLong(size_t index, long &n) { char* field = getItem(index); return StringParser::toLong(field, n, strlen(field)); } } /* namespace message */ } /* namespace sdp */
mit
dezGusty/serpents
src/model/SerpentBase.cpp
1
10439
// This file is part of Gusty's Serpents // Copyright (C) 2009 Augustin Preda (thegusty999@gmail.com) // // Gusty's Serpents is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Class to allow manipulation of a serpent. #include <model/SerpentBase.h> #include <guslib/trace/trace.h> #include <stdio.h> #include <math.h> using namespace GUtils; namespace Serpents { #if 0 SerpentBase::SerpentBase( ) : fractionOfLength(0.0) , hungerLevel(0.0) { path = new SerpentPath(); this->turnSpeed = 1; this->speed = 1; this->speedStep = 1; this->timeSinceLastBonusPicked = 0; this->hungerGrowthRatio = 1; this->hungerDamagingLimit = 1; bodyParts.clear(); } SerpentBase::~SerpentBase(void) { GTRACE(4, "SerpentBase destructr: Removing serpent & all "<< getLength() << " bodyparts"); for( unsigned i=0; i<bodyParts.size(); i++ ) { delete bodyParts[i]; } bodyParts.clear(); } void SerpentBase::addPart(Serpents::BodyPartBase *partToAdd) { BodyPartBase * myBodyPart = partToAdd; myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->angleInRads = this->spawnAngle; } bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } void SerpentBase::addParts( double numParts ) { GTRACE(4, "SerpentBase: adding " << numParts<< " bodyparts"); if( numParts <= 0 ) { // must use removeparts function, instead of supplying a negative number. return; } bool canStillAdd = true; while( canStillAdd ) { if( numParts >= 1 ) { // need to add a bodypart; // set the currently last bp to full if( getLength() > 1 ) { this->getBodyPart(this->getLength()-1)->setFraction( 1.0 ); } BodyPartBase * myBodyPart = this->createBodyPart( bodyParts.size() == 0); if( myBodyPart ) { myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->setAngleInRadians(this->spawnAngle ); } myBodyPart->setFraction( 1.0 + fractionOfLength ); bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } numParts--; } else { fractionOfLength = fractionOfLength + numParts; if( fractionOfLength > 0 ) { // set the currently last bp to full if( getLength() > 1 ) { this->getBodyPart(this->getLength()-1)->setFraction( 1.0 ); } BodyPartBase * myBodyPart = this->createBodyPart( bodyParts.size() == 0); if( myBodyPart ) { myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->setAngleInRadians(this->spawnAngle ); } fractionOfLength -= 1.0; myBodyPart->setFraction( 1.0 + fractionOfLength ); bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } } this->getBodyPart(this->getLength()-1)->setFraction( 1.0 + fractionOfLength ); canStillAdd = false; } } } void SerpentBase::initialize( double initialLength ) { maxlength = 100; minlength = MIN_SERP_LEN; spawnBodyPartSize.x = 15; spawnBodyPartSize.y = 15; addParts(initialLength); if( bodyParts.size()> 0 ) { DPOINT hsz = {20,20}; this->bodyParts[0]->setSize( hsz ); } minSpeed = DEFAULT_MIN_SPEED; maxSpeed = DEFAULT_MAX_SPEED; setSpeed(1); setSpeedInfluenceOnTurn(0); setSpeedStep(0.001); fractionOfLength = 0; } void SerpentBase::onAddedBodyPart() { path->addStrip(); } void SerpentBase::onRemovedBodyPart() { path->removeStrip(); } void SerpentBase::removeParts( double numParts ) { GTRACE(4, "SerpentBase: removing " << numParts << " bodyparts"); bool canRemoveParts = true; double partsStillToRemove = numParts; while( canRemoveParts ) { if( partsStillToRemove >= 1 ) { if( getLength() - 1 <= minlength ) canRemoveParts = false; if( getLength() - 1 <= MIN_SERP_LEN ) canRemoveParts = false; if( canRemoveParts ) { delete bodyParts[bodyParts.size()-1]; bodyParts.pop_back(); this->onRemovedBodyPart(); if( fractionOfLength >= 0 ) bodyParts[getLength()-1]->setFraction( fractionOfLength ); else bodyParts[getLength()-1]->setFraction( 1.0 + fractionOfLength ); -- partsStillToRemove; } } else { fractionOfLength -= partsStillToRemove; if( fractionOfLength <= -1 ) { if( getLength() > 1 ) { delete bodyParts[getLength()-1]; bodyParts.pop_back(); this->onRemovedBodyPart(); } fractionOfLength ++; bodyParts[getLength()-1]->setFraction( 1.0 + fractionOfLength ); } canRemoveParts = false; } } } void SerpentBase::setBodyPartSpawnSize( double width, double height ) { this->spawnBodyPartSize.x = width; this->spawnBodyPartSize.y = height; } void SerpentBase::setSpawnPosition(double x, double y) { this->spawnPosition.x = x; this->spawnPosition.y = y; } void SerpentBase::spawn(double x, double y) { for( int i = 0; i< this->getLength(); i++ ) { this->bodyParts[i]->setLocation(x,y); if( i==0) { bodyParts[i]->spawned = true; } else { bodyParts[i]->spawned = false; } } } void SerpentBase::spawn() { this->spawn( spawnPosition.x, spawnPosition.y ); } void SerpentBase::setAngleInRadians(double angle, bool affectAll ) { int maxIter = (affectAll ? 1 : this->getLength() ); for( int i=0; i< maxIter && i< this->getLength(); i++ ) { this->bodyParts[i]->angleInRads = angle; } spawnAngle = angle; } void SerpentBase::setSpeed( double newSpeed ) { this->speed = newSpeed; if( newSpeed < minSpeed ) { this->speed = minSpeed; } if( newSpeed > maxSpeed ) { this->speed = maxSpeed; } if( newSpeed < DEFAULT_MIN_SPEED ) { this->speed = DEFAULT_MIN_SPEED; } if( newSpeed > DEFAULT_MAX_SPEED ) { this->speed = DEFAULT_MAX_SPEED; } } void SerpentBase::setTurnSpeed(double newTurnSpeed) { if( newTurnSpeed > MIN_TURN_SPEED && newTurnSpeed < MAX_TURN_SPEED ) { this->turnSpeed = newTurnSpeed; } } void SerpentBase::move( double timeUnits ) { GTRACE(5, "*** SerpentBase::move"); if( getLength() <= 0 ) return; if( timeUnits <=0 ) { timeUnits = DEFAULT_TIME_INTERVAL; } GTRACE(5, "*** SerpentBase::move, len="<<getLength()); if( getLength() <= minlength ) { return; } // spawn the parts that are not yet visible. int lastNonSpawn = getLength(); for(int i=getLength()-1;i>=0;i-- ) { if( ! bodyParts[i]->spawned ) { lastNonSpawn = i; } } if( lastNonSpawn > 0 ) { for( int i= lastNonSpawn; i < getLength(); i++ ) { if( bodyParts[i]->collidesWith( bodyParts[i-1] )) { break; } else { bodyParts[i]->spawned = bodyParts[i-1]->spawned; } } } // Calculate the new location of the head. SPoint<double> newLocation = bodyParts[0]->getLocation(); newLocation.x += GusUtils::Cos( bodyParts[0]->getAngleInRadians() ) * this->speed * timeUnits; newLocation.y -= GusUtils::Sin( bodyParts[0]->getAngleInRadians() ) * this->speed * timeUnits; // Distance between the path elements. // The head is (by standard at least) a bit larger than the rest of the bodyparts. So the distance between it // and another bodypart is the radius of the head + the radius of a regular bodypart. double xsz = bodyParts[0]->getSizeFromCenter() + (bodyParts[1] ? bodyParts[1]->getSizeFromCenter() : 0); // Move the head strip. path->moveHeadStrip( newLocation.x, newLocation.y, xsz); // Move all strips, and set the bodyparts according to their location. path->getAndSetPositionOfAllParts( bodyParts ); } // // get the bodypart at a certain index // BodyPartBase* SerpentBase::getBodyPart(int index) { if( index >= (int)bodyParts.size() ) throw std::exception("Tried to get bodypart, but index out of range!"); return bodyParts[index]; } // // turn the snake left or right // void SerpentBase::turn( double angle, bool useRadians ) { double angleRad = angle; if( ! useRadians ) { angleRad = angle * GusUtils::PI() / 180 ; } BodyPartBase * temp = getBodyPart(0); if( temp ) { temp->setAngleInRadians( temp->getAngleInRadians() + angleRad * turnSpeed * (1 + speedInfluenceOnTurn * sqrt(speed)) ); } } void SerpentBase::setFractionOfLength( double value ) { if( value >=0 && value <=1 ) { fractionOfLength = value; } else { if( value > 1 ) fractionOfLength = 1; else // value <0 fractionOfLength = 0; } } void SerpentBase::setMinAllowedSpeed( double value ) { minSpeed = value; setSpeed(getSpeed()); } void SerpentBase::setMaxAllowedSpeed( double value ) { maxSpeed = value; setSpeed(getSpeed()); } void SerpentBase::setSpeedStep( double value ) { speedStep = value; } void SerpentBase::setHungerLevel( double value ) { if( value <= 0 ) { hungerLevel = 0; } else { hungerLevel = value; } } void SerpentBase::setAlive( bool bAlive ) { this->alive = bAlive; } #endif } // namespace Serpents
mit
kreischtauf/CSRST
src/PoissonSolver.cpp
1
23889
/*************************************************************************** PoissonSolver.cpp ------------------- begin : Tue Jun 28 2011 copyright : (C) 2011 by Christof Kraus email : christof.kraus-csrst@my.mail.de ***************************************************************************/ #include "PoissonSolver.hh" #include "utils.hh" #include "Epetra_VbrMatrix.h" #include "Epetra_LinearProblem.h" #include "Epetra_Operator.h" #include "Epetra_Time.h" #include "EpetraExt_RowMatrixOut.h" #include "Teuchos_Array.hpp" #include "BelosConfigDefs.hpp" #include "BelosLinearProblem.hpp" #include "BelosEpetraAdapter.hpp" #include "BelosBlockCGSolMgr.hpp" #include "Ifpack.h" #include "Physics.hh" extern ostream dbg; #define DBGOUT dbg << "PoissonSolver.cpp: " << __LINE__ << "\t" struct IndexComp { bool operator()(const Index & a, const Index & b) { return (a.first() < b.first()); } }; typedef double ST; typedef Epetra_Operator OP; typedef Epetra_MultiVector MV; typedef Belos::OperatorTraits<ST,MV,OP> OPT; typedef Belos::MultiVecTraits<ST,MV> MVT; PoissonSolver::PoissonSolver(PartBunch & bunch, const Bend & bend, const std::vector<BoundaryCell>& bc, const Mesh_t & mesh, const FieldLayout<DIM> & fl, const BCType & bctX, const BCType & bctY): _gamma(0.0), _Nx(0), _Ny(0), _hr(DIM), _bctX(bctX), _bctY(bctY), _bunch(bunch), _bend(bend), _boundaryCells(bc), _mesh(mesh), _FL(fl) { Vector_t pmean; _bunch.get_pmean(pmean); _gamma = sqrt(dot(pmean, pmean) + 1); _lDom = _FL.getLocalNDIndex(); _gDom = _FL.getDomain(); _hr[0] = _mesh.get_meshSpacing(0) * _gamma; _hr[1] = _mesh.get_meshSpacing(1); #if DIM>2 _hr[2] = _mesh.get_meshSpacing(2); #endif _Nx = _gDom[0].length(); _Ny = _gDom[1].length(); _setupTimer = Timings::getTimer("setup poisson"); _solveTimer = Timings::getTimer("solve poisson"); } /// actual computation void PoissonSolver::computeField(VField_Edge_t & EFD, VField_Cell_t & HFD, VField_Edge_t & JFD, const double & dt, const double & tol, const int & maxIterations) { Mesh_t & mesh = EFD.get_mesh(); FieldLayout<DIM> & FL = EFD.getLayout(); const NDIndex<DIM> lDom = FL.getLocalNDIndex(); _bunch.saveR(); const GCS_t & gcs = EFD.getGuardCellSizes(); Timings::startTimer(_setupTimer); Epetra_Map* Map = getGlobalElements(); Teuchos::RCP<Epetra_Vector> LHS; LHS = Teuchos::rcp(new Epetra_Vector(*Map)); Teuchos::RCP<Epetra_Vector> RHS; RHS = Teuchos::rcp(new Epetra_Vector(*Map)); Teuchos::RCP<Epetra_CrsMatrix> A; A = Teuchos::rcp(new Epetra_CrsMatrix(Copy, *Map, 5)); StencilGeometry(RHS, A); // print("PoissonMatrix.dat", RHS, A); Teuchos::ParameterList belosList; belosList.set( "Maximum Iterations", maxIterations ); // Maximum number of iterations allowed belosList.set( "Convergence Tolerance", tol ); belosList.set( "Verbosity", (Belos::Errors + Belos::Warnings + Belos::TimingDetails + Belos::FinalSummary + Belos::StatusTestDetails) ); Teuchos::ParameterList MLList; SetupMLList(MLList); Teuchos::RCP<ML_Epetra::MultiLevelPreconditioner> MLPrec = Teuchos::rcp(new ML_Epetra::MultiLevelPreconditioner(*A, MLList,false)); MLPrec->ComputePreconditioner(); Teuchos::RCP<Belos::EpetraPrecOp> prec = Teuchos::rcp(new Belos::EpetraPrecOp(MLPrec)); Belos::LinearProblem<ST, MV, OP> problem; problem.setOperator(A); problem.setLHS(LHS); problem.setRHS(RHS); problem.setLeftPrec(prec); if (!problem.isProblemSet()) { if (!problem.setProblem()) { std::cerr << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl; } } Teuchos::RCP< Belos::SolverManager<ST, MV, OP> > solver; solver = Teuchos::rcp( new Belos::BlockCGSolMgr<ST, MV, OP>(Teuchos::rcp(&problem, false), Teuchos::rcp(&belosList, false))); Timings::stopTimer(_setupTimer); BinaryVtkFile vtkFile; SField_t rho(mesh, FL, gcs); _bunch.drift_particles(dt / 2); _bunch.scatterQ(rho); _bunch.drift_particles(-dt / 2); fillRHS(rho, RHS); LHS->Random(); problem.setProblem(Teuchos::null, RHS); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 1); fillFields(LHS, EFD, HFD, 1); _bunch.move_by(Vector_t(-0.5 * _hr[0] / _gamma, 0.0)); _bunch.scatterQ(rho); fillRHS(rho, RHS); shiftLHS(rho, LHS, 1.0); problem.setProblem(Teuchos::null, RHS); belosList.set("Convergence Tolerance", 1e-6); solver->setParameters(Teuchos::rcp(&belosList, false)); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 2); fillFields(LHS, EFD, HFD, 2); _bunch.restoreR(); _bunch.scatterQ(rho); vtkFile.addScalarField(rho, "rho"); JFD = 0.0; JFD[lDom[0]][lDom[1]](0) += Physics::c * sqrt(1.0 - 1.0 / (_gamma * _gamma)) * rho[lDom[0]][lDom[1]]; fillRHS(rho, RHS); shiftLHS(rho, LHS, -0.5); problem.setProblem(Teuchos::null, RHS); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 0); fillFields(LHS, EFD, HFD, 0); vtkFile.writeFile("Data/potential"); delete Map; } /// building the stencil void PoissonSolver::StencilGeometry(Teuchos::RCP<Epetra_Vector> & RHS, Teuchos::RCP<Epetra_CrsMatrix> & A) { const Epetra_BlockMap & MyMap = RHS->Map(); int NumMyElements = MyMap.NumMyElements(); int* MyGlobalElements = MyMap.MyGlobalElements(); double * rhsvalues = RHS->Values(); std::vector<double> Values(5); std::vector<int> Indices(5); const auto & inside = _bend.getInsideMask(); for (int lid = 0; lid < NumMyElements; ++ lid) { size_t NumEntries = 0; const size_t & gid = MyGlobalElements[lid]; cutoffStencil(Indices, Values, rhsvalues[lid], NumEntries, inside, gid); A->InsertGlobalValues(gid, NumEntries, &Values[0], &Indices[0]); } A->FillComplete(); A->OptimizeStorage(); } void PoissonSolver::initializeLHS(Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); ST * values = LHS->Values(); // size_t length = _bend.getLengthStraightSection() + 1; // size_t width = _bend.getWidthStraightSection() + 1; Vector_t position; _bunch.get_rmean(position); _bend.getPositionInCells(position); int lastX = (_bend.getGlobalDomain())[0].last(); int lastY = (_bend.getGlobalDomain())[1].last(); // NDIndex<DIM> initDom(Index(0,length), Index(lastY - width, lastY)); NDIndex<DIM> elem; for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); Vector_t contr; if (idx > position(0)) { contr(0) = (idx - position(0)) / (lastX - position(0)); } else { contr(0) = (position(0) - idx) / position(0); } if (idy > position(1)) { contr(1) = (idy - position(1)) / (lastY - position(1)); } else { contr(1) = (position(1) - idy) / position(1); } const double val = sqrt(dot(contr, contr)); dbg << std::min(10.0, -log(val)) << std::endl; values[lid] = -std::max(0.0, std::min(10.0,-log(val))); } } void PoissonSolver::shiftLHS(SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS, double tau) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); rho.localElement(elem) = values[lid]; } rho.fillGuardCells(); if (tau > 0) { if (tau > 1) tau = 1; rho[II][JJ] += tau * rho[II+1][JJ] - tau * rho[II][JJ]; } else { tau = - tau; if (tau > 1) tau = 1; rho[II][JJ] += tau * rho[II-1][JJ] - tau * rho[II][JJ]; } for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] = rho.localElement(elem); } } void PoissonSolver::subtract(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] -= rho.localElement(elem); } } void PoissonSolver::add(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] += rho.localElement(elem); } } void PoissonSolver::initialGuessLHS(Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); Vector_t spos; NDIndex<DIM> elem; Vector_t origin = _mesh.get_origin(); double totalQ = -_bunch.get_qtotal() / (2 * Physics::pi * Physics::epsilon_0); totalQ /= 97.63; double *values = LHS->Values(); _bunch.get_rmean(spos); spos[0] = (spos[0] - origin(0)) / _mesh.get_meshSpacing(0); spos[1] = (spos[1] - origin(1)) / _mesh.get_meshSpacing(1); for (int lid = 0; lid < NumMyElements; ++ lid) { const double dx = _hr[0] * (spos[0] - MyGlobalElements[lid] % _Nx); const double dy = _hr[1] * (spos[1] - MyGlobalElements[lid] / _Nx); values[lid] = totalQ / sqrt(dx*dx + dy*dy + _hr[0]*_hr[1]); } } void PoissonSolver::fillRHS(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & RHS) { const ST couplingConstant = 1 / (Physics::epsilon_0 * _gamma); const Epetra_BlockMap & Map = RHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; ST * values = RHS->Values(); // double minv = 0.0; // double maxv = 0.0; for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] = rho.localElement(elem) * couplingConstant; // if (minv > values[lid]) minv = values[lid]; // if (maxv < values[lid]) maxv = values[lid]; } // dbg << "rhs_{min}: " << minv << " - rhs_{max}: " << maxv << endl; } void PoissonSolver::plotPotential(BinaryVtkFile & vtkFile, const Teuchos::RCP<Epetra_Vector> & LHS, const VField_Edge_t & EFD, const int & component) { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); boost::shared_ptr<SField_Vert_t> scalarField = Utils::getScalarVertField(EFD); NDIndex<DIM> elem; char fieldName[50]; ST * values = LHS->Values(); sprintf(fieldName, "potential_%d", component); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); scalarField->localElement(elem) = values[lid]; } vtkFile.addScalarField(*scalarField, fieldName); } void PoissonSolver::fillFields(const Teuchos::RCP<Epetra_Vector> & LHS, VField_Edge_t & EFD, VField_Cell_t & HFD, const int & components) { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); const Vector_t hr(_mesh.get_meshSpacing(0), _mesh.get_meshSpacing(1)); Index II = _lDom[0], JJ = _lDom[1]; NDIndex<DIM> elem, elem2; ST * values = LHS->Values(); switch (components) { case 0: for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); EFD.localElement(elem)(0) = values[lid] / _hr[0]; } EFD.fillGuardCells(); EFD[II][JJ](0) -= EFD[II+1][JJ](0); break; case 1: for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); EFD.localElement(elem)(1) = _gamma * values[lid] / _hr[1]; } EFD.fillGuardCells(); EFD[II][JJ](1) -= EFD[II][JJ+1](1); break; case 2: { double betaGamma = sqrt(_gamma * _gamma - 1); for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); double hfd = betaGamma * values[lid] / (2 * Physics::c * Physics::mu_0 * _hr[1]); HFD.localElement(elem) = Vector_t(hfd, hfd); } HFD.fillGuardCells(); HFD[II][JJ](0) -= HFD[II][JJ+1](0); HFD[II][JJ](1) -= HFD[II][JJ+1](1); break; } case -1: default: ; } } bool PoissonSolver::isInside(const int & idx, const int & idy) { if (idx < 0 || idx > _gDom[0].last() || idy < 0 || idy > _gDom[1].last()) { return false; } return true; } void PoissonSolver::distance_bunch_to_boundary(std::vector<double> & dist, const double & x, const double & y) { Vector_t spos; _bunch.get_rmean(spos); dist[0] = std::abs(x - spos[0]); dist[1] = std::abs(y - spos[1]); } void PoissonSolver::print(const std::string & filename, Teuchos::RCP<Epetra_Vector> & RHS, Teuchos::RCP<Epetra_CrsMatrix> & A) const { EpetraExt::RowMatrixToMatlabFile(filename.c_str(), *A); // if (Ippl::getNodes() == 1) { // const Epetra_BlockMap & Map = RHS->Map(); // const int NumMyElements = Map.NumMyElements(); // ST * values = RHS->Values(); // ofstream out("rhs.dat"); // for (size_t lid = 0; lid < NumMyElements; ++ lid) { // out << values[lid] << "\n"; // } // out.close(); // } } void PoissonSolver::linearStencil(std::vector<int> & Indices, std::vector<double> & Values, double & rhs, size_t & NumEntries, const Field<bool, DIM, Mesh_t, Vert> & isInside, const size_t & gid) { const double EW = -1 / (_hr[0]*_hr[0]); const double NS = -1 / (_hr[1]*_hr[1]); const int idx = gid % _Nx; const int idy = gid / _Nx; const NDIndex<DIM> elem(Index(idx, idx), Index(idy, idy)); if (isInside.localElement(elem)) { NumEntries = 5; Values[0] = NS; Indices[0] = gid - _Nx; Values[1] = EW; Indices[1] = gid - 1; Values[2] = -2 * (EW + NS); Indices[2] = gid; Values[3] = EW; Indices[3] = gid + 1; Values[4] = NS; Indices[4] = gid + _Nx; return; } const std::vector<int> & localToBCellNr = _bend.getInverseMapDualGrid(); const int & localID = localToBCellNr[_bend.getLocalID(elem)]; if (localID == -1) { NumEntries = 1; Values[0] = 1; Indices[0] = gid; NDIndex<DIM> elemmy(elem[0], elem[1] - 1); int localIDmy = localToBCellNr[_bend.getLocalID(elemmy)]; if (localIDmy != -1 && _boundaryCells[localIDmy].lambda_m(1) > SPACE_EPS) { const BoundaryCell & bc = _boundaryCells[localIDmy]; const double & s = bc.lambda_m(1); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid - _Nx; dbg << gid << " " << gid - _Nx << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } NDIndex<DIM> elemmx(elem[0] - 1, elem[1]); int localIDmx = localToBCellNr[_bend.getLocalID(elemmx)]; if (localIDmx != -1 && _boundaryCells[localIDmx].lambda_m(0) > SPACE_EPS) { const BoundaryCell & bc = _boundaryCells[localIDmx]; const double & s = bc.lambda_m(0); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid - 1; dbg << gid << " " << gid - 1 << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } rhs = 0.0; return; } const BoundaryCell & bc = _boundaryCells[localID]; if (bc.lambda_m[0] > 1 - SPACE_EPS || bc.lambda_m[1] > 1 - SPACE_EPS) { NumEntries = 5; Values[0] = NS; Indices[0] = gid - _Nx; Values[1] = EW; Indices[1] = gid - 1; Values[2] = -2 * (EW + NS); Indices[2] = gid; Values[3] = EW; Indices[3] = gid + 1; Values[4] = NS; Indices[4] = gid + _Nx; } else { NumEntries = 1; Values[0] = 1; Indices[0] = gid; if (bc.lambda_m(0) > SPACE_EPS) { const double & s = bc.lambda_m(0); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid + 1; dbg << gid << " " << gid + 1 << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } if (bc.lambda_m(1) > SPACE_EPS) { const double & s = bc.lambda_m(1); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid + _Nx; dbg << gid << " " << gid + _Nx << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } rhs = 0.0; } return; } void PoissonSolver::cutoffStencil(std::vector<int> & Indices, std::vector<double> & Values, double & rhs, size_t & NumEntries, const Field<bool, DIM, Mesh_t, Cell> & isInside, const size_t & gid) { const double EW = -1 / (_hr[0]*_hr[0]); const double NS = -1 / (_hr[1]*_hr[1]); const int idx = gid % _Nx; const int idy = gid / _Nx; const NDIndex<DIM> elem(Index(idx, idx), Index(idy, idy)); const NDIndex<DIM> elemmx(elem[0] - 1, elem[1]); const NDIndex<DIM> elemmy(elem[0], elem[1] - 1); const NDIndex<DIM> elempx(elem[0] + 1, elem[1]); const NDIndex<DIM> elempy(elem[0], elem[1] + 1); const std::vector<int> & localToBCellNr = _bend.getInverseMap(); const int & localID = localToBCellNr[_bend.getLocalID(elem)]; const int & localIDmx = localToBCellNr[_bend.getLocalID(elemmx)]; const int & localIDmy = localToBCellNr[_bend.getLocalID(elemmy)]; const int & localIDpx = localToBCellNr[_bend.getLocalID(elempx)]; const int & localIDpy = localToBCellNr[_bend.getLocalID(elempy)]; long maxX = _bend.getLengthStraightSection(); if (idx < maxX && (isInside.localElement(elem) || (localID > -1 && _boundaryCells[localID].area_m > 0.5))) { NumEntries = 0; if (isInside.localElement(elemmy) || (localIDmy > -1 && _boundaryCells[localIDmy].area_m > 0.5)) { Indices[NumEntries] = gid - _Nx; Values[NumEntries] = NS; NumEntries ++; } if (isInside.localElement(elemmx) || (localIDmx > -1 && _boundaryCells[localIDmx].area_m > 0.5)) { Indices[NumEntries] = gid - 1; Values[NumEntries] = EW; NumEntries ++; } if (isInside.localElement(elempx) || (localIDpx > -1 && _boundaryCells[localIDpx].area_m > 0.5)) { Indices[NumEntries] = gid + 1; Values[NumEntries] = EW; NumEntries ++; } if (isInside.localElement(elempy) || (localIDpy > -1 && _boundaryCells[localIDpy].area_m > 0.5)) { Indices[NumEntries] = gid + _Nx; Values[NumEntries] = NS; NumEntries ++; } Indices[NumEntries] = gid; Values[NumEntries] = -2 * (EW + NS); NumEntries ++; return; } NumEntries = 1; Indices[0] = gid; Values[0] = 1; rhs = 0; return; }
mit
vnen/godot
scene/2d/canvas_modulate.cpp
1
4292
/*************************************************************************/ /* canvas_modulate.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "canvas_modulate.h" void CanvasModulate::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_CANVAS) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } } else if (p_what == NOTIFICATION_EXIT_CANVAS) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } else { RS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } update_configuration_warnings(); } } void CanvasModulate::_bind_methods() { ClassDB::bind_method(D_METHOD("set_color", "color"), &CanvasModulate::set_color); ClassDB::bind_method(D_METHOD("get_color"), &CanvasModulate::get_color); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); } void CanvasModulate::set_color(const Color &p_color) { color = p_color; if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); } } Color CanvasModulate::get_color() const { return color; } TypedArray<String> CanvasModulate::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (is_visible_in_tree() && is_inside_tree()) { List<Node *> nodes; get_tree()->get_nodes_in_group("_canvas_modulate_" + itos(get_canvas().get_id()), &nodes); if (nodes.size() > 1) { warnings.push_back(TTR("Only one visible CanvasModulate is allowed per scene (or set of instantiated scenes). The first created one will work, while the rest will be ignored.")); } } return warnings; } CanvasModulate::CanvasModulate() { } CanvasModulate::~CanvasModulate() { }
mit
shiftf8/cs539
fall2016/hw6pointers.c
1
7413
// CS 539, HW 6, Rob Lamog #include <stdio.h> #include <stdlib.h> void show( const double * begin, const double * end ); double sum( const double * begin, const double * end ); void half( double * begin, double * end ); void add( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ); void maximum( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ); void stat( double * smallest, double * average, double * largest, const double * begin, const double * end ); void setFib( unsigned * begin, unsigned * end ); void reverse( double * begin, double * end ); int die( const char * msg ); void fillArraySequentially( double * begin, double * end ); void fillArrayRandomly( double * begin, double * end ); void fillUnsignedArraySequentially( unsigned * begin, unsigned * end ); unsigned fib( unsigned n ); void showUnsigned( const unsigned * begin, const unsigned * end ); int main(){ /* * Change size for ALL tests here. */ unsigned set_size = 4; /* * Initializing main variables. */ double *arr, *arr1, *arr2; unsigned *uarr; double szero = 0, azero = 0, lzero = 0; //An address for pointers s (smallest), a (average), l (largest), to point to for stat(). double *s = &szero, *a = &azero, *l = &lzero; //It's important to point to someplace that is defined. srand(time(NULL)); //Using srand() to seed pseudo random numbers for fillArrayRandomly(). /* * Building test arrays. */ arr = malloc(set_size * sizeof *arr); if (arr == NULL) die("malloc unsuccessful."); // printf("%p : %lf : %lu\n", &arr, *arr, sizeof *arr); arr1 = malloc(set_size * sizeof *arr1); if (arr1 == NULL) die("malloc unsuccessful."); arr2 = malloc(set_size * sizeof *arr2); if (arr2 == NULL) die("malloc unsuccessful."); uarr = malloc(set_size * sizeof *uarr); if (uarr == NULL) die("malloc unsuccessful."); /* * Filling test arrays with something worth manipulating. */ fillArraySequentially(arr, arr + set_size); // fillArrayRandomly(arr, arr + set_size); fillArraySequentially(arr1, arr1 + set_size); // fillArrayRandomly(arr1, arr1 + set_size); // fillArraySequentially(arr2, arr2 + set_size); fillArrayRandomly(arr2, arr2 + set_size); fillUnsignedArraySequentially(uarr, uarr + set_size); //Special unsigned array for setfib(). // printf("%lf\n", *(arr1 + (set_size - 1))); /* * Printing initialized arrays with show() and custom showUnsigned(). */ show(arr, arr + set_size); show(arr1, arr1 + set_size); show(arr2, arr2 + set_size); showUnsigned(uarr, uarr + set_size); printf("\n"); /* * Running tests. */ printf("sum = %lf\n", sum(arr, arr + set_size)); printf("half = "); half(arr, arr + set_size); show(arr, arr + set_size); printf("add = "); add(arr, arr + set_size, arr1, arr2); show(arr, arr + set_size); printf("maximum = "); maximum(arr, arr + set_size, arr1, arr2); show(arr, arr + set_size); stat(s, a, l, arr, arr + set_size); printf("smallest = %lf, average = %lf, largest = %lf of ", *s, *a, *l); show(arr, arr + set_size); printf("setFib = "); setFib(uarr, uarr + set_size); showUnsigned(uarr, uarr + set_size); //Utilizing custom showUnsigned(). Same as show(), except this function prints unsigned arrays instead of double arrays. printf("reverse = "); reverse(arr, arr + set_size); show(arr, arr + set_size); /* * It's important to free allocated memory and manage pointers safely. */ free(arr); arr = NULL; free(arr1); arr1 = NULL; free(arr2); arr2 = NULL; free(uarr); uarr = NULL; s = NULL; a = NULL; l = NULL; return 0; } //main void show( const double * begin, const double * end ){ printf("{"); while (begin < end){ printf("%lf", *begin); ++begin; if (begin < end) printf(", "); } printf("}\n"); } double sum( const double * begin, const double * end ){ double retVal = 0; while (begin < end){ retVal += *begin; ++begin; } return retVal; } void half( double * begin, double * end ){ while (begin < end){ *begin /= 2; ++begin; } } void add( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ){ unsigned i = 0; // printf("%lf / %lf : %lf", *(a0Begin + i), *(a1Begin + i), (*(a0Begin + i) + *(a1Begin + i))); while (resultBegin < resultEnd){ *resultBegin = *(a0Begin + i) + *(a1Begin + i); ++i; ++resultBegin; } } void maximum( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ){ unsigned i = 0; while (resultBegin < resultEnd){ if (*(a0Begin + i) < *(a1Begin + i)) *resultBegin = *(a1Begin + i); else *resultBegin = *(a0Begin + i); ++i; ++resultBegin; } } void stat( double * smallest, double * average, double * largest, const double * begin, const double * end ){ unsigned elements = end - begin; if (begin == end) die("Zero elements defined. stat() needs at least one element to examine."); //Be wary of dying before the rest of your test code can manage. //Initializing with first element. *smallest = *begin; *largest = *begin; while (begin < end){ //While loop will always run at least once given the nature of stat() arguments as pointers. Affording *average to be initialized properly. if (*smallest >= *begin) *smallest = *begin; *average += *begin; if (*largest <= *begin) *largest = *begin; ++begin; } *average = *average / elements; } void setFib( unsigned * begin, unsigned * end ){ while (begin < end){ *begin = fib(*begin); ++begin; } } void reverse( double * begin, double * end ){ double temp = 0; unsigned elements = end - begin; unsigned i = 0; // printf("%u\n", i); for (i; i < elements / 2; ++i){ temp = *(begin + i); *(begin + i) = *(begin + (elements - 1 - i)); *(begin + (elements - 1 - i)) = temp; } } int die( const char * msg ){ printf("Fatal error: %s\n", msg); exit(EXIT_FAILURE); } void fillArraySequentially( double * begin, double * end ){ //Range [0++] unsigned i = 0; while (begin < end){ *begin = i++; ++begin; } } void fillArrayRandomly( double * begin, double * end ){ //Pseudo random range [0-9] while (begin < end){ *begin = rand() % 10; //Simple unsigned range for quick test verification // *begin = rand() / (RAND_MAX / (10.0)); //Random range of doubles [0.0-9.9] ++begin; } } void fillUnsignedArraySequentially( unsigned * begin, unsigned * end ){ //Range [0++] unsigned i = 0; while (begin < end){ *begin = i++; ++begin; } } unsigned fib( unsigned n ){ if (n == 0) return 0; //Special 0 case if (n == 1) return 1; //Special 1 case return fib(n - 1) + fib(n - 2); } void showUnsigned( const unsigned * begin, const unsigned * end ){ printf("{"); while (begin < end){ printf("%u", *begin); ++begin; if (begin < end) printf(", "); } printf("}\n"); }
mit
cedar-renjun/air-conditioning-assistant
rt-thread/examples/kernel/thread_detach.c
1
3211
/* * 程序清单:线程脱离 * * 这个例子会创建两个线程,在其中一个线程中执行对另一个线程的脱离。 */ #include <rtthread.h> #include "tc_comm.h" /* 线程1控制块 */ static struct rt_thread thread1; /* 线程1栈 */ static rt_uint8_t thread1_stack[THREAD_STACK_SIZE]; /* 线程2控制块 */ static struct rt_thread thread2; /* 线程2栈 */ static rt_uint8_t thread2_stack[THREAD_STACK_SIZE]; /* 线程1入口 */ static void thread1_entry(void* parameter) { rt_uint32_t count = 0; while (1) { /* 线程1采用低优先级运行,一直打印计数值 */ rt_kprintf("thread count: %d\n", count ++); } } /* 线程2入口 */ static void thread2_entry(void* parameter) { /* 线程2拥有较高的优先级,以抢占线程1而获得执行 */ /* 线程2启动后先睡眠10个OS Tick */ rt_thread_delay(10); /* * 线程2唤醒后直接执行线程1脱离,线程1将从就绪线程队列中删除 */ rt_thread_detach(&thread1); /* * 线程2继续休眠10个OS Tick然后退出 */ rt_thread_delay(10); /* * 线程2运行结束后也将自动被从就绪队列中删除,并脱离线程队列 */ } int thread_detach_init() { rt_err_t result; /* 初始化线程1 */ result = rt_thread_init(&thread1, "t1", /* 线程名:t1 */ thread1_entry, RT_NULL, /* 线程的入口是thread1_entry,入口参数是RT_NULL*/ &thread1_stack[0], sizeof(thread1_stack), /* 线程栈是thread1_stack */ THREAD_PRIORITY, 10); if (result == RT_EOK) /* 如果返回正确,启动线程1 */ rt_thread_startup(&thread1); else tc_stat(TC_STAT_END | TC_STAT_FAILED); /* 初始化线程2 */ result = rt_thread_init(&thread2, "t2", /* 线程名:t2 */ thread2_entry, RT_NULL, /* 线程的入口是thread2_entry,入口参数是RT_NULL*/ &thread2_stack[0], sizeof(thread2_stack), /* 线程栈是thread2_stack */ THREAD_PRIORITY - 1, 10); if (result == RT_EOK) /* 如果返回正确,启动线程2 */ rt_thread_startup(&thread2); else tc_stat(TC_STAT_END | TC_STAT_FAILED); return 0; } #ifdef RT_USING_TC static void _tc_cleanup() { /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */ rt_enter_critical(); /* 执行线程脱离 */ if (thread1.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread1); if (thread2.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread2); /* 调度器解锁 */ rt_exit_critical(); /* 设置TestCase状态 */ tc_done(TC_STAT_PASSED); } int _tc_thread_detach() { /* 设置TestCase清理回调函数 */ tc_cleanup(_tc_cleanup); thread_detach_init(); /* 返回TestCase运行的最长时间 */ return 25; } /* 输出函数命令到finsh shell中 */ FINSH_FUNCTION_EXPORT(_tc_thread_detach, a static thread example); #else /* 用户应用入口 */ int rt_application_init() { thread_detach_init(); return 0; } #endif
mit
Paregov/hexadiv
edno/software/nuttx/configs/mirtoo/src/up_leds.c
1
8433
/**************************************************************************** * configs/mirtoo/src/up_leds.c * arch/arm/src/board/up_leds.c * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <debug.h> #include <arch/board/board.h> #include "pic32mx-internal.h" #include "mirtoo-internal.h" /**************************************************************************** * Definitions ****************************************************************************/ /* LED Configuration ********************************************************/ /* The Mirtoo module has 2 user LEDs labeled LED0 and LED1 in the schematics: * * --- ----- -------------------------------------------------------------- * PIN Board Notes * --- ----- -------------------------------------------------------------- * RC8 LED0 Grounded, high value illuminates * RC9 LED1 Grounded, high value illuminates * * The Dimitech DTX1-4000L EV-kit1 supports 3 more LEDs, but there are not * controllable from software. * * If CONFIG_ARCH_LEDS is defined, then NuttX will control these LEDs as * follows: * ON OFF * ------------------------- ---- ---- ---- ---- * LED0 LED1 LED0 LED1 * ------------------------- ---- ---- ---- ---- * LED_STARTED 0 OFF OFF --- --- * LED_HEAPALLOCATE 1 ON OFF --- --- * LED_IRQSENABLED 2 OFF ON --- --- * LED_STACKCREATED 3 ON ON --- --- * LED_INIRQ 4 ON N/C OFF N/C * LED_SIGNAL 4 ON N/C OFF N/C * LED_ASSERTION 4 ON N/C OFF N/C * LED_PANIC 4 ON N/C OFF N/C */ #define GPIO_LED_0 (GPIO_OUTPUT|GPIO_VALUE_ZERO|GPIO_PORTC|GPIO_PIN8) #define GPIO_LED_1 (GPIO_OUTPUT|GPIO_VALUE_ZERO|GPIO_PORTC|GPIO_PIN9) /* LED Management Definitions ***********************************************/ #ifdef CONFIG_ARCH_LEDS # define LED_OFF 0 # define LED_ON 1 # define LED_NC 2 #endif /* Debug ********************************************************************/ #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_LEDS) # define leddbg lldbg # ifdef CONFIG_DEBUG_VERBOSE # define ledvdbg lldbg # else # define ledvdbg(x...) # endif #else # undef CONFIG_DEBUG_LEDS # undef CONFIG_DEBUG_VERBOSE # define leddbg(x...) # define ledvdbg(x...) #endif /**************************************************************************** * Private types ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS struct led_setting_s { uint8_t led0 : 2; uint8_t led1 : 2; uint8_t unused : 4; }; #endif /**************************************************************************** * Private Data ****************************************************************************/ /* If CONFIG_ARCH_LEDS is defined then NuttX will control the LEDs. The * following structures identified the LED settings for each NuttX LED state. */ #ifdef CONFIG_ARCH_LEDS static const struct led_setting_s g_ledonvalues[LED_NVALUES] = { {LED_OFF, LED_OFF, 0}, {LED_ON, LED_OFF, 0}, {LED_OFF, LED_ON, 0}, {LED_ON, LED_ON, 0}, {LED_ON, LED_NC, 0}, }; static const struct led_setting_s g_ledoffvalues[LED_NVALUES] = { {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_OFF, LED_NC, 0}, }; /* If CONFIG_ARCH_LEDS is not defined, then the user can control the LEDs in * any way. The following array simply maps the PIC32MX_MIRTOO_LEDn * index values to the correct LED pin configuration. */ #else static const uint16_t g_ledpincfg[PIC32MX_MIRTOO_NLEDS] = { GPIO_LED_0, GPIO_LED_1 }; #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: up_setleds ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void up_setleds(FAR const struct led_setting_s *setting) { /* LEDs are pulled up so writing a low value (false) illuminates them */ if (setting->led0 != LED_NC) { pic32mx_gpiowrite(GPIO_LED_0, setting->led0 == LED_ON); } if (setting->led1 != LED_NC) { pic32mx_gpiowrite(GPIO_LED_1, setting->led1 == LED_ON); } } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: pic32mx_ledinit ****************************************************************************/ void pic32mx_ledinit(void) { /* Configure output pins */ pic32mx_configgpio(GPIO_LED_0); pic32mx_configgpio(GPIO_LED_1); } /**************************************************************************** * Name: pic32mx_setled ****************************************************************************/ #ifndef CONFIG_ARCH_LEDS void pic32mx_setled(int led, bool ledon) { /* LEDs are pulled up so writing a low value (false) illuminates them */ if ((unsigned)led < PIC32MX_MIRTOO_NLEDS) { pic32mx_gpiowrite(g_ledpincfg[led], ledon); } } #endif /**************************************************************************** * Name: pic32mx_setleds ****************************************************************************/ #ifndef CONFIG_ARCH_LEDS void pic32mx_setleds(uint8_t ledset) { /* Call pic32mx_setled() with ledon == true to illuminated the LED */ pic32mx_setled(PIC32MX_MIRTOO_LED0, (ledset & PIC32MX_MIRTOO_LED0_BIT) != 0); pic32mx_setled(PIC32MX_MIRTOO_LED1, (ledset & PIC32MX_MIRTOO_LED1_BIT) != 0); } #endif /**************************************************************************** * Name: board_led_on ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void board_led_on(int led) { if ((unsigned)led < LED_NVALUES) { up_setleds(&g_ledonvalues[led]); } } #endif /**************************************************************************** * Name: board_led_off ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void board_led_off(int led) { if ((unsigned)led < LED_NVALUES) { up_setleds(&g_ledoffvalues[led]); } } #endif
mit
Billary/BillaryCoinSource
src/qt/sendcoinsdialog.cpp
1
17904
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a BillaryCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid BillaryCoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
mit
ldorelli/tcc
src/draw_main.cpp
1
1377
#include <SFML/Graphics.hpp> #include <iostream> #include <cmath> #include <cstdlib> #include <util.h> #include <graph.h> #include <kuramoto.h> #include <time.h> using namespace std; #define BOLAS 2 int main() { srand ( time(NULL) ); Graph<KuramotoOscillator> g; KuramotoOscillator::simpleKuramotoNetwork(g, 2, 50); // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "My window"); sf::View view( sf::Vector2f(0.0, 0.0), sf::Vector2f(200, 150) ); window.setView(view); // run the program as long as the window is open while (window.isOpen()) { for (int i = 0; i < 2000; ++i) { sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); } // clear the window with black color window.clear(sf::Color::Black); for (int i = 0; i < 2; ++i) { sf::CircleShape sp(3); sp.setPosition(5*i, g.nodes[i].phase * 30.0); // int color = (57.0 + g.nodes[i].phase)/114.00 * 255; if (i) sp.setFillColor( sf::Color::Blue ); else sp.setFillColor( sf::Color::Red ); window.draw(sp); } // end the current frame window.display(); g.update(); sf::sleep( sf::seconds(0.1) ); } } return 0; }
mit
staycrypto/antimatter
src/test/test_bitcoin.cpp
1
1757
#define BOOST_TEST_MODULE Antimatter Test Suite #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include "db.h" #include "txdb.h" #include "main.h" #include "wallet.h" #include "util.h" CWallet* pwalletMain; CClientUIInterface uiInterface; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; TestingSetup() { fPrintToDebugger = true; // don't want to write to debug.log file noui_connect(); bitdb.MakeMock(); pathTemp = GetTempPath() / strprintf("test_antimatter_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); InitBlockIndex(); bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterWallet(pwalletMain); nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } ~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); delete pwalletMain; pwalletMain = NULL; delete pcoinsTip; delete pcoinsdbview; delete pblocktree; bitdb.Flush(true); boost::filesystem::remove_all(pathTemp); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); }
mit
julzor42/core32
src/uart.c
1
4586
/* MIT License Copyright (c) 2016 Julien Delmotte Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <core32.h> #include <core32/uart.h> #ifdef UART_CONSOLE void _mon_putc(char c) { while (UART_IsFull(UART_CONSOLE)); UxTXREG(UART_CONSOLE) = c; } int _mon_getc(int canblock) { if (canblock) { while (!UART_HasData(UART_CONSOLE)); return UxRXREG(UART_CONSOLE); } if (UART_HasData(UART_CONSOLE)) return UxRXREG(UART_CONSOLE); return 0; } #endif void UART_Initialize(unsigned int Port, unsigned int Baud, unsigned int RdWr) { int Div4 = 0; // Disable and clear UART UxMODE(Port) = 0; PBDIV1_CYCLE_WAIT(); if (Div4) UxMODESET(Port) = UMODE_BRGH; if (RdWr & UART_WRITE) UxSTASET(Port) = USTA_UTXEN; if (RdWr & UART_READ) UxSTASET(Port) = USTA_URXEN; UxBRG(Port) = PBCLK / (Div4 ? 4 : 16) / Baud - 1; UART_Enable(Port); } void UART_PutChar(unsigned int Port, char Data) { while (UART_IsFull(Port)); UxTXREG(Port) = Data; } void UART_PutString(unsigned int Port, const char* Data) { while (*Data) UART_PutChar(Port, *Data++); } void UART_Write(unsigned int Port, const char* Data, unsigned int Length) { while (--Length) UART_PutChar(Port, *Data++); } char UART_GetChar(unsigned int Port) { while (!UART_HasData(Port)); return UxRXREG(Port); } void UART_Read(unsigned int Port, char* Data, unsigned int Length) { while (--Length) (*Data++) = UART_GetChar(Port); } void UART_ReadLine(unsigned int Port, char* Data, unsigned int MaxLength) { while (--MaxLength > 0) { *Data = UART_GetChar(Port); if (*Data == '\n') break; Data++; } *Data = 0; } void UART_SetInterrupt(unsigned int Port, unsigned int Mode, unsigned int Priority, unsigned int SubPriority) { UART_EnableInterrupt(Port, DISABLED); UART_EnableTXInterrupt(Port, DISABLED); UART_EnableRXInterrupt(Port, DISABLED); switch (Port) { case UART_2: IPC8bits.U2IP = Priority; IPC8bits.U2IS = SubPriority; break; } UART_ClearInterrupt(Port); UART_ClearTXInterrupt(Port); UART_ClearRXInterrupt(Port); UART_EnableInterrupt(Port, (Mode != 0) ? 1 : 0); UART_EnableTXInterrupt(Port, (Mode & UART_WRITE) ? 1 : 0); UART_EnableRXInterrupt(Port, (Mode & UART_READ) ? 1 : 0); } void UART_EnableInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2EIE = Enabled; break; } } void UART_EnableTXInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2TXIE = Enabled; break; } } void UART_EnableRXInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2RXIE = Enabled; break; } } void UART_ClearInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2EIF = 0; break; } } void UART_ClearTXInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2TXIF = 0; break; } } void UART_ClearRXInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2RXIF = 0; break; } } unsigned int UART_CheckInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2EIF; } return 0; } unsigned int UART_CheckTXInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2TXIF; } return 0; } unsigned int UART_CheckRXInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2RXIF; } return 0; }
mit
AndrewGaspar/OSR-Learning-Kit-Universal-WDF-Driver
osrdrv/Device.cpp
1
6851
/*++ Module Name: device.c - Device handling events for example driver. Abstract: This file contains the device entry points and callbacks. Environment: Kernel-mode Driver Framework --*/ #include "Precomp.h" #include "Device.h" #include "TraceLogging.h" #include "Result.h" #include "Queue.h" #include "File.h" #include <Public.h> PASSIVE PAGED NTSTATUS DriverCreateDevice( _Inout_ PWDFDEVICE_INIT DeviceInit) /*++ Routine Description: Worker routine called to create a device and its software resources. Arguments: DeviceInit - Pointer to an opaque init structure. Memory for this structure will be freed by the framework when the WdfDeviceCreate succeeds. So don't access the structure after that point. Return Value: NTSTATUS --*/ { PAGED_CODE(); OSRLogEntry(); // Power events WDF_PNPPOWER_EVENT_CALLBACKS pnpPowerCallbacks; WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks); pnpPowerCallbacks.EvtDevicePrepareHardware = EvtOSRDevicePrepareHardware; pnpPowerCallbacks.EvtDeviceD0Entry = EvtOSRD0Entry; pnpPowerCallbacks.EvtDeviceD0Exit = EvtOSRD0Exit; WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks); // File events WDF_FILEOBJECT_CONFIG fileObjectConfig; WDF_FILEOBJECT_CONFIG_INIT(&fileObjectConfig, EvtOSRDeviceFileCreate, nullptr, nullptr); WDF_OBJECT_ATTRIBUTES fileObjectAttributes; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&fileObjectAttributes, FileContext); WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileObjectConfig, &fileObjectAttributes); WDF_OBJECT_ATTRIBUTES deviceAttributes; WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, DEVICE_CONTEXT); WDFDEVICE device; RETURN_IF_NT_FAILED(WdfDeviceCreate(&DeviceInit, &deviceAttributes, &device)); // // Get a pointer to the device context structure that we just associated // with the device object. We define this structure in the device.h // header file. DeviceGetContext is an inline function generated by // using the WDF_DECLARE_CONTEXT_TYPE_WITH_NAME macro in device.h. // This function will do the type checking and return the device context. // If you pass a wrong object handle it will return NULL and assert if // run under framework verifier mode. // auto deviceContext = DeviceGetContext(device); // // Initialize the context. // *deviceContext = {}; // // Create a device interface so that applications can find and talk // to us. // RETURN_IF_NT_FAILED(WdfDeviceCreateDeviceInterface( device, &GUID_DEVINTERFACE_OSR_FX2, NULL // ReferenceString )); // // Initialize the I/O Package and any Queues // RETURN_IF_NT_FAILED(DriverQueueInitialize(device)); OSRLogExit(); return STATUS_SUCCESS; } PASSIVE PAGED NTSTATUS EvtOSRD0Entry( _In_ WDFDEVICE Device, _In_ WDF_POWER_DEVICE_STATE PreviousState) { UNREFERENCED_PARAMETER((PreviousState)); OSRLogEntry(); auto context = DeviceGetContext(Device); if (context->DipSwitches) { RETURN_IF_NT_FAILED(context->DipSwitches.Start()); } if (context->InData) { RETURN_IF_NT_FAILED(context->InData.Start()); } if (context->OutData) { RETURN_IF_NT_FAILED(context->OutData.Start()); } OSRLogExit(); return STATUS_SUCCESS; } PASSIVE PAGED NTSTATUS EvtOSRD0Exit( _In_ WDFDEVICE Device, _In_ WDF_POWER_DEVICE_STATE TargetState) { UNREFERENCED_PARAMETER((TargetState)); OSRLogEntry(); auto context = DeviceGetContext(Device); if (context->DipSwitches) { context->DipSwitches.Stop(WdfIoTargetCancelSentIo); } if (context->InData) { context->InData.Stop(WdfIoTargetCancelSentIo); } if (context->OutData) { context->OutData.Stop(WdfIoTargetCancelSentIo); } OSRLogExit(); return STATUS_SUCCESS; } PASSIVE PAGED NTSTATUS EvtOSRDevicePrepareHardware( _In_ WDFDEVICE Device, _In_ WDFCMRESLIST ResourcesRaw, _In_ WDFCMRESLIST ResourcesTranslated) { UNREFERENCED_PARAMETER((ResourcesRaw, ResourcesTranslated)); PAGED_CODE(); OSRLogEntry(); auto context = DeviceGetContext(Device); if (!context->UsbDevice) { WDF_USB_DEVICE_CREATE_CONFIG createParams; WDF_USB_DEVICE_CREATE_CONFIG_INIT(&createParams, USBD_CLIENT_CONTRACT_VERSION_602); RETURN_IF_NT_FAILED( WdfUsbTargetDeviceCreateWithParameters(Device, &createParams, WDF_NO_OBJECT_ATTRIBUTES, &context->UsbDevice)); WDF_USB_DEVICE_SELECT_CONFIG_PARAMS configParams; WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_SINGLE_INTERFACE(&configParams); RETURN_IF_NT_FAILED( WdfUsbTargetDeviceSelectConfig(context->UsbDevice, WDF_NO_OBJECT_ATTRIBUTES, &configParams)); context->UsbInterface = configParams.Types.SingleInterface.ConfiguredUsbInterface; context->NumberConfiguredPipes = WdfUsbInterfaceGetNumConfiguredPipes(context->UsbInterface); if (context->NumberConfiguredPipes == 0) { RETURN_IF_NT_FAILED(USBD_STATUS_BAD_NUMBER_OF_ENDPOINTS); } for (UINT8 i = 0; i < context->NumberConfiguredPipes; i++) { WDF_USB_PIPE_INFORMATION pipeInfo; WDF_USB_PIPE_INFORMATION_INIT(&pipeInfo); auto pipe = WdfUsbInterfaceGetConfiguredPipe(context->UsbInterface, i, &pipeInfo); OSRLoggingWrite( "AvailablePipe", TraceLoggingValue(pipeInfo.EndpointAddress, "EndpointAddress"), TraceLoggingUInt32(pipeInfo.PipeType, "PipeType"), TraceLoggingValue(pipeInfo.Interval, "Interval"), TraceLoggingValue(pipeInfo.SettingIndex, "SettingIndex"), TraceLoggingValue(pipeInfo.MaximumPacketSize, "MaximumPacketSize"), TraceLoggingValue(pipeInfo.MaximumTransferSize, "MaximumTransferSize")); switch (pipeInfo.EndpointAddress) { case DipSwitchEndpoint: context->DipSwitches = { pipeInfo, pipe }; break; case DataOutEndpoint: context->OutData = { pipeInfo, pipe }; break; case DataInEndpoint: context->InData = { pipeInfo, pipe }; break; } } if (context->DipSwitches) { WdfUsbTargetPipeSetNoMaximumPacketSizeCheck(context->DipSwitches.Object); } else { OSRLoggingWrite("DipSwitchesMissing", TraceLoggingLevel(TRACE_LEVEL_ERROR)); } } OSRLogExit(); return STATUS_SUCCESS; }
mit
gautier-lefebvre/cppframework
framework/src/Library/ThirdParty/cppformat/posix.cpp
1
7849
/* A C++ interface to POSIX functions. Copyright (c) 2014 - 2015, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Disable bogus MSVC warnings. #ifndef _CRT_SECURE_NO_WARNINGS # define _CRT_SECURE_NO_WARNINGS #endif #include "Library/ThirdParty/cppformat/posix.hh" #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #ifndef _WIN32 # include <unistd.h> #else # include <windows.h> # include <io.h> # define O_CREAT _O_CREAT # define O_TRUNC _O_TRUNC # ifndef S_IRUSR # define S_IRUSR _S_IREAD # endif # ifndef S_IWUSR # define S_IWUSR _S_IWRITE # endif # ifdef __MINGW32__ # define _SH_DENYNO 0x40 # undef fileno # endif #endif // _WIN32 namespace { #ifdef _WIN32 // Return type of read and write functions. typedef int RWResult; // On Windows the count argument to read and write is unsigned, so convert // it from size_t preventing integer overflow. inline unsigned convert_rwcount(std::size_t count) { return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX; } #else // Return type of read and write functions. typedef ssize_t RWResult; inline std::size_t convert_rwcount(std::size_t count) { return count; } #endif } fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT { if (file_ && FMT_SYSTEM(fclose(file_)) != 0) fmt::report_system_error(errno, "cannot close file"); } fmt::BufferedFile::BufferedFile( fmt::CStringRef filename, fmt::CStringRef mode) { FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0); if (!file_) throw SystemError(errno, "cannot open file {}", filename); } void fmt::BufferedFile::close() { if (!file_) return; int result = FMT_SYSTEM(fclose(file_)); file_ = 0; if (result != 0) throw SystemError(errno, "cannot close file"); } // A macro used to prevent expansion of fileno on broken versions of MinGW. #define FMT_ARGS int fmt::BufferedFile::fileno() const { int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_)); if (fd == -1) throw SystemError(errno, "cannot get file descriptor"); return fd; } fmt::File::File(fmt::CStringRef path, int oflag) { int mode = S_IRUSR | S_IWUSR; #if defined(_WIN32) && !defined(__MINGW32__) fd_ = -1; FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); #else FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); #endif if (fd_ == -1) throw SystemError(errno, "cannot open file {}", path); } fmt::File::~File() FMT_NOEXCEPT { // Don't retry close in case of EINTR! // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) fmt::report_system_error(errno, "cannot close file"); } void fmt::File::close() { if (fd_ == -1) return; // Don't retry close in case of EINTR! // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html int result = FMT_POSIX_CALL(close(fd_)); fd_ = -1; if (result != 0) throw SystemError(errno, "cannot close file"); } fmt::LongLong fmt::File::size() const { #ifdef _WIN32 // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT // is less than 0x0500 as is the case with some default MinGW builds. // Both functions support large file sizes. DWORD size_upper = 0; HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_)); DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper)); if (size_lower == INVALID_FILE_SIZE) { DWORD error = GetLastError(); if (error != NO_ERROR) throw WindowsError(GetLastError(), "cannot get file size"); } fmt::ULongLong long_size = size_upper; return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower; #else typedef struct stat Stat; Stat file_stat = Stat(); if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) throw SystemError(errno, "cannot get file attributes"); FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(file_stat.st_size), "return type of File::size is not large enough"); return file_stat.st_size; #endif } std::size_t fmt::File::read(void *buffer, std::size_t count) { RWResult result = 0; FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); if (result < 0) throw SystemError(errno, "cannot read from file"); return result; } std::size_t fmt::File::write(const void *buffer, std::size_t count) { RWResult result = 0; FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); if (result < 0) throw SystemError(errno, "cannot write to file"); return result; } fmt::File fmt::File::dup(int fd) { // Don't retry as dup doesn't return EINTR. // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html int new_fd = FMT_POSIX_CALL(dup(fd)); if (new_fd == -1) throw SystemError(errno, "cannot duplicate file descriptor {}", fd); return File(new_fd); } void fmt::File::dup2(int fd) { int result = 0; FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); if (result == -1) { throw SystemError(errno, "cannot duplicate file descriptor {} to {}", fd_, fd); } } void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT { int result = 0; FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); if (result == -1) ec = ErrorCode(errno); } void fmt::File::pipe(File &read_end, File &write_end) { // Close the descriptors first to make sure that assignments don't throw // and there are no leaks. read_end.close(); write_end.close(); int fds[2] = {}; #ifdef _WIN32 // Make the default pipe capacity same as on Linux 2.6.11+. enum { DEFAULT_CAPACITY = 65536 }; int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); #else // Don't retry as the pipe function doesn't return EINTR. // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html int result = FMT_POSIX_CALL(pipe(fds)); #endif if (result != 0) throw SystemError(errno, "cannot create pipe"); // The following assignments don't throw because read_fd and write_fd // are closed. read_end = File(fds[0]); write_end = File(fds[1]); } fmt::BufferedFile fmt::File::fdopen(const char *mode) { // Don't retry as fdopen doesn't return EINTR. FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode)); if (!f) throw SystemError(errno, "cannot associate stream with file descriptor"); BufferedFile file(f); fd_ = -1; return file; } long fmt::getpagesize() { #ifdef _WIN32 SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; #else long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); if (size < 0) throw SystemError(errno, "cannot get memory page size"); return size; #endif }
mit
mathemage/CompetitiveProgramming
gkickstart/2022/round-D/A/A.cpp
1
6553
/* ======================================== ID: mathema6 TASK: A LANG: C++14 * File Name : A.cpp * Creation Date : 10-07-2022 * Last Modified : Sun 10 Jul 2022 07:27:31 AM CEST * Created By : Karel Ha <mathemage@gmail.com> * URL : https://codingcompetitions.withgoogle.com/kickstart/round/00000000008caea6/0000000000b76e11 * Points/Time : 00:26:29 * Total/ETA : 4+6 pts * Status : * S AC AC !!! (flash) * ==========================================*/ #define PROBLEMNAME "A" #include <bits/stdc++.h> using namespace std; #define endl "\n" // #define endl "\n" << flush // flush for interactive problems #define REP(i,n) for(ll i=0;i<(n);i++) #define FOR(i,a,b) for(ll i=(a);i<=(b);i++) #define FORD(i,a,b) for(ll i=(a);i>=(b);i--) #define REPi(i,n) for(int i=0;i<(n);i++) #define FORi(i,a,b) for(int i=(a);i<=(b);i++) #define FORDi(i,a,b) for(int i=(a);i>=(b);i--) #define ALL(A) (A).begin(), (A).end() #define REVALL(A) (A).rbegin(), (A).rend() #define F first #define S second #define OP first #define CL second #define PB push_back #define MP make_pair #define MTP make_tuple #define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0) #define CONTAINS(S,E) ((S).find(E) != (S).end()) #define SZ(x) ((ll) (x).size()) #define YES cout << "YES" << endl; #define NO cout << "NO" << endl; #define YN(b) cout << ((b)?"YES":"NO") << endl; #define Yes cout << "Yes" << endl; #define No cout << "No" << endl; #define Yn(b) cout << ((b)?"Yes":"No") << endl; #define Imp cout << "Impossible" << endl; #define IMP cout << "IMPOSSIBLE" << endl; using ll = long long; using ul = unsigned long long; using ld = long double; using graph_unord = unordered_map<ll, vector<ll>>; using graph_ord = map<ll, set<ll>>; using graph_t = graph_unord; #ifdef ONLINE_JUDGE #undef MATHEMAGE_DEBUG #endif #ifdef MATHEMAGE_DEBUG #define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl; #define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl; #define LINESEP1 cerr << "----------------------------------------------- " << endl; #define LINESEP2 cerr << "#################################################################" << endl; #define LINESEP3 cerr << "_________________________________________________________________" << endl; #else #define MSG(a) #define MSG_VEC_VEC(v) #define LINESEP1 #define LINESEP2 #define LINESEP3 #endif ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; } template<typename T> inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) { for (const auto & row: vec) { for (const auto & col: row) { os << "[ " << col << "] "; } os << endl; } return os; } template<typename T, class Compare> ostream& operator<<(ostream& os, const set<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; } template<typename T, class Compare> ostream& operator<<(ostream& os, const multiset<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; } template<typename T1, typename T2> ostream& operator<<(ostream& os, const map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; } template<typename T1, typename T2> ostream& operator<<(ostream& os, const unordered_map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; } template<typename T1, typename T2> ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << "(" << p.F << ", " << p.S << ")"; } template<typename T> istream& operator>>(istream& is, vector<T> & vec) { for (auto & x: vec) is >> x; return is; } template<typename T> inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); } template<class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } template<class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } // inline bool eqDouble(double a, double b) { return fabs(a-b) < 1e-9; } inline bool eqDouble(ld a, ld b) { return fabs(a-b) < 1e-9; } inline bool isCollinear(ld x, ld y, ld x1, ld y1, ld x2, ld y2) { // (x-x1)/(y-y1) == (x-x2)/(y-y2) // (x-x1)*(y-y2) == (x-x2)*(y-y1) return eqDouble((x-x1)*(y-y2), (x-x2)*(y-y1)); } inline bool isBetween(ld x, ld y, ld x1, ld y1, ld x2, ld y2) { return min(x1,x2)<=x && x<=max(x1,x2) && min(y1,y2)<=y && y<=max(y1,y2); } inline bool onLine(ld x, ld y, ld x1, ld y1, ld x2, ld y2) { return isCollinear(x, y, x1, y1, x2, y2) && isBetween(x, y, x1, y1, x2, y2); } #ifndef MATHEMAGE_LOCAL void setIO(string filename) { // the argument is the filename without the extension freopen((filename+".in").c_str(), "r", stdin); freopen((filename+".out").c_str(), "w", stdout); MSG(filename); } #endif const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1}; const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1}; const vector<pair<int,int>> DXY8 = { {-1,-1}, {-1,0}, {-1,1}, { 0,-1}, { 0,1}, { 1,-1}, { 1,0}, { 1,1} }; const vector<int> DX4 = {0, 1, 0, -1}; const vector<int> DY4 = {1, 0, -1, 0}; const vector<pair<int,int>> DXY4 = { {0,1}, {1,0}, {0,-1}, {-1,0} }; const string dues="NESW"; const int CLEAN = -1; const int UNDEF = -42; const long long MOD = 1000000007; const double EPS = 1e-8; const ld PI = acos((ld)-1); const int INF = INT_MAX; const long long INF_LL = LLONG_MAX; const long long INF_ULL = ULLONG_MAX; void solve() { ll N,M; cin >> N >> M; vector<ll> A(N); cin >> A; std::sort(REVALL(A)); MSG(A); LINESEP1; ld result = 0.0; REP(i,M-1) { result += A[i]; } MSG(result); LINESEP1; ll len=N-(M-1); if (len>0) { ll head=M-1; ll l1=len/2; ll l2=(len+1)/2 - 1; result += (A[head+l1] + A[head+l2] ) / 2.0; MSG(len); MSG(head); MSG(l1); MSG(A[head+l1]); MSG(l2); MSG(A[head+l2]); } cout << result << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout << std::setprecision(10) << std::fixed; #ifndef MATHEMAGE_LOCAL // setIO(PROBLEMNAME); #endif int cases = 1; cin >> cases; FOR(tt,1,cases) { cout << "Case #" << tt << ": "; solve(); LINESEP3; } return 0; }
mit
BonexGu/Blik2D-SDK
Blik2D/addon/openssl-1.1.0c_for_blik/crypto/cryptlib.c
1
10321
/* * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECDH support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ #include BLIK_OPENSSL_U_internal__cryptlib_int_h //original-code:"internal/cryptlib_int.h" #include BLIK_OPENSSL_V_openssl__safestack_h //original-code:<openssl/safestack.h> #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) extern unsigned int OPENSSL_ia32cap_P[4]; # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY) #include <stdio.h> # define OPENSSL_CPUID_SETUP typedef uint64_t IA32CAP; void OPENSSL_cpuid_setup(void) { static int trigger = 0; IA32CAP OPENSSL_ia32_cpuid(unsigned int *); IA32CAP vec; char *env; if (trigger) return; trigger = 1; if ((env = getenv("OPENSSL_ia32cap"))) { int off = (env[0] == '~') ? 1 : 0; # if defined(_WIN32) if (!sscanf(env + off, "%I64i", &vec)) vec = strtoul(env + off, NULL, 0); # else if (!sscanf(env + off, "%lli", (long long *)&vec)) vec = strtoul(env + off, NULL, 0); # endif if (off) vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~vec; else if (env[0] == ':') vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); OPENSSL_ia32cap_P[2] = 0; if ((env = strchr(env, ':'))) { unsigned int vecx; env++; off = (env[0] == '~') ? 1 : 0; vecx = strtoul(env + off, NULL, 0); if (off) OPENSSL_ia32cap_P[2] &= ~vecx; else OPENSSL_ia32cap_P[2] = vecx; } } else vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); /* * |(1<<10) sets a reserved bit to signal that variable * was initialized already... This is to avoid interference * with cpuid snippets in ELF .init segment. */ OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10); OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32); } # else unsigned int OPENSSL_ia32cap_P[4]; # endif #endif int OPENSSL_NONPIC_relocated = 0; #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ) void OPENSSL_cpuid_setup(void) { } #endif #if defined(_WIN32) && !defined(__CYGWIN__) # include <tchar.h> # include <signal.h> # ifdef __WATCOMC__ # if defined(_UNICODE) || defined(__UNICODE__) # define _vsntprintf _vsnwprintf # else # define _vsntprintf _vsnprintf # endif # endif # ifdef _MSC_VER # define alloca _alloca # endif # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 int OPENSSL_isservice(void) { HWINSTA h; DWORD len; WCHAR *name; static union { void *p; FARPROC f; } _OPENSSL_isservice = { NULL }; if (_OPENSSL_isservice.p == NULL) { HANDLE mod = GetModuleHandle(NULL); if (mod != NULL) _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice"); if (_OPENSSL_isservice.p == NULL) _OPENSSL_isservice.p = (void *)-1; } if (_OPENSSL_isservice.p != (void *)-1) return (*_OPENSSL_isservice.f) (); h = GetProcessWindowStation(); if (h == NULL) return -1; if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) return -1; if (len > 512) return -1; /* paranoia */ len++, len &= ~1; /* paranoia */ name = (WCHAR *)alloca(len + sizeof(WCHAR)); if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len)) return -1; len++, len &= ~1; /* paranoia */ name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */ # if 1 /* * This doesn't cover "interactive" services [working with real * WinSta0's] nor programs started non-interactively by Task Scheduler * [those are working with SAWinSta]. */ if (wcsstr(name, L"Service-0x")) return 1; # else /* This covers all non-interactive programs such as services. */ if (!wcsstr(name, L"WinSta0")) return 1; # endif else return 0; } # else int OPENSSL_isservice(void) { return 0; } # endif void OPENSSL_showfatal(const char *fmta, ...) { va_list ap; TCHAR buf[256]; const TCHAR *fmt; # ifdef STD_ERROR_HANDLE /* what a dirty trick! */ HANDLE h; if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL && GetFileType(h) != FILE_TYPE_UNKNOWN) { /* must be console application */ int len; DWORD out; va_start(ap, fmta); len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap); WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL); va_end(ap); return; } # endif if (sizeof(TCHAR) == sizeof(char)) fmt = (const TCHAR *)fmta; else do { int keepgoing; size_t len_0 = strlen(fmta) + 1, i; WCHAR *fmtw; fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR)); if (fmtw == NULL) { fmt = (const TCHAR *)L"no stack?"; break; } if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0)) for (i = 0; i < len_0; i++) fmtw[i] = (WCHAR)fmta[i]; for (i = 0; i < len_0; i++) { if (fmtw[i] == L'%') do { keepgoing = 0; switch (fmtw[i + 1]) { case L'0': case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': case L'.': case L'*': case L'-': i++; keepgoing = 1; break; case L's': fmtw[i + 1] = L'S'; break; case L'S': fmtw[i + 1] = L's'; break; case L'c': fmtw[i + 1] = L'C'; break; case L'C': fmtw[i + 1] = L'c'; break; } } while (keepgoing); } fmt = (const TCHAR *)fmtw; } while (0); va_start(ap, fmta); _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap); buf[OSSL_NELEM(buf) - 1] = _T('\0'); va_end(ap); # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 /* this -------------v--- guards NT-specific calls */ if (check_winnt() && OPENSSL_isservice() > 0) { HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL")); if (hEventLog != NULL) { const TCHAR *pmsg = buf; if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL, 1, 0, &pmsg, NULL)) { #if defined(DEBUG) /* * We are in a situation where we tried to report a critical * error and this failed for some reason. As a last resort, * in debug builds, send output to the debugger or any other * tool like DebugView which can monitor the output. */ OutputDebugString(pmsg); #endif } (void)DeregisterEventSource(hEventLog); } } else # endif MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR); } #else void OPENSSL_showfatal(const char *fmta, ...) { #ifndef OPENSSL_NO_STDIO va_list ap; va_start(ap, fmta); vfprintf(stderr, fmta, ap); va_end(ap); #endif } int OPENSSL_isservice(void) { return 0; } #endif void OPENSSL_die(const char *message, const char *file, int line) { OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n", file, line, message); #if !defined(_WIN32) || defined(__CYGWIN__) abort(); #else /* * Win32 abort() customarily shows a dialog, but we just did that... */ # if !defined(_WIN32_WCE) raise(SIGABRT); # endif _exit(3); #endif } #if !defined(OPENSSL_CPUID_OBJ) /* volatile unsigned char* pointers are there because * 1. Accessing a variable declared volatile via a pointer * that lacks a volatile qualifier causes undefined behavior. * 2. When the variable itself is not volatile the compiler is * not required to keep all those reads and can convert * this into canonical memcmp() which doesn't read the whole block. * Pointers to volatile resolve the first problem fully. The second * problem cannot be resolved in any Standard-compliant way but this * works the problem around. Compilers typically react to * pointers to volatile by preserving the reads and writes through them. * The latter is not required by the Standard if the memory pointed to * is not volatile. * Pointers themselves are volatile in the function signature to work * around a subtle bug in gcc 4.6+ which causes writes through * pointers to volatile to not be emitted in some rare, * never needed in real life, pieces of code. */ int CRYPTO_memcmp(const volatile void * volatile in_a, const volatile void * volatile in_b, size_t len) { size_t i; const volatile unsigned char *a = in_a; const volatile unsigned char *b = in_b; unsigned char x = 0; for (i = 0; i < len; i++) x |= a[i] ^ b[i]; return x; } #endif
mit
ensemblr/llvm-project-boilerplate
include/llvm/projects/test-suite/SingleSource/UnitTests/Vector/Altivec/alti.expandfft.c
2
9856
#include <stdio.h> #include <math.h> #include <time.h> #include <float.h> #include <stdlib.h> #include <altivec.h> #define N 1048576 #define N2 N/2 void cfft2(unsigned int n,float x[][2],float y[][2],float w[][2], float sign); void cffti(int n, float w[][2]); main() { /* Example of Apple Altivec coded binary radix FFT using intrinsics from Petersen and Arbenz "Intro. to Parallel Computing," Section 3.6 This is an expanded version of a generic work-space FFT: steps are in-line. cfft2(n,x,y,w,sign) takes complex n-array "x" (Fortran real,aimag,real,aimag,... order) and writes its DFT in "y". Both input "x" and the original contents of "y" are destroyed. Initialization for array "w" (size n/2 complex of twiddle factors (exp(twopi*i*k/n), for k=0..n/2-1)) is computed once by cffti(n,w). WPP, SAM. Math. ETHZ, 1 June, 2002 */ int first,i,icase,it,ln2,n; int nits=1000000; static float seed = 331.0; float error,fnm1,sign,z0,z1,ggl(); float *x,*y,*z,*w; double t1,mflops; /* allocate storage for x,y,z,w on 4-word bndr. */ x = (float *) malloc(8*N); y = (float *) malloc(8*N); z = (float *) malloc(8*N); w = (float *) malloc(4*N); n = 2; for(ln2=1;ln2<21;ln2++){ first = 1; for(icase=0;icase<2;icase++){ if(first){ for(i=0;i<2*n;i+=2){ z0 = ggl(&seed); /* real part of array */ z1 = ggl(&seed); /* imaginary part of array */ x[i] = z0; z[i] = z0; /* copy of initial real data */ x[i+1] = z1; z[i+1] = z1; /* copy of initial imag. data */ } } else { for(i=0;i<2*n;i+=2){ z0 = 0; /* real part of array */ z1 = 0; /* imaginary part of array */ x[i] = z0; z[i] = z0; /* copy of initial real data */ x[i+1] = z1; z[i+1] = z1; /* copy of initial imag. data */ } } /* initialize sine/cosine tables */ cffti(n,w); /* transform forward, back */ if(first){ sign = 1.0; cfft2(n,x,y,w,sign); sign = -1.0; cfft2(n,y,x,w,sign); /* results should be same as initial multiplied by n */ fnm1 = 1.0/((float) n); error = 0.0; for(i=0;i<2*n;i+=2){ error += (z[i] - fnm1*x[i])*(z[i] - fnm1*x[i]) + (z[i+1] - fnm1*x[i+1])*(z[i+1] - fnm1*x[i+1]); } error = sqrt(fnm1*error); printf(" for n=%d, fwd/bck error=%e\n",n,error); first = 0; } else { for(it=0;it<nits;it++){ sign = +1.0; cfft2(n,x,y,w,sign); sign = -1.0; cfft2(n,y,x,w,sign); } } } if((ln2%4)==0) nits /= 10; n *= 2; } return 0; } void cfft2(unsigned int n,float x[][2],float y[][2],float w[][2], float sign) { /* altivec version of cfft2 from Petersen and Arbenz book, "Intro. to Parallel Computing", Oxford Univ. Press, 2003, Section 3.6 wpp 14. Dec. 2003 */ int jb,jc,jd,jw,k,k2,k4,lj,m,j,mj,mj2,pass,tgle; float rp,up,wr[4] __attribute((aligned(16))); float wu[4] __attribute((aligned(16))); float *a,*b,*c,*d; const vector float vminus = (vector float){-0.,0.,-0.,0.}; const vector float vzero = (vector float){0.,0.,0.,0.}; const vector unsigned char pv3201 = (vector unsigned char){4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11}; vector float V0,V1,V2,V3,V4,V5,V6,V7; vector float V8,V9,V10,V11,V12,V13,V14,V15; if(n<=1){ y[0][0] = x[0][0]; y[0][1] = x[0][1]; return; } m = (int) (log((float) n)/log(1.99)); mj = 1; mj2 = 2; lj = n/2; /* first pass thru data: x -> y */ for(j=0;j<lj;j++){ jb = n/2+j; jc = j*mj2; jd = jc + 1; rp = w[j][0]; up = w[j][1]; if(sign<0.0) up = -up; y[jd][0] = rp*(x[j][0] - x[jb][0]) - up*(x[j][1] - x[jb][1]); y[jd][1] = up*(x[j][0] - x[jb][0]) + rp*(x[j][1] - x[jb][1]); y[jc][0] = x[j][0] + x[jb][0]; y[jc][1] = x[j][1] + x[jb][1]; } if(n==2) return; /* next pass is mj = 2 */ mj = 2; mj2 = 4; lj = n/4; a = (float *)&y[0][0]; b = (float *)&y[n/2][0]; c = (float *)&x[0][0]; d = (float *)&x[mj][0]; if(n==4){ c = (float *)&y[0][0]; d = (float *)&y[mj][0]; } for(j=0;j<lj;j++){ jw = j*mj; jc = j*mj2; jd = 2*jc; rp = w[jw][0]; up = w[jw][1]; if(sign<0.0) up = -up; wr[0] = rp; wr[1] = rp; wr[2] = rp; wr[3] = rp; wu[0] = up; wu[1] = up; wu[2] = up; wu[3] = up; V6 = vec_ld(0,wr); V7 = vec_ld(0,wu); V7 = vec_xor(V7,vminus); V0 = vec_ld(0,(vector float *) (a+jc)); V1 = vec_ld(0,(vector float *) (b+jc)); V2 = vec_add(V0,V1); /* a + b */ vec_st(V2,0,(vector float *) (c+jd)); /* store c */ V3 = vec_sub(V0,V1); /* a - b */ V4 = vec_perm(V3,V3,pv3201); V0 = vec_madd(V6,V3,vzero); V1 = vec_madd(V7,V4,vzero); V2 = vec_add(V0,V1); /* w*(a - b) */ vec_st(V2,0,(vector float*) (d+jd)); /* store d */ } if(n==4) return; mj *= 2; mj2 = 2*mj; lj = n/mj2; tgle = 0; for(pass=2;pass<m-1;pass++){ if(tgle){ a = (float *)&y[0][0]; b = (float *)&y[n/2][0]; c = (float *)&x[0][0]; d = (float *)&x[mj][0]; tgle = 0; } else { a = (float *)&x[0][0]; b = (float *)&x[n/2][0]; c = (float *)&y[0][0]; d = (float *)&y[mj][0]; tgle = 1; } for(j=0; j<lj; j++){ jw = j*mj; jc = j*mj2; jd = 2*jc; rp = w[jw][0]; up = w[jw][1]; if(sign<0.0) up = -up; wr[0] = rp; wr[1] = rp; wr[2] = rp; wr[3] = rp; wu[0] = up; wu[1] = up; wu[2] = up; wu[3] = up; V6 = vec_ld(0,wr); V7 = vec_ld(0,wu); V7 = vec_xor(V7,vminus); for(k=0; k<mj; k+=4){ k2 = 2*k; k4 = k2+4; V0 = vec_ld(0,(vector float *) (a+jc+k2)); V1 = vec_ld(0,(vector float *) (b+jc+k2)); V2 = vec_add(V0,V1); /* a + b */ vec_st(V2,0,(vector float*) (c+jd+k2)); /* store c */ V3 = vec_sub(V0,V1); /* a - b */ V4 = vec_perm(V3,V3,pv3201); V0 = vec_madd(V6,V3,vzero); V1 = vec_madd(V7,V4,vzero); V2 = vec_add(V0,V1); /* w*(a - b) */ vec_st(V2,0,(vector float *) (d+jd+k2)); /* store d */ V8 = vec_ld(0,(vector float *) (a+jc+k4)); V9 = vec_ld(0,(vector float *) (b+jc+k4)); V10 = vec_add(V8,V9); /* a + b */ vec_st(V10,0,(vector float *) (c+jd+k4)); /* store c */ V11 = vec_sub(V8,V9); /* a - b */ V12 = vec_perm(V11,V11,pv3201); V8 = vec_madd(V6,V11,vzero); V9 = vec_madd(V7,V12,vzero); V10 = vec_add(V8,V9); /* w*(a - b) */ vec_st(V10,0,(vector float *) (d+jd+k4)); /* store d */ } } mj *= 2; mj2 = 2*mj; lj = n/mj2; } /* last pass thru data: in-place if previous in y */ c = (float *)&y[0][0]; d = (float *)&y[n/2][0]; if(tgle) { a = (float *)&y[0][0]; b = (float *)&y[n/2][0]; } else { a = (float *)&x[0][0]; b = (float *)&x[n/2][0]; } for(k=0; k<(n/2); k+=4){ k2 = 2*k; k4 = k2+4; V0 = vec_ld(0,(vector float *) (a+k2)); V1 = vec_ld(0,(vector float *) (b+k2)); V2 = vec_add(V0,V1); /* a + b */ vec_st(V2,0,(vector float*) (c+k2)); /* store c */ V3 = vec_sub(V0,V1); /* a - b */ vec_st(V3,0,(vector float *) (d+k2)); /* store d */ V4 = vec_ld(0,(vector float *) (a+k4)); V5 = vec_ld(0,(vector float *) (b+k4)); V6 = vec_add(V4,V5); /* a + b */ vec_st(V6,0,(vector float *) (c+k4)); /* store c */ V7 = vec_sub(V4,V5); /* a - b */ vec_st(V7,0,(vector float *) (d+k4)); /* store d */ } } // LLVM LOCAL begin // Implementations of sin() and cos() may vary slightly in the accuracy of // their results, typically only in the least significant bit. Round to make // the results consistent across platforms. typedef union { double d; unsigned long long ll; } dbl_ll_union; static double LLVMsin(double d) { dbl_ll_union u; u.d = sin(d); u.ll = (u.ll + 1) & ~1ULL; return u.d; } static double LLVMcos(double d) { dbl_ll_union u; u.d = cos(d); u.ll = (u.ll + 1) & ~1ULL; return u.d; } // LLVM LOCAL end void cffti(int n, float w[][2]) { /* initialization routine for cfft2: computes cos(twopi*k),sin(twopi*k) for k=0..n/2-1 - the "twiddle factors" for a binary radix FFT */ int i,n2; float aw,arg,pi; pi = 3.141592653589793; n2 = n/2; aw = 2.0*pi/((float)n); for(i=0;i<n2;i++){ arg = aw*((float)i); w[i][0] = LLVMcos(arg); w[i][1] = LLVMsin(arg); } } #include <math.h> float ggl(float *ds) { /* generate u(0,1) distributed random numbers. Seed ds must be saved between calls. ggl is essentially the same as the IMSL routine RNUM. W. Petersen and M. Troyer, 24 Oct. 2002, ETHZ: a modification of a fortran version from I. Vattulainen, Tampere Univ. of Technology, Finland, 1992 */ double t,d2=0.2147483647e10; t = (float) *ds; t = fmod(0.16807e5*t,d2); *ds = (float) t; return((float) ((t-1.0e0)/(d2-1.0e0))); }
mit
yashkin/libhuffman
src/encoder.c
2
10305
#include <string.h> #include <unistd.h> #include "huffman/bufio.h" #include "huffman/encoder.h" #include "huffman/malloc.h" #include "huffman/sys.h" #include "huffman/histogram.h" #include "huffman/io.h" #include "huffman/symbol.h" #include "huffman/tree.h" struct __huf_encoder { // Read-only field with encoder configuration. huf_config_t *config; // Bit buffer. huf_bit_read_writer_t bit_writer; // Stores leaves and the root of the Huffman tree. huf_tree_t *huffman_tree; // char_coding represents map of binary encoding for // particular byte. huf_symbol_mapping_t *mapping; // Frequencies of the symbols occurrence. huf_histogram_t *histogram; // Buffered reader instance. huf_bufio_read_writer_t *bufio_writer; // Buffered writer instance. huf_bufio_read_writer_t *bufio_reader; }; // Create a mapping of 8-bit bytes to the Huffman encoding. static huf_error_t __huf_create_char_coding(huf_encoder_t *self) { routine_m(); huf_error_t err; huf_symbol_mapping_element_t *element = NULL; uint8_t coding[HUF_1KIB_BUFFER] = {0}; routine_param_m(self); for (size_t index = 0; index < self->mapping->length; index++) { const huf_node_t *node = self->huffman_tree->leaves[index]; if (!node) { continue; } size_t position = sizeof(coding); // Print node to the string. err = huf_node_to_string(node, coding, &position); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Create mapping element and inialize it with coding string. err = huf_symbol_mapping_element_init(&element, coding, position); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Insert coding element to the symbol-aware position. err = huf_symbol_mapping_insert(self->mapping, index, element); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } } routine_yield_m(); } // Encode chunk of data. static huf_error_t __huf_encode_block(huf_encoder_t* self, const uint8_t *buf, uint64_t len) { routine_m(); huf_error_t err; huf_symbol_mapping_element_t *element = NULL; uint64_t pos; size_t index; routine_param_m(self); routine_param_m(buf); for (pos = 0; pos < len; pos++) { // Retrieve the next symbol coding element. err = huf_symbol_mapping_get(self->mapping, buf[pos], &element); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } for (index = element->length; index > 0; index--) { // Fill the next bit of the encoded byte. huf_bit_write(&self->bit_writer, element->coding[index - 1]); if (self->bit_writer.offset) { continue; } // If buffer is full, then dump it to the writer buffer. err = huf_bufio_write_uint8(self->bufio_writer, self->bit_writer.bits); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } huf_bit_read_writer_reset(&self->bit_writer); } } if (self->bit_writer.offset != 8) { err = huf_bufio_write_uint8(self->bufio_writer, self->bit_writer.bits); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } } routine_yield_m(); } // Create a new instance of the Huffman encoder. huf_error_t huf_encoder_init(huf_encoder_t **self, const huf_config_t *config) { routine_m(); huf_encoder_t *self_ptr = NULL; huf_config_t *encoder_config = NULL; routine_param_m(self); routine_param_m(config); huf_error_t err = huf_malloc(void_pptr_m(&self_ptr), sizeof(huf_encoder_t), 1); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } *self = self_ptr; // Save the encoder configuration. err = huf_config_init(&encoder_config); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } memcpy(encoder_config, config, sizeof(*config)); // If size of encoding chunk set to zero then length of the // data to encode will be treated as size of the chunk. if (!encoder_config->blocksize) { encoder_config->blocksize = encoder_config->length; } self_ptr->config = encoder_config; // Allocate memory for Huffman tree. err = huf_tree_init(&self_ptr->huffman_tree); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_symbol_mapping_init(&self_ptr->mapping, HUF_ASCII_COUNT); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Allocate memory for the frequency histogram. err = huf_histogram_init(&self_ptr->histogram, 1, HUF_HISTOGRAM_LEN); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Create buffered writer instance. If writer buffer size // set to zero, the 64 KiB buffer will be used by default. err = huf_bufio_read_writer_init(&self_ptr->bufio_writer, self_ptr->config->writer, self_ptr->config->writer_buffer_size); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Create buffered reader instance. If reader buffer size // set to zero, the 64 KiB buffer will be used by default. err = huf_bufio_read_writer_init(&self_ptr->bufio_reader, self_ptr->config->reader, self_ptr->config->reader_buffer_size); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } routine_yield_m(); } // Release memory occupied by the Huffman encoder. huf_error_t huf_encoder_free(huf_encoder_t **self) { routine_m(); huf_error_t err; huf_encoder_t *self_ptr; routine_param_m(self); self_ptr = *self; err = huf_tree_free(&self_ptr->huffman_tree); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_bufio_read_writer_free(&self_ptr->bufio_writer); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_bufio_read_writer_free(&self_ptr->bufio_reader); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_histogram_free(&self_ptr->histogram); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_symbol_mapping_free(&self_ptr->mapping); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_config_free(&self_ptr->config); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } free(self_ptr); *self = NULL; routine_yield_m(); } // Encode the data according to the provided // configuration. huf_error_t huf_encode(const huf_config_t *config) { routine_m(); huf_error_t err; huf_encoder_t *self = NULL; uint8_t *buf = NULL; int16_t tree_head[HUF_BTREE_LEN] = {0}; int16_t actual_tree_length = 0; size_t tree_length = 0; err = huf_encoder_init(&self, config); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_malloc(void_pptr_m(&buf), sizeof(uint8_t), self->config->blocksize); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } size_t left_to_read = self->config->length; size_t need_to_read; while (left_to_read > 0) { need_to_read = self->config->blocksize; if (left_to_read < need_to_read) { need_to_read = left_to_read; } // Read the next chunk of data, that we are going to encode. err = huf_bufio_read(self->bufio_reader, buf, need_to_read); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_histogram_populate(self->histogram, buf, need_to_read); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_tree_from_histogram(self->huffman_tree, self->histogram); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = __huf_create_char_coding(self); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Write serialized tree into buffer. err = huf_tree_serialize(self->huffman_tree, tree_head, &tree_length); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } actual_tree_length = tree_length; // Write the size of the next chunk. err = huf_bufio_write(self->bufio_writer, &need_to_read, sizeof(need_to_read)); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Write the length of the serialized Huffman tree. err = huf_bufio_write(self->bufio_writer, &actual_tree_length, sizeof(actual_tree_length)); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Write the serialized tree itself. err = huf_bufio_write(self->bufio_writer, tree_head, tree_length * sizeof(int16_t)); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } // Reset the bit writer before encoging the next chunk of data. huf_bit_read_writer_reset(&self->bit_writer); // Write data err = __huf_encode_block(self, buf, need_to_read); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } left_to_read -= need_to_read; // If there is no more data to read, then skip reset of the histogram. if (!left_to_read) { continue; } err = huf_tree_reset(self->huffman_tree); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_histogram_reset(self->histogram); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } err = huf_symbol_mapping_reset(self->mapping); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } } // Flush buffer to the file. err = huf_bufio_read_writer_flush(self->bufio_writer); if (err != HUF_ERROR_SUCCESS) { routine_error_m(err); } routine_ensure_m(); huf_encoder_free(&self); free(buf); routine_defer_m(); }
mit
maurer/tiamat
samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68a.c
2
4129
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68a.c Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-68a.tmpl.c */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fgets Read data from the console using fgets() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) #define HELLO_STRING "hello" size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_badData; size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_goodG2BData; size_t CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_goodB2GData; #ifndef OMITBAD /* bad function declaration */ void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_badSink(); void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_bad() { size_t data; /* Initialize data */ data = 0; { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* POTENTIAL FLAW: Read data from the console using fgets() */ if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) { /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } else { printLine("fgets() failed."); } } CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_badData = data; CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_goodG2BSink(); void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_goodB2GSink(); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { size_t data; /* Initialize data */ data = 0; /* FIX: Use a relatively small number for memory allocation */ data = 20; CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_goodG2BData = data; CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_goodG2BSink(); } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { size_t data; /* Initialize data */ data = 0; { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* POTENTIAL FLAW: Read data from the console using fgets() */ if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) { /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } else { printLine("fgets() failed."); } } CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_goodB2GData = data; CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68b_goodB2GSink(); } void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_68_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
mit
coinkeeper/2015-06-22_18-45_quatloo
src/qt/addressbookpage.cpp
2
12971
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "editaddressdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #ifdef USE_QRCODE #include "qrcodedialog.h" #endif #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->verifyMessage->setIcon(QIcon()); ui->signMessage->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCode->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->exportButton->hide(); break; case ForEditing: ui->buttonBox->setVisible(false); break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Quatloo addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); ui->signMessage->setVisible(false); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Quatloo addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.")); ui->deleteAddress->setVisible(false); ui->signMessage->setVisible(true); break; } // Context menu actions QAction *copyAddressAction = new QAction(ui->copyAddress->text(), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *sendCoinsAction = new QAction(tr("Send &Coins"), this); QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this); QAction *signMessageAction = new QAction(ui->signMessage->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); if(tab == SendingTab) contextMenu->addAction(sendCoinsAction); #ifdef USE_QRCODE contextMenu->addAction(showQRCodeAction); #endif if(tab == ReceivingTab) contextMenu->addAction(signMessageAction); else if(tab == SendingTab) contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(onSendCoinsAction())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_signMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit signMessage(address); } } void AddressBookPage::on_verifyMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit verifyMessage(address); } } void AddressBookPage::onSendCoinsAction() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit sendCoins(address); } } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); ui->signMessage->setEnabled(false); ui->signMessage->setVisible(false); ui->verifyMessage->setEnabled(true); ui->verifyMessage->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); ui->signMessage->setEnabled(true); ui->signMessage->setVisible(true); ui->verifyMessage->setEnabled(false); ui->verifyMessage->setVisible(false); break; } ui->copyAddress->setEnabled(true); ui->showQRCode->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->showQRCode->setEnabled(false); ui->copyAddress->setEnabled(false); ui->signMessage->setEnabled(false); ui->verifyMessage->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void AddressBookPage::on_showQRCode_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); QString label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
mit
nudnud/nud-unofficial
src/rpcblockchain.cpp
2
8979
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014 The NUD developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best (tip) block in the longest block chain."); return hashBestChain.GetHex(); } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount LTC/KB>\n" "<amount> is a real and is rounded to the nearest 0.00000001 LTC per KB"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value setdelegatefee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setdelegatefee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nDelegateFee = nAmount; return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [verbose=true]\n" "If verbose is false, returns a string that is serialized, hex-encoded data for block <hash>.\n" "If verbose is true, returns an Object with information about block <hash>." ); std::string strHash = params[0].get_str(); uint256 hash(strHash); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } Value gettxoutsetinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "Returns statistics about the unspent transaction output set."); Object ret; CCoinsStats stats; if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (boost::int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } Value gettxout(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout <txid> <n> [includemempool=true]\n" "Returns details about an unspent transaction output."); Object ret; std::string strHash = params[0].get_str(); uint256 hash(strHash); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(*pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return Value::null; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return Value::null; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return Value::null; ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); Object o; ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } Value verifychain(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "verifychain [check level] [num blocks]\n" "Verifies blockchain database."); int nCheckLevel = GetArg("-checklevel", 3); int nCheckDepth = GetArg("-checkblocks", 288); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return VerifyDB(nCheckLevel, nCheckDepth); }
mit
Pocketart/typhoonclawvex
Musical_Instruments_2017_2018/Musical_Glove/OLD CODE/gloves/Gloves_R/teensy/avr/libraries/Audio/effect_midside.cpp
2
3715
/* Audio Library for Teensy 3.X * Copyright (c) 2015, Hedde Bosman * * Development of this audio library was funded by PJRC.COM, LLC by sales of * Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop * open source software by purchasing Teensy or other PJRC products. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice, development funding notice, and this permission * notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "effect_midside.h" void AudioEffectMidSide::update(void) { audio_block_t *blocka, *blockb; uint32_t *pa, *pb, *end; uint32_t a12, a34; //, a56, a78; uint32_t b12, b34; //, b56, b78; blocka = receiveWritable(0); // left (encoding) or mid (decoding) blockb = receiveWritable(1); // right (encoding) or side (decoding) if (!blocka || !blockb) { if (blocka) release(blocka); // maybe an extra if statement here but if one if (blockb) release(blockb); // of the blocks is NULL then it's trouble anyway return; } #if defined(KINETISK) pa = (uint32_t *)(blocka->data); pb = (uint32_t *)(blockb->data); end = pa + AUDIO_BLOCK_SAMPLES/2; if (encoding) { while (pa < end) { // mid[i] = (blocka[i] + blockb[i])/2; // div2 to prevent overflows // side[i] = (blocka[i] - blockb[i])/2; // div2 to prevent overflows // L[i] = (mid[i] + side[i])/2; // R[i] = (mid[i] - side[i])/2; a12 = signed_halving_add_16_and_16(*pa, *pb); // mid12 a34 = signed_halving_add_16_and_16(*(pa+1), *(pb+1)); //mid34 b12 = signed_halving_subtract_16_and_16(*pa, *pb); // side12 b34 = signed_halving_subtract_16_and_16(*(pa+1), *(pb+1)); // side34 *pa++ = a12; *pa++ = a34; *pb++ = b12; *pb++ = b34; } } else { while (pa < end) { // L[i] = mid[i] + side[i]); // R[i] = mid[i] - side[i]); // Because the /2 has already been applied in the encoding, // we shouldn't have to add it here. // However... because of the posibility that the user has // modified mid or side such that // it could overflow, we have to: // a) preventively do a (x/2+y/2)*2 again, causing bit reduction // or b) perform saturation or something. // While (b) could produce artifacts if saturated, I'll go for // that option to preserve precision // QADD16 and QSUB16 perform saturating add/sub a12 = signed_add_16_and_16(*pa, *pb); // left12 a34 = signed_add_16_and_16(*(pa+1), *(pb+1)); // left34 b12 = signed_subtract_16_and_16(*pa, *pb); // right12 b34 = signed_subtract_16_and_16(*(pa+1), *(pb+1)); // right34 *pa++ = a12; *pa++ = a34; *pb++ = b12; *pb++ = b34; } } transmit(blocka, 0); // mid (encoding) or left (decoding) transmit(blockb, 1); // side (encoding) or right (decoding) #endif release(blocka); release(blockb); }
mit
msmolens/bayer-pattern-demosaicing
bayer_cg/src/RenderTexture.cpp
2
70424
//--------------------------------------------------------------------------- // File : RenderTexture.cpp //--------------------------------------------------------------------------- // Copyright (c) 2002-2004 Mark J. Harris //--------------------------------------------------------------------------- // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any // damages arising from the use of this software. // // Permission is granted to anyone to use this software for any // purpose, including commercial applications, and to alter it and // redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you // must not claim that you wrote the original software. If you use // this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and // must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // -------------------------------------------------------------------------- // Credits: // Original RenderTexture class: Mark J. Harris // Original Render to Depth Texture support: Thorsten Scheuermann // Linux Copy-to-texture: Eric Werness // Various Bug Fixes: Daniel (Redge) Sperl // Bill Baxter // // -------------------------------------------------------------------------- /** * @file RenderTexture.cpp * * Implementation of class RenderTexture. A multi-format render to * texture wrapper. */ #pragma warning(disable:4786) #include "RenderTexture.h" #include <GL/glut.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #ifdef _WIN32 #pragma comment(lib, "gdi32.lib") // required for GetPixelFormat() #endif using namespace std; //--------------------------------------------------------------------------- // Function : RenderTexture::RenderTexture // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::RenderTexture() * @brief Mode-string-based Constructor. */ RenderTexture::RenderTexture(const char *strMode) : _iWidth(0), _iHeight(0), _bIsTexture(false), _bIsDepthTexture(false), _bHasARBDepthTexture(true), // [Redge] #ifdef _WIN32 _eUpdateMode(RT_RENDER_TO_TEXTURE), #else _eUpdateMode(RT_COPY_TO_TEXTURE), #endif _bInitialized(false), _iNumAuxBuffers(0), _bIsBufferBound(false), _iCurrentBoundBuffer(0), _iNumDepthBits(0), _iNumStencilBits(0), _bFloat(false), _bDoubleBuffered(false), _bPowerOf2(true), _bRectangle(false), _bMipmap(false), _bShareObjects(false), _bCopyContext(false), #ifdef _WIN32 _hDC(NULL), _hGLContext(NULL), _hPBuffer(NULL), _hPreviousDC(0), _hPreviousContext(0), #else _pDisplay(NULL), _hGLContext(NULL), _hPBuffer(0), _hPreviousContext(0), _hPreviousDrawable(0), #endif _iTextureTarget(GL_NONE), _iTextureID(0), _iDepthTextureID(0), _pPoorDepthTexture(0) // [Redge] { _iNumColorBits[0] = _iNumColorBits[1] = _iNumColorBits[2] = _iNumColorBits[3] = 0; #ifdef _WIN32 _pixelFormatAttribs.push_back(WGL_DRAW_TO_PBUFFER_ARB); _pixelFormatAttribs.push_back(true); _pixelFormatAttribs.push_back(WGL_SUPPORT_OPENGL_ARB); _pixelFormatAttribs.push_back(true); _pbufferAttribs.push_back(WGL_PBUFFER_LARGEST_ARB); _pbufferAttribs.push_back(true); #else _pbufferAttribs.push_back(GLX_RENDER_TYPE_SGIX); _pbufferAttribs.push_back(GLX_RGBA_BIT_SGIX); _pbufferAttribs.push_back(GLX_DRAWABLE_TYPE_SGIX); _pbufferAttribs.push_back(GLX_PBUFFER_BIT_SGIX); #endif _ParseModeString(strMode, _pixelFormatAttribs, _pbufferAttribs); #ifdef _WIN32 _pixelFormatAttribs.push_back(0); _pbufferAttribs.push_back(0); #else _pixelFormatAttribs.push_back(None); #endif } //--------------------------------------------------------------------------- // Function : RenderTexture::~RenderTexture // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::~RenderTexture() * @brief Destructor. */ RenderTexture::~RenderTexture() { _Invalidate(); } //--------------------------------------------------------------------------- // Function : _wglGetLastError // Description : //--------------------------------------------------------------------------- /** * @fn wglGetLastError() * @brief Returns the last windows error generated. */ #ifdef _WIN32 void _wglGetLastError() { #ifdef _DEBUG DWORD err = GetLastError(); switch(err) { case ERROR_INVALID_PIXEL_FORMAT: fprintf(stderr, "RenderTexture Win32 Error: ERROR_INVALID_PIXEL_FORMAT\n"); break; case ERROR_NO_SYSTEM_RESOURCES: fprintf(stderr, "RenderTexture Win32 Error: ERROR_NO_SYSTEM_RESOURCES\n"); break; case ERROR_INVALID_DATA: fprintf(stderr, "RenderTexture Win32 Error: ERROR_INVALID_DATA\n"); break; case ERROR_INVALID_WINDOW_HANDLE: fprintf(stderr, "RenderTexture Win32 Error: ERROR_INVALID_WINDOW_HANDLE\n"); break; case ERROR_RESOURCE_TYPE_NOT_FOUND: fprintf(stderr, "RenderTexture Win32 Error: ERROR_RESOURCE_TYPE_NOT_FOUND\n"); break; case ERROR_SUCCESS: // no error break; default: LPVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); fprintf(stderr, "RenderTexture Win32 Error %d: %s\n", err, lpMsgBuf); LocalFree( lpMsgBuf ); break; } SetLastError(0); #endif // _DEBUG } #endif //--------------------------------------------------------------------------- // Function : PrintExtensionError // Description : //--------------------------------------------------------------------------- /** * @fn PrintExtensionError( char* strMsg, ... ) * @brief Prints an error about missing OpenGL extensions. */ void PrintExtensionError( char* strMsg, ... ) { fprintf(stderr, "Error: RenderTexture requires the following unsupported " "OpenGL extensions: \n"); char strBuffer[512]; va_list args; va_start(args, strMsg); #ifdef _WIN32 _vsnprintf( strBuffer, 512, strMsg, args ); #else vsnprintf( strBuffer, 512, strMsg, args ); #endif va_end(args); fprintf(stderr, strMsg); } //--------------------------------------------------------------------------- // Function : RenderTexture::Initialize // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::Initialize(int width, int height, bool shareObjects, bool copyContext); * @brief Initializes the RenderTexture, sharing display lists and textures if specified. * * This function creates of the p-buffer. It can only be called once a GL * context has already been created. */ bool RenderTexture::Initialize(int width, int height, bool shareObjects /* = true */, bool copyContext /* = false */) { assert(width > 0 && height > 0); _iWidth = width; _iHeight = height; _bPowerOf2 = IsPowerOfTwo(width) && IsPowerOfTwo(height); _bShareObjects = shareObjects; _bCopyContext = copyContext; // Check if this is an NVXX GPU and verify necessary extensions. if (!_VerifyExtensions()) return false; if (_bInitialized) _Invalidate(); #if _WIN32 // Get the current context. HDC hdc = wglGetCurrentDC(); if (NULL == hdc) _wglGetLastError(); HGLRC hglrc = wglGetCurrentContext(); if (NULL == hglrc) _wglGetLastError(); int iFormat = 0; unsigned int iNumFormats; if (_bCopyContext) { // Get the pixel format for the on-screen window. iFormat = GetPixelFormat(hdc); if (iFormat == 0) { fprintf(stderr, "RenderTexture Error: GetPixelFormat() failed.\n"); return false; } } else { if (!wglChoosePixelFormatARB(hdc, &_pixelFormatAttribs[0], NULL, 1, &iFormat, &iNumFormats)) { fprintf(stderr, "RenderTexture Error: wglChoosePixelFormatARB() failed.\n"); _wglGetLastError(); return false; } if ( iNumFormats <= 0 ) { fprintf(stderr, "RenderTexture Error: Couldn't find a suitable " "pixel format.\n"); _wglGetLastError(); return false; } } // Create the p-buffer. _hPBuffer = wglCreatePbufferARB(hdc, iFormat, _iWidth, _iHeight, &_pbufferAttribs[0]); if (!_hPBuffer) { fprintf(stderr, "RenderTexture Error: wglCreatePbufferARB() failed.\n"); _wglGetLastError(); return false; } // Get the device context. _hDC = wglGetPbufferDCARB( _hPBuffer); if ( !_hDC ) { fprintf(stderr, "RenderTexture Error: wglGetGetPbufferDCARB() failed.\n"); _wglGetLastError(); return false; } // Create a gl context for the p-buffer. if (_bCopyContext) { // Let's use the same gl context.. // Since the device contexts are compatible (i.e. same pixelformat), // we should be able to use the same gl rendering context. _hGLContext = hglrc; } else { _hGLContext = wglCreateContext( _hDC ); if ( !_hGLContext ) { fprintf(stderr, "RenderTexture Error: wglCreateContext() failed.\n"); _wglGetLastError(); return false; } } // Share lists, texture objects, and program objects. if( _bShareObjects ) { if( !wglShareLists(hglrc, _hGLContext) ) { fprintf(stderr, "RenderTexture Error: wglShareLists() failed.\n"); _wglGetLastError(); return false; } } // Determine the actual width and height we were able to create. wglQueryPbufferARB( _hPBuffer, WGL_PBUFFER_WIDTH_ARB, &_iWidth ); wglQueryPbufferARB( _hPBuffer, WGL_PBUFFER_HEIGHT_ARB, &_iHeight ); _bInitialized = true; // get the actual number of bits allocated: int attrib = WGL_RED_BITS_ARB; //int bits[6]; int value; _iNumColorBits[0] = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_GREEN_BITS_ARB; _iNumColorBits[1] = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_BLUE_BITS_ARB; _iNumColorBits[2] = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_ALPHA_BITS_ARB; _iNumColorBits[3] = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_DEPTH_BITS_ARB; _iNumDepthBits = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_STENCIL_BITS_ARB; _iNumStencilBits = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? value : 0; attrib = WGL_DOUBLE_BUFFER_ARB; _bDoubleBuffered = (wglGetPixelFormatAttribivARB(_hDC, iFormat, 0, 1, &attrib, &value)) ? (value?true:false) : false; #if defined(_DEBUG) | defined(DEBUG) fprintf(stderr, "Created a %dx%d RenderTexture with BPP(%d, %d, %d, %d)", _iWidth, _iHeight, _iNumColorBits[0], _iNumColorBits[1], _iNumColorBits[2], _iNumColorBits[3]); if (_iNumDepthBits) fprintf(stderr, " depth=%d", _iNumDepthBits); if (_iNumStencilBits) fprintf(stderr, " stencil=%d", _iNumStencilBits); if (_bDoubleBuffered) fprintf(stderr, " double buffered"); fprintf(stderr, "\n"); #endif #else // !_WIN32 _pDisplay = glXGetCurrentDisplay(); GLXContext context = glXGetCurrentContext(); int screen = DefaultScreen(_pDisplay); XVisualInfo *visInfo; int iFormat = 0; int iNumFormats; int attrib = 0; GLXFBConfigSGIX *fbConfigs; int nConfigs; fbConfigs = glXChooseFBConfigSGIX(_pDisplay, screen, &_pixelFormatAttribs[0], &nConfigs); if (nConfigs == 0 || !fbConfigs) { fprintf(stderr, "RenderTexture Error: Couldn't find a suitable pixel format.\n"); return false; } // Pick the first returned format that will return a pbuffer for (int i=0;i<nConfigs;i++) { _hPBuffer = glXCreateGLXPbufferSGIX(_pDisplay, fbConfigs[i], _iWidth, _iHeight, NULL); if (_hPBuffer) { _hGLContext = glXCreateContextWithConfigSGIX(_pDisplay, fbConfigs[i], GLX_RGBA_TYPE, _bShareObjects ? context : NULL, True); break; } } if (!_hPBuffer) { fprintf(stderr, "RenderTexture Error: glXCreateGLXPbufferSGIX() failed.\n"); return false; } if(!_hGLContext) { // Try indirect _hGLContext = glXCreateContext(_pDisplay, visInfo, _bShareObjects ? context : NULL, False); if ( !_hGLContext ) { fprintf(stderr, "RenderTexture Error: glXCreateContext() failed.\n"); return false; } } glXQueryGLXPbufferSGIX(_pDisplay, _hPBuffer, GLX_WIDTH_SGIX, (GLuint*)&_iWidth); glXQueryGLXPbufferSGIX(_pDisplay, _hPBuffer, GLX_HEIGHT_SGIX, (GLuint*)&_iHeight); _bInitialized = true; // XXX Query the color format #endif // Now that the pbuffer is created, allocate any texture objects needed, // and initialize them (for CTT updates only). These must be allocated // in the context of the pbuffer, though, or the RT won't work without // wglShareLists. #ifdef _WIN32 if (false == wglMakeCurrent( _hDC, _hGLContext)) { _wglGetLastError(); return false; } #else _hPreviousContext = glXGetCurrentContext(); _hPreviousDrawable = glXGetCurrentDrawable(); if (False == glXMakeCurrent(_pDisplay, _hPBuffer, _hGLContext)) { return false; } #endif bool result = _InitializeTextures(); #ifdef _WIN32 BindBuffer(WGL_FRONT_LEFT_ARB); _BindDepthBuffer(); #endif #ifdef _WIN32 // make the previous rendering context current if (false == wglMakeCurrent( hdc, hglrc)) { _wglGetLastError(); return false; } #else if (False == glXMakeCurrent(_pDisplay, _hPreviousDrawable, _hPreviousContext)) { return false; } #endif return result; } //--------------------------------------------------------------------------- // Function : RenderTexture::_Invalidate // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_Invalidate() * @brief Returns the pbuffer memory to the graphics device. * */ bool RenderTexture::_Invalidate() { _iNumColorBits[0] = _iNumColorBits[1] = _iNumColorBits[2] = _iNumColorBits[3] = 0; _iNumDepthBits = 0; _iNumStencilBits = 0; if (_bIsTexture) glDeleteTextures(1, &_iTextureID); if (_bIsDepthTexture) { // [Redge] if (!_bHasARBDepthTexture) delete[] _pPoorDepthTexture; // [/Redge] glDeleteTextures(1, &_iDepthTextureID); } #if _WIN32 if ( _hPBuffer ) { // Check if we are currently rendering in the pbuffer if (wglGetCurrentContext() == _hGLContext) wglMakeCurrent(0,0); if (!_bCopyContext) wglDeleteContext( _hGLContext); wglReleasePbufferDCARB( _hPBuffer, _hDC); wglDestroyPbufferARB( _hPBuffer ); _hPBuffer = 0; return true; } #else if ( _hPBuffer ) { if(glXGetCurrentContext() == _hGLContext) // XXX I don't know if this is right at all glXMakeCurrent(_pDisplay, _hPBuffer, 0); glXDestroyGLXPbufferSGIX(_pDisplay, _hPBuffer); _hPBuffer = 0; return true; } #endif // [WVB] do we need to call _ReleaseBoundBuffers() too? return false; } //--------------------------------------------------------------------------- // Function : RenderTexture::Reset // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::Reset() * @brief Resets the resolution of the offscreen buffer. * * Causes the buffer to delete itself. User must call Initialize() again * before use. */ bool RenderTexture::Reset(const char *strMode, ...) { _iWidth = 0; _iHeight = 0; _bIsTexture = false; _bIsDepthTexture = false, _bHasARBDepthTexture = true; #ifdef _WIN32 _eUpdateMode = RT_RENDER_TO_TEXTURE; #else _eUpdateMode = RT_COPY_TO_TEXTURE; #endif _bInitialized = false; _iNumAuxBuffers = 0; _bIsBufferBound = false; _iCurrentBoundBuffer = 0; _iNumDepthBits = 0; _iNumStencilBits = 0; _bDoubleBuffered = false; _bFloat = false; _bPowerOf2 = true; _bRectangle = false; _bMipmap = false; _bShareObjects = false; _bCopyContext = false; _iTextureTarget = GL_NONE; _iTextureID = 0; _iDepthTextureID = 0; _pPoorDepthTexture = 0; _pixelFormatAttribs.clear(); _pbufferAttribs.clear(); if (IsInitialized() && !_Invalidate()) { fprintf(stderr, "RenderTexture::Reset(): failed to invalidate.\n"); return false; } _iNumColorBits[0] = _iNumColorBits[1] = _iNumColorBits[2] = _iNumColorBits[3] = 0; #ifdef _WIN32 _pixelFormatAttribs.push_back(WGL_DRAW_TO_PBUFFER_ARB); _pixelFormatAttribs.push_back(true); _pixelFormatAttribs.push_back(WGL_SUPPORT_OPENGL_ARB); _pixelFormatAttribs.push_back(true); _pbufferAttribs.push_back(WGL_PBUFFER_LARGEST_ARB); _pbufferAttribs.push_back(true); #else _pbufferAttribs.push_back(GLX_RENDER_TYPE_SGIX); _pbufferAttribs.push_back(GLX_RGBA_BIT_SGIX); _pbufferAttribs.push_back(GLX_DRAWABLE_TYPE_SGIX); _pbufferAttribs.push_back(GLX_PBUFFER_BIT_SGIX); #endif va_list args; char strBuffer[256]; va_start(args,strMode); #ifdef _WIN32 _vsnprintf( strBuffer, 256, strMode, args ); #else vsnprintf( strBuffer, 256, strMode, args ); #endif va_end(args); _ParseModeString(strBuffer, _pixelFormatAttribs, _pbufferAttribs); #ifdef _WIN32 _pixelFormatAttribs.push_back(0); _pbufferAttribs.push_back(0); #else _pixelFormatAttribs.push_back(None); #endif return true; } //------------------------------------------------------------------------------ // Function : RenderTexture::Resize // Description : //------------------------------------------------------------------------------ /** * @fn RenderTexture::Resize(int iWidth, int iHeight) * @brief Changes the size of the offscreen buffer. * * Like Reset() this causes the buffer to delete itself. * But unlike Reset(), this call re-initializes the RenderTexture. * Note that Resize() will not work after calling Reset(), or before * calling Initialize() the first time. */ bool RenderTexture::Resize(int iWidth, int iHeight) { if (!_bInitialized) { fprintf(stderr, "RenderTexture::Resize(): must Initialize() first.\n"); return false; } if (iWidth == _iWidth && iHeight == _iHeight) { return true; } // Do same basic work as _Invalidate, but don't reset all our flags if (_bIsTexture) glDeleteTextures(1, &_iTextureID); if (_bIsDepthTexture) glDeleteTextures(1, &_iDepthTextureID); #ifdef _WIN32 if ( _hPBuffer ) { // Check if we are currently rendering in the pbuffer if (wglGetCurrentContext() == _hGLContext) wglMakeCurrent(0,0); if (!_bCopyContext) wglDeleteContext( _hGLContext); wglReleasePbufferDCARB( _hPBuffer, _hDC); wglDestroyPbufferARB( _hPBuffer ); _hPBuffer = 0; return true; } #else if ( _hPBuffer ) { if(glXGetCurrentContext() == _hGLContext) // XXX I don't know if this is right at all glXMakeCurrent(_pDisplay, _hPBuffer, 0); glXDestroyGLXPbufferSGIX(_pDisplay, _hPBuffer); _hPBuffer = 0; } #endif else { fprintf(stderr, "RenderTexture::Resize(): failed to resize.\n"); return false; } _bInitialized = false; return Initialize(iWidth, iHeight, _bShareObjects, _bCopyContext); } //--------------------------------------------------------------------------- // Function : RenderTexture::BeginCapture // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::BeginCapture() * @brief Activates rendering to the RenderTexture. */ bool RenderTexture::BeginCapture() { if (!_bInitialized) { fprintf(stderr, "RenderTexture::BeginCapture(): Texture is not initialized!\n"); return false; } #ifdef _WIN32 // cache the current context so we can reset it when EndCapture() is called. _hPreviousDC = wglGetCurrentDC(); if (NULL == _hPreviousDC) _wglGetLastError(); _hPreviousContext = wglGetCurrentContext(); if (NULL == _hPreviousContext) _wglGetLastError(); #else _hPreviousContext = glXGetCurrentContext(); _hPreviousDrawable = glXGetCurrentDrawable(); #endif _ReleaseBoundBuffers(); return _MakeCurrent(); } //--------------------------------------------------------------------------- // Function : RenderTexture::EndCapture // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::EndCapture() * @brief Ends rendering to the RenderTexture. */ bool RenderTexture::EndCapture() { if (!_bInitialized) { fprintf(stderr, "RenderTexture::EndCapture() : Texture is not initialized!\n"); return false; } _MaybeCopyBuffer(); #ifdef _WIN32 // make the previous rendering context current if (FALSE == wglMakeCurrent( _hPreviousDC, _hPreviousContext)) { _wglGetLastError(); return false; } #else if (False == glXMakeCurrent(_pDisplay, _hPreviousDrawable, _hPreviousContext)) { return false; } #endif // rebind the textures to a buffers for RTT BindBuffer(_iCurrentBoundBuffer); _BindDepthBuffer(); return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::BeginCapture(RenderTexture*) // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::BeginCapture(RenderTexture* other) * @brief Ends capture of 'other', begins capture on 'this' * * When performing a series of operations where you modify one texture after * another, it is more efficient to use this method instead of the equivalent * 'EndCapture'/'BeginCapture' pair. This method switches directly to the * new context rather than changing to the default context, and then to the * new context. * * RenderTexture doesn't have any mechanism for determining if * 'current' really is currently active, so no error will be thrown * if it is not. */ bool RenderTexture::BeginCapture(RenderTexture* current) { bool bContextReset = false; if (current == this) { return true; // no switch necessary } if (!current) { // treat as normal Begin if current is 0. return BeginCapture(); } if (!_bInitialized) { fprintf(stderr, "RenderTexture::BeginCapture(RenderTexture*): Texture is not initialized!\n"); return false; } if (!current->_bInitialized) { fprintf(stderr, "RenderTexture::BeginCapture(RenderTexture): 'current' texture is not initialized!\n"); return false; } // Sync current pbuffer with its CTT texture if necessary current->_MaybeCopyBuffer(); // pass along the previous context so we can reset it when // EndCapture() is called. #ifdef _WIN32 _hPreviousDC = current->_hPreviousDC; if (NULL == _hPreviousDC) _wglGetLastError(); _hPreviousContext = current->_hPreviousContext; if (NULL == _hPreviousContext) _wglGetLastError(); #else _hPreviousContext = current->_hPreviousContext; _hPreviousDrawable = current->_hPreviousDrawable; #endif // Unbind textures before making context current if (!_ReleaseBoundBuffers()) return false; // Make the pbuffer context current if (!_MakeCurrent()) return false; // Rebind buffers of initial RenderTexture current->BindBuffer(_iCurrentBoundBuffer); current->_BindDepthBuffer(); return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::Bind // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::Bind() * @brief Binds RGB texture. */ void RenderTexture::Bind() const { if (_bInitialized && _bIsTexture) { glBindTexture(_iTextureTarget, _iTextureID); } } //--------------------------------------------------------------------------- // Function : RenderTexture::BindDepth // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::BindDepth() * @brief Binds depth texture. */ void RenderTexture::BindDepth() const { if (_bInitialized && _bIsDepthTexture) { glBindTexture(_iTextureTarget, _iDepthTextureID); } } //--------------------------------------------------------------------------- // Function : RenderTexture::BindBuffer // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::BindBuffer() * @brief Associate the RTT texture id with 'iBuffer' (e.g. WGL_FRONT_LEFT_ARB) */ bool RenderTexture::BindBuffer( int iBuffer ) { // Must bind the texture too if (_bInitialized && _bIsTexture) { glBindTexture(_iTextureTarget, _iTextureID); #if _WIN32 if (RT_RENDER_TO_TEXTURE == _eUpdateMode && _bIsTexture && (!_bIsBufferBound || _iCurrentBoundBuffer != iBuffer)) { if (FALSE == wglBindTexImageARB(_hPBuffer, iBuffer)) { // WVB: WGL API considers binding twice to the same buffer // to be an error. But we don't want to //_wglGetLastError(); //return false; SetLastError(0); } _bIsBufferBound = true; _iCurrentBoundBuffer = iBuffer; } #endif } return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::BindBuffer // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_BindDepthBuffer() * @brief Associate the RTT depth texture id with the depth buffer */ bool RenderTexture::_BindDepthBuffer() const { #ifdef WIN32 if (_bInitialized && _bIsDepthTexture && RT_RENDER_TO_TEXTURE == _eUpdateMode) { glBindTexture(_iTextureTarget, _iDepthTextureID); if (FALSE == wglBindTexImageARB(_hPBuffer, WGL_DEPTH_COMPONENT_NV)) { _wglGetLastError(); return false; } } #endif return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::_ParseModeString // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_ParseModeString() * @brief Parses the user-specified mode string for RenderTexture parameters. */ void RenderTexture::_ParseModeString(const char *modeString, vector<int> &pfAttribs, vector<int> &pbAttribs) { if (!modeString || strcmp(modeString, "") == 0) return; _iNumComponents = 0; #ifdef _WIN32 _eUpdateMode = RT_RENDER_TO_TEXTURE; #else _eUpdateMode = RT_COPY_TO_TEXTURE; #endif int iDepthBits = 0; bool bHasStencil = false; bool bBind2D = false; bool bBindRECT = false; bool bBindCUBE = false; char *mode = strdup(modeString); vector<string> tokens; char *buf = strtok(mode, " "); while (buf != NULL) { tokens.push_back(buf); buf = strtok(NULL, " "); } for (unsigned int i = 0; i < tokens.size(); i++) { string token = tokens[i]; KeyVal kv = _GetKeyValuePair(token); if (kv.first == "rgb" && (_iNumComponents <= 1)) { if (kv.second.find("f") != kv.second.npos) _bFloat = true; vector<int> bitVec = _ParseBitVector(kv.second); if (bitVec.size() < 3) // expand the scalar to a vector { bitVec.push_back(bitVec[0]); bitVec.push_back(bitVec[0]); } #ifdef _WIN32 pfAttribs.push_back(WGL_RED_BITS_ARB); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(WGL_GREEN_BITS_ARB); pfAttribs.push_back(bitVec[1]); pfAttribs.push_back(WGL_BLUE_BITS_ARB); pfAttribs.push_back(bitVec[2]); #else pfAttribs.push_back(GLX_RED_SIZE); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(GLX_GREEN_SIZE); pfAttribs.push_back(bitVec[1]); pfAttribs.push_back(GLX_BLUE_SIZE); pfAttribs.push_back(bitVec[2]); #endif _iNumComponents += 3; continue; } else if (kv.first == "rgb") fprintf(stderr, "RenderTexture Warning: mistake in components definition " "(rgb + %d).\n", _iNumComponents); if (kv.first == "rgba" && (_iNumComponents == 0)) { if (kv.second.find("f") != kv.second.npos) _bFloat = true; vector<int> bitVec = _ParseBitVector(kv.second); if (bitVec.size() < 4) // expand the scalar to a vector { bitVec.push_back(bitVec[0]); bitVec.push_back(bitVec[0]); bitVec.push_back(bitVec[0]); } #ifdef _WIN32 pfAttribs.push_back(WGL_RED_BITS_ARB); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(WGL_GREEN_BITS_ARB); pfAttribs.push_back(bitVec[1]); pfAttribs.push_back(WGL_BLUE_BITS_ARB); pfAttribs.push_back(bitVec[2]); pfAttribs.push_back(WGL_ALPHA_BITS_ARB); pfAttribs.push_back(bitVec[3]); #else pfAttribs.push_back(GLX_RED_SIZE); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(GLX_GREEN_SIZE); pfAttribs.push_back(bitVec[1]); pfAttribs.push_back(GLX_BLUE_SIZE); pfAttribs.push_back(bitVec[2]); pfAttribs.push_back(GLX_ALPHA_SIZE); pfAttribs.push_back(bitVec[3]); #endif _iNumComponents = 4; continue; } else if (kv.first == "rgba") fprintf(stderr, "RenderTexture Warning: mistake in components definition " "(rgba + %d).\n", _iNumComponents); if (kv.first == "r" && (_iNumComponents <= 1)) { if (kv.second.find("f") != kv.second.npos) _bFloat = true; vector<int> bitVec = _ParseBitVector(kv.second); #ifdef _WIN32 pfAttribs.push_back(WGL_RED_BITS_ARB); pfAttribs.push_back(bitVec[0]); #else pfAttribs.push_back(GLX_RED_SIZE); pfAttribs.push_back(bitVec[0]); #endif _iNumComponents++; continue; } else if (kv.first == "r") fprintf(stderr, "RenderTexture Warning: mistake in components definition " "(r + %d).\n", _iNumComponents); if (kv.first == "rg" && (_iNumComponents <= 1)) { if (kv.second.find("f") != kv.second.npos) _bFloat = true; vector<int> bitVec = _ParseBitVector(kv.second); if (bitVec.size() < 2) // expand the scalar to a vector { bitVec.push_back(bitVec[0]); } #ifdef _WIN32 pfAttribs.push_back(WGL_RED_BITS_ARB); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(WGL_GREEN_BITS_ARB); pfAttribs.push_back(bitVec[1]); #else pfAttribs.push_back(GLX_RED_SIZE); pfAttribs.push_back(bitVec[0]); pfAttribs.push_back(GLX_GREEN_SIZE); pfAttribs.push_back(bitVec[1]); #endif _iNumComponents += 2; continue; } else if (kv.first == "rg") fprintf(stderr, "RenderTexture Warning: mistake in components definition " "(rg + %d).\n", _iNumComponents); if (kv.first == "depth") { if (kv.second == "") iDepthBits = 24; else iDepthBits = strtol(kv.second.c_str(), 0, 10); continue; } if (kv.first == "stencil") { bHasStencil = true; #ifdef _WIN32 pfAttribs.push_back(WGL_STENCIL_BITS_ARB); #else pfAttribs.push_back(GLX_STENCIL_SIZE); #endif if (kv.second == "") pfAttribs.push_back(8); else pfAttribs.push_back(strtol(kv.second.c_str(), 0, 10)); continue; } if (kv.first == "samples") { #ifdef _WIN32 pfAttribs.push_back(WGL_SAMPLE_BUFFERS_ARB); pfAttribs.push_back(1); pfAttribs.push_back(WGL_SAMPLES_ARB); pfAttribs.push_back(strtol(kv.second.c_str(), 0, 10)); #else pfAttribs.push_back(GLX_SAMPLE_BUFFERS_ARB); pfAttribs.push_back(1); pfAttribs.push_back(GLX_SAMPLES_ARB); pfAttribs.push_back(strtol(kv.second.c_str(), 0, 10)); #endif continue; } if (kv.first == "doublebuffer" || kv.first == "double") { #ifdef _WIN32 pfAttribs.push_back(WGL_DOUBLE_BUFFER_ARB); pfAttribs.push_back(true); #else pfAttribs.push_back(GLX_DOUBLEBUFFER); pfAttribs.push_back(True); #endif continue; } if (kv.first == "aux") { #ifdef _WIN32 pfAttribs.push_back(WGL_AUX_BUFFERS_ARB); #else pfAttribs.push_back(GLX_AUX_BUFFERS); #endif if (kv.second == "") pfAttribs.push_back(0); else pfAttribs.push_back(strtol(kv.second.c_str(), 0, 10)); continue; } if (token.find("tex") == 0) { _bIsTexture = true; if ((kv.first == "texRECT") && GLEW_NV_texture_rectangle) { _bRectangle = true; bBindRECT = true; } else if (kv.first == "texCUBE") { bBindCUBE = true; } else { bBind2D = true; } continue; } if (token.find("depthTex") == 0) { _bIsDepthTexture = true; if ((kv.first == "depthTexRECT") && GLEW_NV_texture_rectangle) { _bRectangle = true; bBindRECT = true; } else if (kv.first == "depthTexCUBE") { bBindCUBE = true; } else { bBind2D = true; } continue; } if (kv.first == "mipmap") { _bMipmap = true; continue; } if (kv.first == "rtt") { _eUpdateMode = RT_RENDER_TO_TEXTURE; continue; } if (kv.first == "ctt") { _eUpdateMode = RT_COPY_TO_TEXTURE; continue; } fprintf(stderr, "RenderTexture Error: Unknown pbuffer attribute: %s\n", token.c_str()); } // Processing of some options must be last because of interactions. // Check for inconsistent texture targets if (_bIsTexture && _bIsDepthTexture && !(bBind2D ^ bBindRECT ^ bBindCUBE)) { fprintf(stderr, "RenderTexture Warning: Depth and Color texture targets " "should match.\n"); } // Apply default bit format if none specified #ifdef _WIN32 if (0 == _iNumComponents) { pfAttribs.push_back(WGL_RED_BITS_ARB); pfAttribs.push_back(8); pfAttribs.push_back(WGL_GREEN_BITS_ARB); pfAttribs.push_back(8); pfAttribs.push_back(WGL_BLUE_BITS_ARB); pfAttribs.push_back(8); pfAttribs.push_back(WGL_ALPHA_BITS_ARB); pfAttribs.push_back(8); _iNumComponents = 4; } #endif // Depth bits if (_bIsDepthTexture && !iDepthBits) iDepthBits = 24; #ifdef _WIN32 pfAttribs.push_back(WGL_DEPTH_BITS_ARB); #else pfAttribs.push_back(GLX_DEPTH_SIZE); #endif pfAttribs.push_back(iDepthBits); // default if (!bHasStencil) { #ifdef _WIN32 pfAttribs.push_back(WGL_STENCIL_BITS_ARB); pfAttribs.push_back(0); #else pfAttribs.push_back(GLX_STENCIL_SIZE); pfAttribs.push_back(0); #endif } if (_iNumComponents < 4) { // Can't do this right now -- on NVIDIA drivers, currently get // a non-functioning pbuffer if ALPHA_BITS=0 and // WGL_BIND_TO_TEXTURE_RGB_ARB=true //pfAttribs.push_back(WGL_ALPHA_BITS_ARB); //pfAttribs.push_back(0); } #ifdef _WIN32 if (!WGLEW_NV_render_depth_texture && _bIsDepthTexture && (RT_RENDER_TO_TEXTURE == _eUpdateMode)) { #if defined(DEBUG) || defined(_DEBUG) fprintf(stderr, "RenderTexture Warning: No support found for " "render to depth texture.\n"); #endif _bIsDepthTexture = false; } #endif if ((_bIsTexture || _bIsDepthTexture) && (RT_RENDER_TO_TEXTURE == _eUpdateMode)) { #ifdef _WIN32 if (bBindRECT) { pbAttribs.push_back(WGL_TEXTURE_TARGET_ARB); pbAttribs.push_back(WGL_TEXTURE_RECTANGLE_NV); } else if (bBindCUBE) { pbAttribs.push_back(WGL_TEXTURE_TARGET_ARB); pbAttribs.push_back(WGL_TEXTURE_CUBE_MAP_ARB); } else if (bBind2D) { pbAttribs.push_back(WGL_TEXTURE_TARGET_ARB); pbAttribs.push_back(WGL_TEXTURE_2D_ARB); } if (_bMipmap) { pbAttribs.push_back(WGL_MIPMAP_TEXTURE_ARB); pbAttribs.push_back(true); } #elif defined(DEBUG) || defined(_DEBUG) printf("RenderTexture Error: Render to Texture not " "supported in Linux\n"); #endif } // Set the pixel type if (_bFloat) { #ifdef _WIN32 if (WGLEW_NV_float_buffer) { pfAttribs.push_back(WGL_PIXEL_TYPE_ARB); pfAttribs.push_back(WGL_TYPE_RGBA_ARB); pfAttribs.push_back(WGL_FLOAT_COMPONENTS_NV); pfAttribs.push_back(true); } else { pfAttribs.push_back(WGL_PIXEL_TYPE_ARB); pfAttribs.push_back(WGL_TYPE_RGBA_FLOAT_ATI); } #else if (GLXEW_NV_float_buffer) { pfAttribs.push_back(GLX_FLOAT_COMPONENTS_NV); pfAttribs.push_back(1); } #endif } else { #ifdef _WIN32 pfAttribs.push_back(WGL_PIXEL_TYPE_ARB); pfAttribs.push_back(WGL_TYPE_RGBA_ARB); #endif } // Set up texture binding for render to texture if (_bIsTexture && (RT_RENDER_TO_TEXTURE == _eUpdateMode)) { #ifdef _WIN32 if (_bFloat) { if (WGLEW_NV_float_buffer) { switch(_iNumComponents) { case 1: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_FLOAT_R_NV); break; case 2: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_FLOAT_RG_NV); break; case 3: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_FLOAT_RGB_NV); break; case 4: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_FLOAT_RGBA_NV); break; default: fprintf(stderr, "RenderTexture Warning: Bad number of components " "(r=1,rg=2,rgb=3,rgba=4): %d.\n", _iNumComponents); break; } } else { if (4 == _iNumComponents) { pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RGBA_ARB); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_RGBA_ARB); } else { // standard ARB_render_texture only supports 3 or 4 channels pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RGB_ARB); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_RGB_ARB); } } } else { switch(_iNumComponents) { case 3: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RGB_ARB); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_RGB_ARB); break; case 4: pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RGBA_ARB); pfAttribs.push_back(true); pbAttribs.push_back(WGL_TEXTURE_FORMAT_ARB); pbAttribs.push_back(WGL_TEXTURE_RGBA_ARB); break; default: fprintf(stderr, "RenderTexture Warning: Bad number of components " "(r=1,rg=2,rgb=3,rgba=4): %d.\n", _iNumComponents); break; } } #elif defined(DEBUG) || defined(_DEBUG) fprintf(stderr, "RenderTexture Error: Render to Texture not supported in " "Linux\n"); #endif } if (_bIsDepthTexture && (RT_RENDER_TO_TEXTURE == _eUpdateMode)) { #ifdef _WIN32 if (_bRectangle) { pfAttribs.push_back(WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_DEPTH_TEXTURE_FORMAT_NV); pbAttribs.push_back(WGL_TEXTURE_DEPTH_COMPONENT_NV); } else { pfAttribs.push_back(WGL_BIND_TO_TEXTURE_DEPTH_NV); pfAttribs.push_back(true); pbAttribs.push_back(WGL_DEPTH_TEXTURE_FORMAT_NV); pbAttribs.push_back(WGL_TEXTURE_DEPTH_COMPONENT_NV); } #elif defined(DEBUG) || defined(_DEBUG) printf("RenderTexture Error: Render to Texture not supported in " "Linux\n"); #endif } } //--------------------------------------------------------------------------- // Function : RenderTexture::_GetKeyValuePair // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_GetKeyValuePair() * @brief Parses expressions of the form "X=Y" into a pair (X,Y). */ RenderTexture::KeyVal RenderTexture::_GetKeyValuePair(string token) { string::size_type pos = 0; if ((pos = token.find("=")) != token.npos) { string key = token.substr(0, pos); string value = token.substr(pos+1, token.length()-pos+1); return KeyVal(key, value); } else return KeyVal(token, ""); } //--------------------------------------------------------------------------- // Function : RenderTexture::_ParseBitVector // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_ParseBitVector() * @brief Parses expressions of the form "=r,g,b,a" into a vector: (r,g,b,a) */ vector<int> RenderTexture::_ParseBitVector(string bitVector) { vector<string> pieces; vector<int> bits; if (bitVector == "") { bits.push_back(8); // if a depth isn't specified, use default 8 bits return bits; } string::size_type pos = 0; string::size_type nextpos = 0; do { nextpos = bitVector.find_first_of(", \n", pos); pieces.push_back(string(bitVector, pos, nextpos - pos)); pos = nextpos+1; } while (nextpos != bitVector.npos ); for ( vector<string>::iterator it = pieces.begin(); it != pieces.end(); it++) { bits.push_back(strtol(it->c_str(), 0, 10)); } return bits; } //--------------------------------------------------------------------------- // Function : RenderTexture::_VerifyExtensions // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_VerifyExtensions() * @brief Checks that the necessary extensions are available based on RT mode. */ bool RenderTexture::_VerifyExtensions() { #ifdef _WIN32 if (!WGLEW_ARB_pbuffer) { PrintExtensionError("WGL_ARB_pbuffer"); return false; } if (!WGLEW_ARB_pixel_format) { PrintExtensionError("WGL_ARB_pixel_format"); return false; } if (_bIsTexture && !WGLEW_ARB_render_texture) { PrintExtensionError("WGL_ARB_render_texture"); return false; } if (_bRectangle && !GLEW_NV_texture_rectangle) { PrintExtensionError("GL_NV_texture_rectangle"); return false; } if (_bFloat && !(GLEW_NV_float_buffer || WGLEW_ATI_pixel_format_float)) { PrintExtensionError("GL_NV_float_buffer or GL_ATI_pixel_format_float"); return false; } if (_bFloat && _bIsTexture && !(GLEW_NV_float_buffer || GLEW_ATI_texture_float)) { PrintExtensionError("NV_float_buffer or ATI_texture_float"); } if (_bIsDepthTexture && !GLEW_ARB_depth_texture) { // [Redge] #if defined(_DEBUG) | defined(DEBUG) fprintf(stderr, "RenderTexture Warning: " "OpenGL extension GL_ARB_depth_texture not available.\n" " Using glReadPixels() to emulate behavior.\n"); #endif _bHasARBDepthTexture = false; //PrintExtensionError("GL_ARB_depth_texture"); //return false; // [/Redge] } SetLastError(0); #else if (!GLXEW_SGIX_pbuffer) { PrintExtensionError("GLX_SGIX_pbuffer"); return false; } if (!GLXEW_SGIX_fbconfig) { PrintExtensionError("GLX_SGIX_fbconfig"); return false; } if (_bIsDepthTexture && !GLEW_ARB_depth_texture) { PrintExtensionError("GL_ARB_depth_texture"); return false; } if (_bFloat && _bIsTexture && !GLXEW_NV_float_buffer) { PrintExtensionError("GLX_NV_float_buffer"); return false; } if (_eUpdateMode == RT_RENDER_TO_TEXTURE) { PrintExtensionError("Some GLX render texture extension: FIXME!"); return false; } #endif return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::_InitializeTextures // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_InitializeTextures() * @brief Initializes the state of textures used by the RenderTexture. */ bool RenderTexture::_InitializeTextures() { // Determine the appropriate texture formats and filtering modes. if (_bIsTexture || _bIsDepthTexture) { if (_bRectangle && GLEW_NV_texture_rectangle) _iTextureTarget = GL_TEXTURE_RECTANGLE_NV; else _iTextureTarget = GL_TEXTURE_2D; } if (_bIsTexture) { glGenTextures(1, &_iTextureID); glBindTexture(_iTextureTarget, _iTextureID); // Use clamp to edge as the default texture wrap mode for all tex glTexParameteri(_iTextureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(_iTextureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Use NEAREST as the default texture filtering mode. glTexParameteri(_iTextureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(_iTextureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (RT_COPY_TO_TEXTURE == _eUpdateMode) { GLuint iInternalFormat; GLuint iFormat; if (_bFloat) { if (_bMipmap) { fprintf(stderr, "RenderTexture Error: mipmapped float textures not " "supported.\n"); return false; } switch(_iNumComponents) { case 1: if (GLEW_NV_float_buffer) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_FLOAT_R32_NV : GL_FLOAT_R16_NV; } else if (GLEW_ATI_texture_float) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_LUMINANCE_FLOAT32_ATI : GL_LUMINANCE_FLOAT16_ATI; } iFormat = GL_LUMINANCE; break; case 2: if (GLEW_NV_float_buffer) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_FLOAT_RG32_NV : GL_FLOAT_RG16_NV; } else if (GLEW_ATI_texture_float) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_LUMINANCE_ALPHA_FLOAT32_ATI : GL_LUMINANCE_ALPHA_FLOAT16_ATI; } iFormat = GL_LUMINANCE_ALPHA; break; case 3: if (GLEW_NV_float_buffer) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_FLOAT_RGB32_NV : GL_FLOAT_RGB16_NV; } else if (GLEW_ATI_texture_float) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_RGB_FLOAT32_ATI : GL_RGB_FLOAT16_ATI; } iFormat = GL_RGB; break; case 4: if (GLEW_NV_float_buffer) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_FLOAT_RGBA32_NV : GL_FLOAT_RGBA16_NV; } else if (GLEW_ATI_texture_float) { iInternalFormat = (_iNumColorBits[0] > 16) ? GL_RGBA_FLOAT32_ATI : GL_RGBA_FLOAT16_ATI; } iFormat = GL_RGBA; break; default: printf("RenderTexture Error: " "Invalid number of components: %d\n", _iNumComponents); return false; } } else // non-float { if (4 == _iNumComponents) { iInternalFormat = GL_RGBA8; iFormat = GL_RGBA; } else { iInternalFormat = GL_RGB8; iFormat = GL_RGB; } } // Allocate the texture image (but pass it no data for now). glTexImage2D(_iTextureTarget, 0, iInternalFormat, _iWidth, _iHeight, 0, iFormat, GL_FLOAT, NULL); } } if (_bIsDepthTexture) { glGenTextures(1, &_iDepthTextureID); glBindTexture(_iTextureTarget, _iDepthTextureID); // Use clamp to edge as the default texture wrap mode for all tex glTexParameteri(_iTextureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(_iTextureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Use NEAREST as the default texture filtering mode. glTexParameteri(_iTextureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(_iTextureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (RT_COPY_TO_TEXTURE == _eUpdateMode) { // [Redge] if (_bHasARBDepthTexture) { // Allocate the texture image (but pass it no data for now). glTexImage2D(_iTextureTarget, 0, GL_DEPTH_COMPONENT, _iWidth, _iHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); } else { // allocate memory for depth texture // Since this is slow, we warn the user in debug mode. (above) _pPoorDepthTexture = new unsigned short[_iWidth * _iHeight]; glTexImage2D(_iTextureTarget, 0, GL_LUMINANCE16, _iWidth, _iHeight, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, _pPoorDepthTexture); } // [/Redge] } } return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::_MaybeCopyBuffer // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_MaybeCopyBuffer() * @brief Does the actual copying for RenderTextures with RT_COPY_TO_TEXTURE */ void RenderTexture::_MaybeCopyBuffer() { #ifdef _WIN32 if (RT_COPY_TO_TEXTURE == _eUpdateMode) { if (_bIsTexture) { glBindTexture(_iTextureTarget, _iTextureID); glCopyTexSubImage2D(_iTextureTarget, 0, 0, 0, 0, 0, _iWidth, _iHeight); } if (_bIsDepthTexture) { glBindTexture(_iTextureTarget, _iDepthTextureID); // HOW TO COPY DEPTH TEXTURE??? Supposedly this just magically works... // [Redge] if (_bHasARBDepthTexture) { glCopyTexSubImage2D(_iTextureTarget, 0, 0, 0, 0, 0, _iWidth, _iHeight); } else { // no 'real' depth texture available, so behavior has to be emulated // using glReadPixels (beware, this is (naturally) slow ...) glReadPixels(0, 0, _iWidth, _iHeight, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, _pPoorDepthTexture); glTexImage2D(_iTextureTarget, 0, GL_LUMINANCE16, _iWidth, _iHeight, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, _pPoorDepthTexture); } // [/Redge] } } #else if (_bIsTexture) { glBindTexture(_iTextureTarget, _iTextureID); glCopyTexSubImage2D(_iTextureTarget, 0, 0, 0, 0, 0, _iWidth, _iHeight); } if (_bIsDepthTexture) { glBindTexture(_iTextureTarget, _iDepthTextureID); assert(_bHasARBDepthTexture); glCopyTexSubImage2D(_iTextureTarget, 0, 0, 0, 0, 0, _iWidth, _iHeight); } #endif } //--------------------------------------------------------------------------- // Function : RenderTexture::_ReleaseBoundBuffers // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_ReleaseBoundBuffers() * @brief Releases buffer bindings on RenderTextures with RT_RENDER_TO_TEXTURE */ bool RenderTexture::_ReleaseBoundBuffers() { #ifdef _WIN32 if (_bIsTexture && RT_RENDER_TO_TEXTURE == _eUpdateMode) { glBindTexture(_iTextureTarget, _iTextureID); // release the pbuffer from the render texture object if (0 != _iCurrentBoundBuffer && _bIsBufferBound) { if (FALSE == wglReleaseTexImageARB(_hPBuffer, _iCurrentBoundBuffer)) { _wglGetLastError(); return false; } _bIsBufferBound = false; } } if (_bIsDepthTexture && RT_RENDER_TO_TEXTURE == _eUpdateMode) { glBindTexture(_iTextureTarget, _iDepthTextureID); // release the pbuffer from the render texture object if (FALSE == wglReleaseTexImageARB(_hPBuffer, WGL_DEPTH_COMPONENT_NV)) { _wglGetLastError(); return false; } } #else // textures can't be bound in Linux #endif return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::_MakeCurrent // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::_MakeCurrent() * @brief Makes the RenderTexture's context current */ bool RenderTexture::_MakeCurrent() { #ifdef _WIN32 // make the pbuffer's rendering context current. if (FALSE == wglMakeCurrent( _hDC, _hGLContext)) { _wglGetLastError(); return false; } #else if (false == glXMakeCurrent(_pDisplay, _hPBuffer, _hGLContext)) { return false; } #endif return true; } ///////////////////////////////////////////////////////////////////////////// // // Begin Deprecated Interface // ///////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------- // Function : RenderTexture::RenderTexture // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::RenderTexture() * @brief Constructor. */ RenderTexture::RenderTexture(int width, int height, bool bIsTexture /* = true */, bool bIsDepthTexture /* = false */) : _iWidth(width), _iHeight(height), _bIsTexture(bIsTexture), _bIsDepthTexture(bIsDepthTexture), _bHasARBDepthTexture(true), // [Redge] _eUpdateMode(RT_RENDER_TO_TEXTURE), _bInitialized(false), _iNumAuxBuffers(0), _iCurrentBoundBuffer(0), _iNumDepthBits(0), _iNumStencilBits(0), _bDoubleBuffered(false), _bFloat(false), _bPowerOf2(true), _bRectangle(false), _bMipmap(false), _bShareObjects(false), _bCopyContext(false), #ifdef _WIN32 _hDC(NULL), _hGLContext(NULL), _hPBuffer(NULL), _hPreviousDC(0), _hPreviousContext(0), #else _pDisplay(NULL), _hGLContext(NULL), _hPBuffer(0), _hPreviousContext(0), _hPreviousDrawable(0), #endif _iTextureTarget(GL_NONE), _iTextureID(0), _iDepthTextureID(0), _pPoorDepthTexture(0) // [Redge] { assert(width > 0 && height > 0); #if defined DEBUG || defined _DEBUG fprintf(stderr, "RenderTexture Warning: Deprecated Contructor interface used.\n"); #endif _iNumColorBits[0] = _iNumColorBits[1] = _iNumColorBits[2] = _iNumColorBits[3] = 0; _bPowerOf2 = IsPowerOfTwo(width) && IsPowerOfTwo(height); } //------------------------------------------------------------------------------ // Function : RenderTexture::Initialize // Description : //------------------------------------------------------------------------------ /** * @fn RenderTexture::Initialize(bool bShare, bool bDepth, bool bStencil, bool bMipmap, unsigned int iRBits, unsigned int iGBits, unsigned int iBBits, unsigned int iABits); * @brief Initializes the RenderTexture, sharing display lists and textures if specified. * * This function actually does the creation of the p-buffer. It can only be called * once a GL context has already been created. Note that if the texture is not * power of two dimensioned, or has more than 8 bits per channel, enabling mipmapping * will cause an error. */ bool RenderTexture::Initialize(bool bShare /* = true */, bool bDepth /* = false */, bool bStencil /* = false */, bool bMipmap /* = false */, bool bAnisoFilter /* = false */, unsigned int iRBits /* = 8 */, unsigned int iGBits /* = 8 */, unsigned int iBBits /* = 8 */, unsigned int iABits /* = 8 */, UpdateMode updateMode /* = RT_RENDER_TO_TEXTURE */) { if (0 == _iWidth || 0 == _iHeight) return false; #if defined DEBUG || defined _DEBUG fprintf(stderr, "RenderTexture Warning: Deprecated Initialize() interface used.\n"); #endif // create a mode string. string mode = ""; if (bDepth) mode.append("depth "); if (bStencil) mode.append("stencil "); if (bMipmap) mode.append("mipmap "); if (iRBits + iGBits + iBBits + iABits > 0) { if (iRBits > 0) mode.append("r"); if (iGBits > 0) mode.append("g"); if (iBBits > 0) mode.append("b"); if (iABits > 0) mode.append("a"); mode.append("="); char bitVector[100]; sprintf(bitVector, "%d%s,%d%s,%d%s,%d%s", iRBits, (iRBits >= 16) ? "f" : "", iGBits, (iGBits >= 16) ? "f" : "", iBBits, (iBBits >= 16) ? "f" : "", iABits, (iABits >= 16) ? "f" : ""); mode.append(bitVector); mode.append(" "); } if (_bIsTexture) { if (GLEW_NV_texture_rectangle && ((!IsPowerOfTwo(_iWidth) || !IsPowerOfTwo(_iHeight)) || iRBits >= 16 || iGBits > 16 || iBBits > 16 || iABits >= 16)) mode.append("texRECT "); else mode.append("tex2D "); } if (_bIsDepthTexture) { if (GLEW_NV_texture_rectangle && ((!IsPowerOfTwo(_iWidth) || !IsPowerOfTwo(_iHeight)) || iRBits >= 16 || iGBits > 16 || iBBits > 16 || iABits >= 16)) mode.append("texRECT "); else mode.append("tex2D "); } if (RT_COPY_TO_TEXTURE == updateMode) mode.append("ctt"); _pixelFormatAttribs.clear(); _pbufferAttribs.clear(); #ifdef _WIN32 _pixelFormatAttribs.push_back(WGL_DRAW_TO_PBUFFER_ARB); _pixelFormatAttribs.push_back(true); _pixelFormatAttribs.push_back(WGL_SUPPORT_OPENGL_ARB); _pixelFormatAttribs.push_back(true); _pbufferAttribs.push_back(WGL_PBUFFER_LARGEST_ARB); _pbufferAttribs.push_back(true); #else _pixelFormatAttribs.push_back(GLX_RENDER_TYPE_SGIX); _pixelFormatAttribs.push_back(GLX_RGBA_BIT_SGIX); _pixelFormatAttribs.push_back(GLX_DRAWABLE_TYPE_SGIX); _pixelFormatAttribs.push_back(GLX_PBUFFER_BIT_SGIX); #endif _ParseModeString(mode.c_str(), _pixelFormatAttribs, _pbufferAttribs); #ifdef _WIN32 _pixelFormatAttribs.push_back(0); _pbufferAttribs.push_back(0); #else _pixelFormatAttribs.push_back(None); #endif Initialize(_iWidth, _iHeight, bShare); return true; } //--------------------------------------------------------------------------- // Function : RenderTexture::Reset // Description : //--------------------------------------------------------------------------- /** * @fn RenderTexture::Reset(int iWidth, int iHeight, unsigned int iMode, bool bIsTexture, bool bIsDepthTexture) * @brief Resets the resolution of the offscreen buffer. * * Causes the buffer to delete itself. User must call Initialize() again * before use. */ bool RenderTexture::Reset(int iWidth, int iHeight) { fprintf(stderr, "RenderTexture Warning: Deprecated Reset() interface used.\n"); if (!_Invalidate()) { fprintf(stderr, "RenderTexture::Reset(): failed to invalidate.\n"); return false; } _iWidth = iWidth; _iHeight = iHeight; return true; }
mit
cbeck88/cegui-mirror-two
cegui/src/WindowRendererSets/Core/ItemEntry.cpp
3
2948
/*********************************************************************** created: Thu Sep 22 2005 author: Tomas Lindquist Olsen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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. ***************************************************************************/ #include "CEGUI/WindowRendererSets/Core/ItemEntry.h" #include "CEGUI/falagard/WidgetLookManager.h" #include "CEGUI/falagard/WidgetLookFeel.h" // Start of CEGUI namespace section namespace CEGUI { const String FalagardItemEntry::TypeName("Core/ItemEntry"); FalagardItemEntry::FalagardItemEntry(const String& type) : ItemEntryWindowRenderer(type) { } void FalagardItemEntry::createRenderGeometry() { ItemEntry* item = static_cast<ItemEntry*>(d_window); // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); const StateImagery* imagery; // render basic imagery String state = item->isEffectiveDisabled() ? "Disabled" : "Enabled"; if (item->isSelectable() && item->isSelected()) { imagery = &wlf.getStateImagery(item->isEffectiveDisabled() ? "SelectedDisabled" : "SelectedEnabled"); } else { imagery = &wlf.getStateImagery(item->isEffectiveDisabled() ? "Disabled" : "Enabled"); } imagery->render(*d_window); } Sizef FalagardItemEntry::getItemPixelSize() const { // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); return wlf.getNamedArea("ContentSize").getArea().getPixelRect(*d_window).getSize(); } } // End of CEGUI namespace section
mit
Skoks/stateface
tools/font-for-us.cpp
4
2727
#include "src/shape.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <unistd.h> typedef struct { char *shpfile; char *proj; double simplification; char *name_field; char *filter; } opt_t; void help(){ fprintf (stderr, "font-for-us generates eps files for StateFace." "\nusage: font-for-us <shpfile> -p <proj> -s <simplification> -n <name-field> -f <filter>\n" "\n" "Options:\n" " -p projection as in an OGR readable format. (required)\n" " -s simplification to apply to each shape. (required)\n" " -n name field of shapefile to build output filename from. (required)\n" " -f filter value to filter the shapefile on, i.e. AK to only output Alaska. (optional)\n\n" ); exit(1); } void get_options(opt_t *opt, int argc, char **argv){ int c, i; memset(opt, 0, sizeof(*opt)); while((c = getopt(argc, argv, "p:s:n:f:h")) != -1){ switch(c){ case 'p': opt->proj = optarg; break; case 's': opt->simplification = strtod(optarg, NULL); break; case 'n': opt->name_field = optarg; break; case 'f': opt->filter = optarg; break; case '?': case 'h': default: help(); } } opt->shpfile = argv[optind]; if(opt->shpfile == NULL || opt->proj == NULL || opt->name_field == NULL) help(); } int main(int argc, char **argv){ opt_t options; get_options(&options, argc, argv); OGRRegisterAll(); OGRDataSource *ds; ds = OGRSFDriverRegistrar::Open(options.shpfile, FALSE); if(ds == NULL) { fprintf(stderr, "Couldn't open datasource %s\n", options.shpfile); exit(1); } OGRLayer *layer = ds->GetLayer(0); if(layer == NULL) { fprintf(stderr, "No layers in %s", options.shpfile); exit(1); } layer->ResetReading(); int i = 0; OGRFeature *feat; while((feat = layer->GetNextFeature()) != NULL){ int field_index = feat->GetFieldIndex(options.name_field); if(options.filter != NULL && strcmp(feat->GetFieldAsString(field_index), options.filter) != 0){ OGRFeature::DestroyFeature(feat); continue; } Shape shape; OGRGeometry *geo = feat->GetGeometryRef(); if(geo == NULL) continue; shape.setGeom(geo); shape.setProj(options.proj); shape.Simplify(options.simplification); char *filename; if(field_index != -1) { asprintf(&filename, "%s.eps", feat->GetFieldAsString(field_index)); } else { asprintf(&filename, "%i.eps", i); } shape.Render(filename); std::cout << "Rendered: " << filename << std::endl; free(filename); i++; OGRFeature::DestroyFeature(feat); } OGRDataSource::DestroyDataSource(ds); }
mit
kiwih/goFB
examples/goFB_only/c_tcrest/bottlingplant_spm/c/InjectorPumpsController.c
4
6501
// This file has been automatically generated by goFB and should not be edited by hand // Compiler written by Hammond Pearce and available at github.com/kiwih/goFB // This file represents the implementation of the Basic Function Block for InjectorPumpsController #include "InjectorPumpsController.h" /* InjectorPumpsController_preinit() is required to be called to * initialise an instance of InjectorPumpsController. * It sets all I/O values to zero. */ int InjectorPumpsController_preinit(InjectorPumpsController_t _SPM *me) { //if there are input events, reset them me->inputEvents.event.StartPump = 0; me->inputEvents.event.EmergencyStopChanged = 0; me->inputEvents.event.CanisterPressureChanged = 0; me->inputEvents.event.FillContentsAvailableChanged = 0; me->inputEvents.event.VacuumTimerElapsed = 0; //if there are output events, reset them me->outputEvents.event.PumpFinished = 0; me->outputEvents.event.RejectCanister = 0; me->outputEvents.event.InjectorControlsChanged = 0; me->outputEvents.event.FillContentsChanged = 0; me->outputEvents.event.StartVacuumTimer = 0; //if there are input vars with default values, set them //if there are output vars with default values, set them //if there are internal vars with default values, set them (BFBs only) //if there are resource vars with default values, set them //if there are resources with set parameters, set them //if there are fb children (CFBs/Devices/Resources only), call this same function on them //if this is a BFB, set _trigger to be true and start state so that the start state is properly executed me->_trigger = true; me->_state = STATE_InjectorPumpsController_RejectCanister; return 0; } /* InjectorPumpsController_init() is required to be called to * set up an instance of InjectorPumpsController. * It passes around configuration data. */ int InjectorPumpsController_init(InjectorPumpsController_t _SPM *me) { //pass in any parameters on this level //perform a data copy to all children (if any present) (can move config data around, doesn't do anything otherwise) //if there are fb children (CFBs/Devices/Resources only), call this same function on them return 0; } //algorithms void InjectorPumpsController_StartVacuum(InjectorPumpsController_t _SPM *me) { me->InjectorVacuumRun = 1; //printf("Injector: Start vacuum\n"); } void InjectorPumpsController_ClearControls(InjectorPumpsController_t _SPM *me) { me->InjectorContentsValveOpen = 0; me->InjectorPressurePumpRun = 0; me->InjectorVacuumRun = 0; //printf("Injector: Clear controls\n"); } void InjectorPumpsController_OpenValve(InjectorPumpsController_t _SPM *me) { me->InjectorContentsValveOpen = 1; //printf("Injector: Open valve\n"); } void InjectorPumpsController_StartPump(InjectorPumpsController_t _SPM *me) { me->InjectorPressurePumpRun = 1; //printf("Injector: Start pump\n"); } /* InjectorPumpsController_run() executes a single tick of an * instance of InjectorPumpsController according to synchronous semantics. * Notice that it does NOT perform any I/O - synchronisation * will need to be done in the parent. * Also note that on the first run of this function, trigger will be set * to true, meaning that on the very first run no next state logic will occur. */ void InjectorPumpsController_run(InjectorPumpsController_t _SPM *me) { //if there are output events, reset them me->outputEvents.event.PumpFinished = 0; me->outputEvents.event.RejectCanister = 0; me->outputEvents.event.InjectorControlsChanged = 0; me->outputEvents.event.FillContentsChanged = 0; me->outputEvents.event.StartVacuumTimer = 0; //next state logic if(me->_trigger == false) { switch(me->_state) { case STATE_InjectorPumpsController_RejectCanister: if(true) { me->_state = STATE_InjectorPumpsController_AwaitPump; me->_trigger = true; }; break; case STATE_InjectorPumpsController_AwaitPump: if(me->inputEvents.event.StartPump) { me->_state = STATE_InjectorPumpsController_VacuumPump; me->_trigger = true; }; break; case STATE_InjectorPumpsController_VacuumPump: if(me->inputEvents.event.VacuumTimerElapsed) { me->_state = STATE_InjectorPumpsController_RejectCanister; me->_trigger = true; } else if(me->inputEvents.event.CanisterPressureChanged && (me->CanisterPressure <= 10)) { me->_state = STATE_InjectorPumpsController_StopVacuum; me->_trigger = true; }; break; case STATE_InjectorPumpsController_FinishPump: if(true) { me->_state = STATE_InjectorPumpsController_AwaitPump; me->_trigger = true; }; break; case STATE_InjectorPumpsController_StartPump: if(me->inputEvents.event.CanisterPressureChanged && (me->CanisterPressure >= 245)) { me->_state = STATE_InjectorPumpsController_FinishPump; me->_trigger = true; }; break; case STATE_InjectorPumpsController_OpenValve: if(true) { me->_state = STATE_InjectorPumpsController_StartPump; me->_trigger = true; }; break; case STATE_InjectorPumpsController_StopVacuum: if(true) { me->_state = STATE_InjectorPumpsController_OpenValve; me->_trigger = true; }; break; } } //state output logic if(me->_trigger == true) { switch(me->_state) { case STATE_InjectorPumpsController_RejectCanister: InjectorPumpsController_ClearControls(me); me->outputEvents.event.RejectCanister = 1; me->outputEvents.event.InjectorControlsChanged = 1; break; case STATE_InjectorPumpsController_AwaitPump: me->outputEvents.event.PumpFinished = 1; break; case STATE_InjectorPumpsController_VacuumPump: InjectorPumpsController_StartVacuum(me); me->outputEvents.event.InjectorControlsChanged = 1; me->outputEvents.event.StartVacuumTimer = 1; break; case STATE_InjectorPumpsController_FinishPump: InjectorPumpsController_ClearControls(me); me->outputEvents.event.InjectorControlsChanged = 1; break; case STATE_InjectorPumpsController_StartPump: InjectorPumpsController_StartPump(me); me->outputEvents.event.InjectorControlsChanged = 1; break; case STATE_InjectorPumpsController_OpenValve: InjectorPumpsController_OpenValve(me); me->outputEvents.event.InjectorControlsChanged = 1; break; case STATE_InjectorPumpsController_StopVacuum: InjectorPumpsController_ClearControls(me); me->outputEvents.event.InjectorControlsChanged = 1; break; } } me->_trigger = false; }
mit
qtumproject/qtum
src/signet.cpp
5
5790
// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <signet.h> #include <array> #include <cstdint> #include <vector> #include <consensus/merkle.h> #include <consensus/params.h> #include <consensus/validation.h> #include <core_io.h> #include <hash.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <span.h> #include <script/interpreter.h> #include <script/standard.h> #include <streams.h> #include <util/strencodings.h> #include <util/system.h> #include <uint256.h> static constexpr uint8_t SIGNET_HEADER[4] = {0xec, 0xc7, 0xda, 0xa2}; static constexpr unsigned int BLOCK_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_NULLDUMMY; static bool FetchAndClearCommitmentSection(const Span<const uint8_t> header, CScript& witness_commitment, std::vector<uint8_t>& result) { CScript replacement; bool found_header = false; result.clear(); opcodetype opcode; CScript::const_iterator pc = witness_commitment.begin(); std::vector<uint8_t> pushdata; while (witness_commitment.GetOp(pc, opcode, pushdata)) { if (pushdata.size() > 0) { if (!found_header && pushdata.size() > (size_t) header.size() && Span<const uint8_t>(pushdata.data(), header.size()) == header) { // pushdata only counts if it has the header _and_ some data result.insert(result.end(), pushdata.begin() + header.size(), pushdata.end()); pushdata.erase(pushdata.begin() + header.size(), pushdata.end()); found_header = true; } replacement << pushdata; } else { replacement << opcode; } } if (found_header) witness_commitment = replacement; return found_header; } static uint256 ComputeModifiedMerkleRoot(const CMutableTransaction& cb, const CBlock& block) { std::vector<uint256> leaves; leaves.resize(block.vtx.size()); leaves[0] = cb.GetHash(); for (size_t s = 1; s < block.vtx.size(); ++s) { leaves[s] = block.vtx[s]->GetHash(); } return ComputeMerkleRoot(std::move(leaves)); } std::optional<SignetTxs> SignetTxs::Create(const CBlock& block, const CScript& challenge) { CMutableTransaction tx_to_spend; tx_to_spend.nVersion = 0; tx_to_spend.nLockTime = 0; tx_to_spend.vin.emplace_back(COutPoint(), CScript(OP_0), 0); tx_to_spend.vout.emplace_back(0, challenge); CMutableTransaction tx_spending; tx_spending.nVersion = 0; tx_spending.nLockTime = 0; tx_spending.vin.emplace_back(COutPoint(), CScript(), 0); tx_spending.vout.emplace_back(0, CScript(OP_RETURN)); // can't fill any other fields before extracting signet // responses from block coinbase tx // find and delete signet signature if (block.vtx.empty()) return std::nullopt; // no coinbase tx in block; invalid CMutableTransaction modified_cb(*block.vtx.at(0)); const int cidx = GetWitnessCommitmentIndex(block); if (cidx == NO_WITNESS_COMMITMENT) { return std::nullopt; // require a witness commitment } CScript& witness_commitment = modified_cb.vout.at(cidx).scriptPubKey; std::vector<uint8_t> signet_solution; if (!FetchAndClearCommitmentSection(SIGNET_HEADER, witness_commitment, signet_solution)) { // no signet solution -- allow this to support OP_TRUE as trivial block challenge } else { try { VectorReader v(SER_NETWORK, INIT_PROTO_VERSION, signet_solution, 0); v >> tx_spending.vin[0].scriptSig; v >> tx_spending.vin[0].scriptWitness.stack; if (!v.empty()) return std::nullopt; // extraneous data encountered } catch (const std::exception&) { return std::nullopt; // parsing error } } uint256 signet_merkle = ComputeModifiedMerkleRoot(modified_cb, block); std::vector<uint8_t> block_data; CVectorWriter writer(SER_NETWORK, INIT_PROTO_VERSION, block_data, 0); writer << block.nVersion; writer << block.hashPrevBlock; writer << signet_merkle; writer << block.nTime; tx_to_spend.vin[0].scriptSig << block_data; tx_spending.vin[0].prevout = COutPoint(tx_to_spend.GetHash(), 0); return SignetTxs{tx_to_spend, tx_spending}; } // Signet block solution checker bool CheckSignetBlockSolution(const CBlock& block, const Consensus::Params& consensusParams) { if (block.GetHash() == consensusParams.hashGenesisBlock) { // genesis block solution is always valid return true; } const CScript challenge(consensusParams.signet_challenge.begin(), consensusParams.signet_challenge.end()); const std::optional<SignetTxs> signet_txs = SignetTxs::Create(block, challenge); if (!signet_txs) { LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution parse failure)\n"); return false; } const CScript& scriptSig = signet_txs->m_to_sign.vin[0].scriptSig; const CScriptWitness& witness = signet_txs->m_to_sign.vin[0].scriptWitness; PrecomputedTransactionData txdata; txdata.Init(signet_txs->m_to_sign, {signet_txs->m_to_spend.vout[0]}); TransactionSignatureChecker sigcheck(&signet_txs->m_to_sign, /*nIn=*/ 0, /*amount=*/ signet_txs->m_to_spend.vout[0].nValue, txdata, MissingDataBehavior::ASSERT_FAIL); if (!VerifyScript(scriptSig, signet_txs->m_to_spend.vout[0].scriptPubKey, &witness, BLOCK_SCRIPT_VERIFY_FLAGS, sigcheck)) { LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution invalid)\n"); return false; } return true; }
mit
PKRoma/poedit
deps/boost/libs/mpi/test/cartesian_topology_test.cpp
6
5997
// Copyright Alain Miniussi 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Alain Miniussi #include <vector> #include <iostream> #include <sstream> #include <iterator> #include <algorithm> #include <functional> #include <boost/mpi/communicator.hpp> #include <boost/mpi/collectives.hpp> #include <boost/mpi/environment.hpp> #include <boost/mpi/cartesian_communicator.hpp> #include <boost/test/minimal.hpp> namespace mpi = boost::mpi; struct topo_minimum { mpi::cartesian_dimension operator()(mpi::cartesian_dimension const& d1, mpi::cartesian_dimension const& d2 ) const { return mpi::cartesian_dimension(std::min(d1.size, d2.size), d1.periodic && d2.periodic); } }; std::string topology_description( mpi::cartesian_topology const& topo ) { std::ostringstream out; std::copy(topo.begin(), topo.end(), std::ostream_iterator<mpi::cartesian_dimension>(out, " ")); out << std::flush; return out.str(); } // Check that everyone agrees on the coordinates void test_coordinates_consistency( mpi::cartesian_communicator const& cc, std::vector<int> const& coords ) { cc.barrier(); // flush IOs for nice printing bool master = cc.rank() == 0; if (master) { std::cout << "Test coordinates consistency.\n"; } for(int p = 0; p < cc.size(); ++p) { std::vector<int> min(cc.ndims()); std::vector<int> local(cc.coordinates(p)); mpi::reduce(cc, &local.front(), local.size(), &(min[0]), mpi::minimum<int>(), p); cc.barrier(); if (p == cc.rank()) { BOOST_CHECK(std::equal(coords.begin(), coords.end(), min.begin())); std::ostringstream out; out << "proc " << p << " at ("; std::copy(min.begin(), min.end(), std::ostream_iterator<int>(out, " ")); out << ")\n"; std::cout << out.str(); } } } void test_shifted_coords( mpi::cartesian_communicator const& cc, int pos, mpi::cartesian_dimension desc, int dim ) { if (desc.periodic) { for (int i = -(desc.size); i < desc.size; ++i) { std::pair<int,int> rks = cc.shifted_ranks(dim, i); int src = cc.coordinates(rks.first)[dim]; int dst = cc.coordinates(rks.second)[dim]; if (pos == (dim/2)) { std::ostringstream out; out << "Rank " << cc.rank() << ", dim. " << dim << ", pos " << pos << ", in " << desc << ' '; out << "shifted pos: " << src << ", " << dst << '\n'; std::cout << out.str(); } } } } void test_shifted_coords( mpi::cartesian_communicator const& cc) { cc.barrier(); // flush IOs for nice printing std::vector<int> coords; mpi::cartesian_topology topo(cc.ndims()); cc.topology(topo, coords); bool master = cc.rank() == 0; if (master) { std::cout << "Testing shifts with topology " << topo << '\n'; } for(int i = 0; i < cc.ndims(); ++i) { if (master) { std::cout << " for dimension " << i << ": " << topo[i] << '\n'; } test_shifted_coords( cc, coords[i], topo[i], i ); } } void test_topology_consistency( mpi::cartesian_communicator const& cc) { cc.barrier(); // flush IOs for nice printing mpi::cartesian_topology itopo(cc.ndims()); mpi::cartesian_topology otopo(cc.ndims()); std::vector<int> coords(cc.ndims()); cc.topology(itopo, coords); bool master = cc.rank() == 0; if (master) { std::cout << "Test topology consistency of" << itopo << "(on master)\n"; std::cout << "Check that everyone agrees on the dimensions.\n"; } mpi::all_reduce(cc, &(itopo[0]), itopo.size(), &(otopo[0]), topo_minimum()); BOOST_CHECK(std::equal(itopo.begin(), itopo.end(), otopo.begin())); if (master) { std::cout << "We agree on " << topology_description(otopo) << '\n'; } test_coordinates_consistency( cc, coords ); } void test_cartesian_topology( mpi::cartesian_communicator const& cc) { BOOST_CHECK(cc.has_cartesian_topology()); for( int r = 0; r < cc.size(); ++r) { cc.barrier(); if (r == cc.rank()) { std::vector<int> coords = cc.coordinates(r); std::cout << "Process of cartesian rank " << cc.rank() << " has coordinates ("; std::copy(coords.begin(), coords.end(), std::ostream_iterator<int>(std::cout," ")); std::cout << ")\n"; } } test_topology_consistency(cc); test_shifted_coords(cc); std::vector<int> even; for(int i = 0; i < cc.ndims(); i += 2) { even.push_back(i); } cc.barrier(); mpi::cartesian_communicator cce(cc, even); } void test_cartesian_topology( mpi::communicator const& world, mpi::cartesian_topology const& topo) { mpi::cartesian_communicator cc(world, topo, true); if (cc) { BOOST_CHECK(cc.has_cartesian_topology()); BOOST_CHECK(cc.ndims() == int(topo.size())); if (cc.rank() == 0) { std::cout << "Asked topology " << topo << ", got " << cc.topology() << '\n'; } test_cartesian_topology(cc); } else { std::ostringstream out; out << world.rank() << " was left outside the cartesian grid\n"; std::cout << out.str(); } } int test_main(int argc, char* argv[]) { mpi::environment env(argc, argv); mpi::communicator world; int const ndim = world.size() >= 24 ? 3 : 2; mpi::cartesian_topology topo(ndim); typedef mpi::cartesian_dimension cd; if (topo.size() == 3) { topo[0] = cd(2,true); topo[1] = cd(3,false); topo[2] = cd(4, true); } else { if (world.size() >= 6) { topo[0] = cd(2,true); topo[1] = cd(3, false); } else { topo[0] = cd(1,true); topo[1] = cd(1, false); } } test_cartesian_topology( world, topo); #if !defined(BOOST_NO_CXX11_DEFAULTED_MOVES) world.barrier(); if (world.rank()==0) { std::cout << "Testing move constructor.\n"; } test_cartesian_topology( world, std::move(topo)); #endif return 0; }
mit
fillest/7drl2013
libtcod-1.5.2/src/fov_circular_raycasting.c
6
8133
/* * libtcod 1.5.2 * Copyright (c) 2008,2009,2010,2012 Jice & Mingos * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of Jice or Mingos may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JICE OR MINGOS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtcod.h" #include "libtcod_int.h" #include <string.h> #include <math.h> #include <stdlib.h> static void cast_ray(map_t *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { int curx=xo,cury=yo; bool in=false; bool blocked=false; bool end=false; int offset; TCOD_line_init(xo,yo,xd,yd); offset=curx+cury*map->width; if ( 0 <= offset && offset < map->nbcells ) { in=true; map->cells[offset].fov=1; } while (!end) { end = TCOD_line_step(&curx,&cury); /* reached xd,yd */ offset=curx+cury*map->width; if ( r2 > 0 ) { /* check radius */ int cur_radius=(curx-xo)*(curx-xo)+(cury-yo)*(cury-yo); if ( cur_radius > r2 ) return; } if ( 0 <= offset && offset < map->nbcells ) { in=true; if ( !blocked && ! map->cells[offset].transparent ) { blocked=true; } else if ( blocked ) { return; /* wall */ } if ( light_walls || ! blocked ) map->cells[offset].fov=1; } else if (in) return; /* ray out of map */ } } void TCOD_map_postproc(map_t *map,int x0,int y0, int x1, int y1, int dx, int dy) { int cx,cy; for (cx=x0; cx <= x1; cx++) { for (cy=y0;cy <= y1; cy ++ ) { int x2 = cx+dx; int y2 = cy+dy; unsigned int offset=cx+cy*map->width; if ( offset < (unsigned)map->nbcells && map->cells[offset].fov == 1 && map->cells[offset].transparent ) { if ( x2 >= x0 && x2 <= x1 ) { unsigned int offset2=x2+cy*map->width; if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) map->cells[offset2].fov=1; } if ( y2 >= y0 && y2 <= y1 ) { unsigned int offset2=cx+y2*map->width; if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) map->cells[offset2].fov=1; } if ( x2 >= x0 && x2 <= x1 && y2 >= y0 && y2 <= y1 ) { unsigned int offset2=x2+y2*map->width; if ( offset2 < (unsigned)map->nbcells && ! map->cells[offset2].transparent ) map->cells[offset2].fov=1; } } } } } void TCOD_map_compute_fov_circular_raycastingi(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { int xo,yo; map_t *m = (map_t *)map; /* circular ray casting */ int xmin=0, ymin=0, xmax=m->width, ymax=m->height; int c; int r2=max_radius*max_radius; if ( max_radius > 0 ) { xmin=MAX(0,player_x-max_radius); ymin=MAX(0,player_y-max_radius); xmax=MIN(m->width,player_x+max_radius+1); ymax=MIN(m->height,player_y+max_radius+1); } for (c=m->nbcells-1; c >= 0; c--) { m->cells[c].fov=0; } xo=xmin; yo=ymin; while ( xo < xmax ) { cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); } xo=xmax-1;yo=ymin+1; while ( yo < ymax ) { cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); } xo=xmax-2;yo=ymax-1; while ( xo >= 0 ) { cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); } xo=xmin;yo=ymax-2; while ( yo > 0 ) { cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); } if ( light_walls ) { /* post-processing artefact fix */ TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); } } #if 0 #define CELL_RADIUS 0.4f #define RAY_RADIUS 0.2f static bool ray_blocked(map_t *map,float x, float y, int cx, int cy) { int offset=cx+cy*map->width; float d; if ( (unsigned)offset >= (unsigned)map->nbcells ) return false; /* out of the map */ if ( map->cells[offset].transparent ) return false; /* empty cell */ d=(cx-x+0.5f)*(cx-x+0.5f)+(cy-y+0.5f)*(cy-y+0.5f); return d < (CELL_RADIUS+RAY_RADIUS)*(CELL_RADIUS+RAY_RADIUS); } static void cast_rayf(map_t *map, int xo, int yo, int xd, int yd, int r2,bool light_walls) { float fxo=xo+0.5f, fyo=yo+0.5f; float curx=fxo, cury=fyo; float fxd=xd+0.5f; float fyd=yd+0.5f; bool in=false; bool end=false; int offset; float dx=(float)(fxd-curx), dy=(float)(fyd-cury),idx,idy; if ( dx == 0 && dy == 0 ) return; if ( fabs(dx) > fabs(dy) ) { idy = (float)(dy/fabs(dx)); idx = (float)(dx/fabs(dx)); } else { idx = (float)(dx/fabs(dy)); idy = (float)(dy/fabs(dy)); } offset=(int)(curx)+(int)(cury)*map->width; if ( (unsigned)offset < (unsigned)map->nbcells ) { in=true; map->cells[offset].fov=1; } while (!end) { int cx,cy; curx+=idx; cury+=idy; cx=(int)curx; cy=(int)cury; end = (cx==xd && cy==yd); offset=cx+cy*map->width; if ( r2 > 0 ) { /* check radius */ int cur_radius=(int)((curx-fxo)*(curx-fxo)+(cury-fyo)*(cury-fyo)); if ( cur_radius > r2 ) return; } if ( (unsigned)offset < (unsigned)map->nbcells ) { in=true; if ( ray_blocked(map,curx,cury,cx,cy) ) return; if ( curx+RAY_RADIUS > cx+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx+1,cy) ) return; if ( curx-RAY_RADIUS < cx-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx-1,cy) ) return; if ( cury+RAY_RADIUS > cy+0.5f-CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy+1) ) return; if ( cury-RAY_RADIUS < cy-0.5f+CELL_RADIUS && ray_blocked(map,curx,cury,cx,cy-1) ) return; map->cells[offset].fov=1; } else if (in) return; /* ray out of map */ } } #endif void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls) { int xo,yo; map_t *m = (map_t *)map; /* circular ray casting */ int xmin=0, ymin=0, xmax=m->width, ymax=m->height; int c; int r2=max_radius*max_radius; if ( max_radius > 0 ) { xmin=MAX(0,player_x-max_radius); ymin=MAX(0,player_y-max_radius); xmax=MIN(m->width,player_x+max_radius+1); ymax=MIN(m->height,player_y+max_radius+1); } for (c=m->nbcells-1; c >= 0; c--) { m->cells[c].fov=0; } xo=xmin; yo=ymin; while ( xo < xmax ) { cast_ray(m,player_x,player_y,xo++,yo,r2,light_walls); } xo=xmax-1;yo=ymin+1; while ( yo < ymax ) { cast_ray(m,player_x,player_y,xo,yo++,r2,light_walls); } xo=xmax-2;yo=ymax-1; while ( xo >= 0 ) { cast_ray(m,player_x,player_y,xo--,yo,r2,light_walls); } xo=xmin;yo=ymax-2; while ( yo > 0 ) { cast_ray(m,player_x,player_y,xo,yo--,r2,light_walls); } if ( light_walls ) { /* post-processing artefact fix */ TCOD_map_postproc(m,xmin,ymin,player_x,player_y,-1,-1); TCOD_map_postproc(m,player_x,ymin,xmax-1,player_y,1,-1); TCOD_map_postproc(m,xmin,player_y,player_x,ymax-1,-1,1); TCOD_map_postproc(m,player_x,player_y,xmax-1,ymax-1,1,1); } }
mit
josempans/godot
modules/openxr/register_types.cpp
7
4852
/*************************************************************************/ /* register_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "register_types.h" #include "main/main.h" #include "openxr_interface.h" #include "action_map/openxr_action.h" #include "action_map/openxr_action_map.h" #include "action_map/openxr_action_set.h" #include "action_map/openxr_interaction_profile.h" #include "scene/openxr_hand.h" #ifdef TOOLS_ENABLED #include "editor/editor_node.h" #include "editor/openxr_editor_plugin.h" static void _editor_init() { if (OpenXRAPI::openxr_is_enabled(false)) { // Only add our OpenXR action map editor if OpenXR is enabled for our project OpenXREditorPlugin *openxr_plugin = memnew(OpenXREditorPlugin()); EditorNode::get_singleton()->add_editor_plugin(openxr_plugin); } } #endif static OpenXRAPI *openxr_api = nullptr; static Ref<OpenXRInterface> openxr_interface; void initialize_openxr_module(ModuleInitializationLevel p_level) { if (p_level == MODULE_INITIALIZATION_LEVEL_SERVERS) { // For now we create our openxr device here. If we merge it with openxr_interface we'll create that here soon. if (OpenXRAPI::openxr_is_enabled()) { openxr_api = memnew(OpenXRAPI); ERR_FAIL_NULL(openxr_api); if (!openxr_api->initialize(Main::get_rendering_driver_name())) { memdelete(openxr_api); openxr_api = nullptr; return; } } } if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) { GDREGISTER_CLASS(OpenXRInterface); GDREGISTER_CLASS(OpenXRAction); GDREGISTER_CLASS(OpenXRActionSet); GDREGISTER_CLASS(OpenXRActionMap); GDREGISTER_CLASS(OpenXRIPBinding); GDREGISTER_CLASS(OpenXRInteractionProfile); GDREGISTER_CLASS(OpenXRHand); XRServer *xr_server = XRServer::get_singleton(); if (xr_server) { openxr_interface.instantiate(); xr_server->add_interface(openxr_interface); if (openxr_interface->initialize_on_startup()) { openxr_interface->initialize(); } } #ifdef TOOLS_ENABLED EditorNode::add_init_callback(_editor_init); #endif } } void uninitialize_openxr_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } if (openxr_interface.is_valid()) { // uninitialize just in case if (openxr_interface->is_initialized()) { openxr_interface->uninitialize(); } // unregister our interface from the XR server XRServer *xr_server = XRServer::get_singleton(); if (xr_server) { if (xr_server->get_primary_interface() == openxr_interface) { xr_server->set_primary_interface(Ref<XRInterface>()); } xr_server->remove_interface(openxr_interface); } // and release openxr_interface.unref(); } if (openxr_api) { openxr_api->finish(); memdelete(openxr_api); openxr_api = nullptr; } }
mit
mokchhya/coreclr
src/binder/clrprivbindercoreclr.cpp
7
12127
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "assemblybinder.hpp" #include "clrprivbindercoreclr.h" #include "clrprivbinderutil.h" using namespace BINDER_SPACE; //============================================================================= // Helper functions //----------------------------------------------------------------------------- HRESULT CLRPrivBinderCoreCLR::BindAssemblyByNameWorker(BINDER_SPACE::AssemblyName *pAssemblyName, BINDER_SPACE::Assembly **ppCoreCLRFoundAssembly, bool excludeAppPaths) { VALIDATE_ARG_RET(pAssemblyName != nullptr && ppCoreCLRFoundAssembly != nullptr); HRESULT hr = S_OK; #ifdef _DEBUG // MSCORLIB should be bound using BindToSystem _ASSERTE(!pAssemblyName->IsMscorlib()); #endif hr = AssemblyBinder::BindAssembly(&m_appContext, pAssemblyName, NULL, NULL, FALSE, //fNgenExplicitBind, FALSE, //fExplicitBindToNativeImage, excludeAppPaths, ppCoreCLRFoundAssembly); if (!FAILED(hr)) { (*ppCoreCLRFoundAssembly)->SetBinder(this); } return hr; } // ============================================================================ // CLRPrivBinderCoreCLR implementation // ============================================================================ HRESULT CLRPrivBinderCoreCLR::BindAssemblyByName(IAssemblyName *pIAssemblyName, ICLRPrivAssembly **ppAssembly) { HRESULT hr = S_OK; VALIDATE_ARG_RET(pIAssemblyName != nullptr && ppAssembly != nullptr); EX_TRY { *ppAssembly = nullptr; ReleaseHolder<BINDER_SPACE::Assembly> pCoreCLRFoundAssembly; ReleaseHolder<AssemblyName> pAssemblyName; SAFE_NEW(pAssemblyName, AssemblyName); IF_FAIL_GO(pAssemblyName->Init(pIAssemblyName)); hr = BindAssemblyByNameWorker(pAssemblyName, &pCoreCLRFoundAssembly, false /* excludeAppPaths */); #if defined(FEATURE_HOST_ASSEMBLY_RESOLVER) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) && !defined(MDILNIGEN) if ((hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) || (hr == FUSION_E_APP_DOMAIN_LOCKED) || (hr == FUSION_E_REF_DEF_MISMATCH)) { // If we are here, one of the following is possible: // // 1) The assembly has not been found in the current binder's application context (i.e. it has not already been loaded), OR // 2) An assembly with the same simple name was already loaded in the context of the current binder but we ran into a Ref/Def // mismatch (either due to version difference or strong-name difference). // // Thus, if default binder has been overridden, then invoke it in an attempt to perform the binding for it make the call // of what to do next. The host-overridden binder can either fail the bind or return reference to an existing assembly // that has been loaded. // Attempt to resolve the assembly via managed TPA ALC instance if one exists INT_PTR pManagedAssemblyLoadContext = GetManagedAssemblyLoadContext(); if (pManagedAssemblyLoadContext != NULL) { hr = AssemblyBinder::BindUsingHostAssemblyResolver(pManagedAssemblyLoadContext, pAssemblyName, pIAssemblyName, &pCoreCLRFoundAssembly); if (SUCCEEDED(hr)) { // We maybe returned an assembly that was bound to a different AssemblyLoadContext instance. // In such a case, we will not overwrite the binding context (which would be wrong since it would not // be present in the cache of the current binding context). if (pCoreCLRFoundAssembly->GetBinder() == NULL) { pCoreCLRFoundAssembly->SetBinder(this); } } } } #endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) && !defined(MDILNIGEN) IF_FAIL_GO(hr); *ppAssembly = pCoreCLRFoundAssembly.Extract(); Exit:; } EX_CATCH_HRESULT(hr); return hr; } #if defined(FEATURE_HOST_ASSEMBLY_RESOLVER) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) && !defined(MDILNIGEN) HRESULT CLRPrivBinderCoreCLR::BindUsingPEImage( /* in */ PEImage *pPEImage, /* in */ BOOL fIsNativeImage, /* [retval][out] */ ICLRPrivAssembly **ppAssembly) { HRESULT hr = S_OK; EX_TRY { ReleaseHolder<BINDER_SPACE::Assembly> pCoreCLRFoundAssembly; ReleaseHolder<BINDER_SPACE::AssemblyName> pAssemblyName; ReleaseHolder<IMDInternalImport> pIMetaDataAssemblyImport; PEKIND PeKind = peNone; // Get the Metadata interface DWORD dwPAFlags[2]; IF_FAIL_GO(BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, fIsNativeImage)); IF_FAIL_GO(AssemblyBinder::TranslatePEToArchitectureType(dwPAFlags, &PeKind)); _ASSERTE(pIMetaDataAssemblyImport != NULL); // Using the information we just got, initialize the assemblyname SAFE_NEW(pAssemblyName, AssemblyName); IF_FAIL_GO(pAssemblyName->Init(pIMetaDataAssemblyImport, PeKind)); // Validate architecture if (!BINDER_SPACE::Assembly::IsValidArchitecture(pAssemblyName->GetArchitecture())) { IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_BAD_FORMAT)); } // Ensure we are not being asked to bind to a TPA assembly // // Easy out for mscorlib if (pAssemblyName->IsMscorlib()) { IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); } { SString& simpleName = pAssemblyName->GetSimpleName(); SimpleNameToFileNameMap * tpaMap = GetAppContext()->GetTpaList(); if (tpaMap->LookupPtr(simpleName.GetUnicode()) != NULL) { // The simple name of the assembly being requested to be bound was found in the TPA list. // Now, perform the actual bind to see if the assembly was really in the TPA assembly list or not. hr = BindAssemblyByNameWorker(pAssemblyName, &pCoreCLRFoundAssembly, true /* excludeAppPaths */); if (SUCCEEDED(hr)) { if (pCoreCLRFoundAssembly->GetIsInGAC()) { // If we were able to bind to a TPA assembly, then fail the load IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); } } } hr = AssemblyBinder::BindUsingPEImage(&m_appContext, pAssemblyName, pPEImage, PeKind, pIMetaDataAssemblyImport, &pCoreCLRFoundAssembly); if (hr == S_OK) { _ASSERTE(pCoreCLRFoundAssembly != NULL); pCoreCLRFoundAssembly->SetBinder(this); *ppAssembly = pCoreCLRFoundAssembly.Extract(); } } Exit:; } EX_CATCH_HRESULT(hr); return hr; } #endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) && !defined(MDILNIGEN) HRESULT CLRPrivBinderCoreCLR::VerifyBind(IAssemblyName *AssemblyName, ICLRPrivAssembly *pAssembly, ICLRPrivAssemblyInfo *pAssemblyInfo) { return E_FAIL; } HRESULT CLRPrivBinderCoreCLR::GetBinderFlags(DWORD *pBinderFlags) { if (pBinderFlags == NULL) return E_INVALIDARG; *pBinderFlags = BINDER_NONE; return S_OK; } HRESULT CLRPrivBinderCoreCLR::GetBinderID( UINT_PTR *pBinderId) { *pBinderId = reinterpret_cast<UINT_PTR>(this); return S_OK; } HRESULT CLRPrivBinderCoreCLR::FindAssemblyBySpec( LPVOID pvAppDomain, LPVOID pvAssemblySpec, HRESULT *pResult, ICLRPrivAssembly **ppAssembly) { // We are not using a cache at this level // However, assemblies bound by the CoreCLR binder is already cached in the // AppDomain and will be resolved from there if required return E_FAIL; } HRESULT CLRPrivBinderCoreCLR::SetupBindingPaths(SString &sTrustedPlatformAssemblies, SString &sPlatformResourceRoots, SString &sAppPaths, SString &sAppNiPaths) { HRESULT hr = S_OK; EX_TRY { hr = m_appContext.SetupBindingPaths(sTrustedPlatformAssemblies, sPlatformResourceRoots, sAppPaths, sAppNiPaths, TRUE /* fAcquireLock */); } EX_CATCH_HRESULT(hr); return hr; } bool CLRPrivBinderCoreCLR::IsInTpaList(const SString &sFileName) { bool fIsFileOnTpaList = false; TpaFileNameHash * tpaFileNameMap = m_appContext.GetTpaFileNameList(); if (tpaFileNameMap != nullptr) { const FileNameMapEntry *pTpaEntry = tpaFileNameMap->LookupPtr(sFileName.GetUnicode()); fIsFileOnTpaList = (pTpaEntry != nullptr); } return fIsFileOnTpaList; } // See code:BINDER_SPACE::AssemblyBinder::GetAssembly for info on fNgenExplicitBind // and fExplicitBindToNativeImage, and see code:CEECompileInfo::LoadAssemblyByPath // for an example of how they're used. HRESULT CLRPrivBinderCoreCLR::Bind(SString &assemblyDisplayName, LPCWSTR wszCodeBase, PEAssembly *pParentAssembly, BOOL fNgenExplicitBind, BOOL fExplicitBindToNativeImage, ICLRPrivAssembly **ppAssembly) { HRESULT hr = S_OK; VALIDATE_ARG_RET(ppAssembly != NULL); AssemblyName assemblyName; ReleaseHolder<AssemblyName> pAssemblyName; if (!assemblyDisplayName.IsEmpty()) { // AssemblyDisplayName can be empty if wszCodeBase is specified. SAFE_NEW(pAssemblyName, AssemblyName); IF_FAIL_GO(pAssemblyName->Init(assemblyDisplayName)); } EX_TRY { ReleaseHolder<BINDER_SPACE::Assembly> pAsm; hr = AssemblyBinder::BindAssembly(&m_appContext, pAssemblyName, wszCodeBase, pParentAssembly, fNgenExplicitBind, fExplicitBindToNativeImage, false, // excludeAppPaths &pAsm); if(SUCCEEDED(hr)) { _ASSERTE(pAsm != NULL); pAsm->SetBinder(this); *ppAssembly = pAsm.Extract(); } } EX_CATCH_HRESULT(hr); Exit: return hr; } #ifndef CROSSGEN_COMPILE HRESULT CLRPrivBinderCoreCLR::PreBindByteArray(PEImage *pPEImage, BOOL fInspectionOnly) { HRESULT hr = S_OK; VALIDATE_ARG_RET(pPEImage != NULL); EX_TRY { hr = AssemblyBinder::PreBindByteArray(&m_appContext, pPEImage, fInspectionOnly); } EX_CATCH_HRESULT(hr); return hr; } #endif // CROSSGEN_COMPILE
mit
mosass/HexapodRobot
XilinkSDK/sixpod_freertos823_bsp/ps7_cortexa9_0/libsrc/lwip141_v1_7/src/lwip-1.4.1/src/core/ipv4/ip_addr.c
9
8601
/** * @file * This is the IPv4 address tools implementation. * */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #include "lwip/opt.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" /* used by IP_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */ const ip_addr_t ip_addr_any = { IPADDR_ANY }; const ip_addr_t ip_addr_broadcast = { IPADDR_BROADCAST }; /** * Determine if an address is a broadcast address on a network interface * * @param addr address to be checked * @param netif the network interface against which the address is checked * @return returns non-zero if the address is a broadcast address */ u8_t ip4_addr_isbroadcast(u32_t addr, const struct netif *netif) { ip_addr_t ipaddr; ip4_addr_set_u32(&ipaddr, addr); /* all ones (broadcast) or all zeroes (old skool broadcast) */ if ((~addr == IPADDR_ANY) || (addr == IPADDR_ANY)) { return 1; /* no broadcast support on this network interface? */ } else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) { /* the given address cannot be a broadcast address * nor can we check against any broadcast addresses */ return 0; /* address matches network interface address exactly? => no broadcast */ } else if (addr == ip4_addr_get_u32(&netif->ip_addr)) { return 0; /* on the same (sub) network... */ } else if (ip_addr_netcmp(&ipaddr, &(netif->ip_addr), &(netif->netmask)) /* ...and host identifier bits are all ones? =>... */ && ((addr & ~ip4_addr_get_u32(&netif->netmask)) == (IPADDR_BROADCAST & ~ip4_addr_get_u32(&netif->netmask)))) { /* => network broadcast address */ return 1; } else { return 0; } } /** Checks if a netmask is valid (starting with ones, then only zeros) * * @param netmask the IPv4 netmask to check (in network byte order!) * @return 1 if the netmask is valid, 0 if it is not */ u8_t ip4_addr_netmask_valid(u32_t netmask) { u32_t mask; u32_t nm_hostorder = lwip_htonl(netmask); /* first, check for the first zero */ for (mask = 1UL << 31 ; mask != 0; mask >>= 1) { if ((nm_hostorder & mask) == 0) { break; } } /* then check that there is no one */ for (; mask != 0; mask >>= 1) { if ((nm_hostorder & mask) != 0) { /* there is a one after the first zero -> invalid */ return 0; } } /* no one after the first zero -> valid */ return 1; } /* Here for now until needed in other places in lwIP */ #ifndef isprint #define in_range(c, lo, up) ((u8_t)c >= lo && (u8_t)c <= up) #define isprint(c) in_range(c, 0x20, 0x7f) #define isdigit(c) in_range(c, '0', '9') #define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F')) #define islower(c) in_range(c, 'a', 'z') #define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v') #endif /** * Ascii internet address interpretation routine. * The value returned is in network order. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @return ip address in network order */ u32_t ipaddr_addr(const char *cp) { ip_addr_t val; if (ipaddr_aton(cp, &val)) { return ip4_addr_get_u32(&val); } return (IPADDR_NONE); } /** * Check whether "cp" is a valid ascii representation * of an Internet address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * This replaces inet_addr, the return value from which * cannot distinguish between failure and a local broadcast address. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @param addr pointer to which to save the ip address in network order * @return 1 if cp could be converted to addr, 0 on failure */ int ipaddr_aton(const char *cp, ip_addr_t *addr) { u32_t val; u8_t base; char c; u32_t parts[4]; u32_t *pp = parts; c = *cp; for (;;) { /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, 1-9=decimal. */ if (!isdigit(c)) return (0); val = 0; base = 10; if (c == '0') { c = *++cp; if (c == 'x' || c == 'X') { base = 16; c = *++cp; } else base = 8; } for (;;) { if (isdigit(c)) { val = (val * base) + (int)(c - '0'); c = *++cp; } else if (base == 16 && isxdigit(c)) { val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A')); c = *++cp; } else break; } if (c == '.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16 bits) * a.b (with b treated as 24 bits) */ if (pp >= parts + 3) { return (0); } *pp++ = val; c = *++cp; } else break; } /* * Check for trailing characters. */ if (c != '\0' && !isspace(c)) { return (0); } /* * Concoct the address according to * the number of parts specified. */ switch (pp - parts + 1) { case 0: return (0); /* initial nondigit */ case 1: /* a -- 32 bits */ break; case 2: /* a.b -- 8.24 bits */ if (val > 0xffffffUL) { return (0); } val |= parts[0] << 24; break; case 3: /* a.b.c -- 8.8.16 bits */ if (val > 0xffff) { return (0); } val |= (parts[0] << 24) | (parts[1] << 16); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (val > 0xff) { return (0); } val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); break; default: LWIP_ASSERT("unhandled", 0); break; } if (addr) { ip4_addr_set_u32(addr, htonl(val)); } return (1); } /** * Convert numeric IP address into decimal dotted ASCII representation. * returns ptr to static buffer; not reentrant! * * @param addr ip address in network order to convert * @return pointer to a global static (!) buffer that holds the ASCII * represenation of addr */ char * ipaddr_ntoa(const ip_addr_t *addr) { static char str[16]; return ipaddr_ntoa_r(addr, str, 16); } /** * Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used. * * @param addr ip address in network order to convert * @param buf target buffer where the string is stored * @param buflen length of buf * @return either pointer to buf which now holds the ASCII * representation of addr or NULL if buf was too small */ char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen) { u32_t s_addr; char inv[3]; char *rp; u8_t *ap; u8_t rem; u8_t n; u8_t i; int len = 0; s_addr = ip4_addr_get_u32(addr); rp = buf; ap = (u8_t *)&s_addr; for(n = 0; n < 4; n++) { i = 0; do { rem = *ap % (u8_t)10; *ap /= (u8_t)10; inv[i++] = '0' + rem; } while(*ap); while(i--) { if (len++ >= buflen) { return NULL; } *rp++ = inv[i]; } if (len++ >= buflen) { return NULL; } *rp++ = '.'; ap++; } *--rp = 0; return buf; }
mit
alexhenrie/poedit
deps/boost/tools/quickbook/test/src/text_diff.cpp
9
2701
// // Copyright (c) 2005 João Abecasis // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <vector> #include <boost/spirit/include/classic_primitives.hpp> #include <boost/spirit/include/classic_scanner.hpp> namespace spirit = boost::spirit::classic; typedef std::istream_iterator<char, char> iterator; typedef spirit::scanner<iterator> scanner; int main(int argc, char* argv[]) { std::vector<char*> args; bool usage_error = false; for (int i = 1; i < argc; ++i) { if (std::strncmp(argv[i], "--", 2) == 0) { if (strcmp(argv[i], "--strict") == 0) { // Ignore --strict because the build file accidentally // uses it. Why yes, this is a horrible hack. } else { std::cerr << "ERROR: Invalid flag: " << argv[i] << std::endl; usage_error = true; } } else { args.push_back(argv[i]); } } if (!usage_error && args.size() != 2) { std::cerr << "ERROR: Wrong number of arguments." << std::endl; usage_error = true; } if (usage_error) { std::cout << "Usage:\n\t" << argv[0] << " file1 file2" << std::endl; return 1; } std::ifstream file1(args[0], std::ios_base::binary | std::ios_base::in), file2(args[1], std::ios_base::binary | std::ios_base::in); if (!file1 || !file2) { std::cerr << "ERROR: Unable to open one or both files." << std::endl; return 2; } file1.unsetf(std::ios_base::skipws); file2.unsetf(std::ios_base::skipws); iterator iter_file1(file1), iter_file2(file2); scanner scan1(iter_file1, iterator()), scan2(iter_file2, iterator()); std::size_t line = 1, column = 1; while (!scan1.at_end() && !scan2.at_end()) { if (spirit::eol_p.parse(scan1)) { if (!spirit::eol_p.parse(scan2)) { std::cout << "Files differ at line " << line << ", column " << column << '.' << std::endl; return 3; } ++line, column = 1; continue; } if (*scan1 != *scan2) { std::cout << "Files differ at line " << line << ", column " << column << '.' << std::endl; return 4; } ++scan1, ++scan2, ++column; } if (scan1.at_end() != scan2.at_end()) { std::cout << "Files differ in length." << std::endl; return 5; } }
mit
quxn6/wugargar
NNGameFramework/NNGameFramework/Library/TinyXML/xpath_processor.cpp
9
72591
/* www.sourceforge.net/projects/tinyxpath Copyright (c) 2002-2004 Yves Berquin (yvesb@users.sourceforge.net) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* @history: Modified on 16 December 2006 by Aman Aggarwal ::Added support for Expressions like ( Expr or Expr or Expr) Modified on 18 December 2006 by Aman Aggarwal ::Added support for translate() */ #include <math.h> #include "xpath_processor.h" #include "xml_util.h" using namespace TinyXPath; #ifdef TINYXPATH_DEBUG // only define DUMP_ACTION if TINYXPATH_DEBUG is defined #define DUMP_ACTION #endif /// xpath_processor constructor xpath_processor::xpath_processor ( const TiXmlNode * XNp_source_tree, ///< Source XML tree const char * cp_xpath_expr) ///< XPath expression : xpath_stream (cp_xpath_expr) { if (XNp_source_tree && cp_xpath_expr) XNp_base = XNp_source_tree; else XNp_base = NULL; er_result . v_set_root (XNp_base); xs_stack . v_set_root (XNp_base); XEp_context = NULL; o_is_context_by_name = false; XNp_base_parent = NULL; } /// Compute an XPath expression, and return the number of nodes in the resulting node set. /// \n Returns 0 if the result is not a node set unsigned xpath_processor::u_compute_xpath_node_set () { er_compute_xpath (); if (er_result . e_type != e_node_set) return 0; return er_result . nsp_get_node_set () -> u_get_nb_node_in_set (); } /// Get one of the XML nodes from the resulting node set. Can only be used after a call to u_compute_xpath_node_set void xpath_processor::v_get_xpath_base ( unsigned u_order, ///< Order of the node. Must be between 0 and the number of nodes - 1 const TiXmlBase * & XBp_res, ///< Output node bool & o_attrib) ///< True if the output node is an attribute, false if it's a TiXmlNode { XBp_res = NULL; o_attrib = false; if (er_result . e_type != e_node_set) return; if (u_order >= er_result . nsp_get_node_set () -> u_get_nb_node_in_set ()) return; XBp_res = er_result . nsp_get_node_set () -> XBp_get_base_in_set (u_order); o_attrib = er_result . nsp_get_node_set () -> o_is_attrib (u_order); } /// Retrieves an XPath node from the node set. This assumes you know it's not an attribute TiXmlNode * xpath_processor::XNp_get_xpath_node ( unsigned u_order) ///< Order of the node. Must be between 0 and the number of nodes - 1 { bool o_attrib; const TiXmlBase * XBp_res; o_attrib = false; XBp_res = NULL; v_get_xpath_base (u_order, XBp_res, o_attrib); if (o_attrib) return NULL; return (TiXmlNode *) XBp_res; } /// Retrieves an XPath attribute from the node set. This assumes you know it's an attribute TiXmlAttribute * xpath_processor::XAp_get_xpath_attribute ( unsigned u_order) ///< Order of the node. Must be between 0 and the number of nodes - 1 { bool o_attrib; const TiXmlBase * XBp_res; o_attrib = false; XBp_res = NULL; v_get_xpath_base (u_order, XBp_res, o_attrib); if (! o_attrib) return NULL; return (TiXmlAttribute *) XBp_res; } void xpath_processor::v_build_root () { if (XNp_base) { XNp_base_parent = XNp_base -> Parent (); if (! XNp_base_parent) // no correct initialization of the xpath_processor object throw execution_error (1); // set the main node as the context one, if it's an element if (XNp_base -> ToElement ()) XEp_context = XNp_base -> ToElement (); } else XNp_base_parent = NULL; } /// Compute an XPath expression expression_result xpath_processor::er_compute_xpath () { try { XNp_base_parent = XNp_base -> Parent (); if (! XNp_base_parent) // no correct initialization of the xpath_processor object throw execution_error (1); // set the main node as the context one, if it's an element if (XNp_base -> ToElement ()) XEp_context = XNp_base -> ToElement (); // Decode XPath expression v_evaluate (); // Compute result v_execute_stack (); /// The executions stack need to contain 1 and only 1 element, otherwize it's not valid if (xs_stack . u_get_size () == 1) { er_result = * xs_stack . erp_top (); xs_stack . v_pop (); e_error = e_no_error; } else { expression_result er_null (NULL); er_result = er_null; e_error = e_error_stack; } } catch (syntax_error) { expression_result er_null (NULL); er_result = er_null; e_error = e_error_syntax; } catch (syntax_overflow) { expression_result er_null (NULL); er_result = er_null; e_error = e_error_overflow; } catch (execution_error) { expression_result er_null (NULL); er_result = er_null; e_error = e_error_execution; } return er_result; } /// Compute an XPath expression and return the result as a string TIXML_STRING xpath_processor::S_compute_xpath () { expression_result er_res (XNp_base); TIXML_STRING S_res; er_res = er_compute_xpath (); S_res = er_res . S_get_string (); return S_res; } /// Compute an XPath expression and return the result as an integer int xpath_processor::i_compute_xpath () { expression_result er_res (XNp_base); int i_res; er_res = er_compute_xpath (); i_res = er_res . i_get_int (); return i_res; } bool xpath_processor::o_compute_xpath () { expression_result er_res (XNp_base); bool o_res; er_res = er_compute_xpath (); o_res = er_res . o_get_bool (); return o_res; } double xpath_processor::d_compute_xpath () { expression_result er_res (XNp_base); double d_res; er_res = er_compute_xpath (); d_res = er_res . d_get_double (); return d_res; } /// Callback from the XPath decoder : a rule has to be applied void xpath_processor::v_action ( xpath_construct xc_rule, ///< XPath Rule unsigned u_sub, ///< Rule sub number unsigned u_variable, ///< Parameter, depends on the rule const char * cp_literal) ///< Input literal, depends on the rule { as_action_store . v_add (xc_rule, u_sub, u_variable, cp_literal); #ifdef TINYXPATH_DEBUG printf ("Action %2d : %s (%d,%d,%s)\n", as_action_store . i_get_size () - 1, cp_disp_construct (xc_rule), u_sub, u_variable, cp_literal); #endif } /// Internal use. Retrieves the current action counter int xpath_processor::i_get_action_counter () { // callback for current stack position return as_action_store . i_get_size (); } /// Internal use. Executes the XPath expression. The executions starts at the end of the as_action_store list void xpath_processor::v_execute_stack () { as_action_store . v_set_position (as_action_store . i_get_size () - 1); v_execute_one (xpath_expr, false); } /// Retrieves one quadruplet from the action placeholder void xpath_processor::v_pop_one_action ( xpath_construct & xc_action, ///< Next rule on placeholder unsigned & u_sub, ///< Sub rule unsigned & u_ref, ///< Rule optional parameter TIXML_STRING & S_literal) ///< Rule optional string { int i_1, i_2, i_3; as_action_store . v_get (as_action_store . i_get_position (), i_1, i_2, i_3, S_literal); xc_action = (xpath_construct) i_1; u_sub = i_2; u_ref = i_3; as_action_store . v_dec_position (); } /// Executes one XPath rule void xpath_processor::v_execute_one ( xpath_construct xc_rule, ///< Rule number bool o_skip_only) ///< True if we only need to skip rules and not act on the data stack { xpath_construct xc_action; unsigned u_sub; unsigned u_variable; TIXML_STRING S_literal; TIXML_STRING S_temp; TIXML_STRING S_name; expression_result ** erpp_arg; unsigned u_arg; bool o_error; v_pop_one_action (xc_action, u_sub, u_variable, S_literal); // verify it's the rule we were waiting for if (xc_action != xc_rule) throw execution_error (2); switch (xc_action) { case xpath_expr : // [14] Expr ::= OrExpr v_execute_one (xpath_or_expr, o_skip_only); break; case xpath_or_expr : switch (u_sub) { case xpath_or_expr_simple : v_execute_one (xpath_and_expr, o_skip_only); break; case xpath_or_expr_or : o_error = false; erpp_arg = NULL; try { v_execute_one (xpath_and_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_and_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); v_function_or (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (3); break; case xpath_or_expr_more : { // These case is involved for expressions like a or b or c try { o_error = false; erpp_arg = NULL; v_execute_one (xpath_and_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_or_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); v_function_or (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (7); } break; } break; case xpath_and_expr : switch (u_sub) { case xpath_and_expr_simple : v_execute_one (xpath_equality_expr, o_skip_only); break; case xpath_and_expr_and : o_error = false; erpp_arg = NULL; try { v_execute_one (xpath_equality_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_equality_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); v_function_and (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (4); break; } break; case xpath_equality_expr : switch (u_sub) { case xpath_equality_expr_simple : v_execute_one (xpath_relational_expr, o_skip_only); break; case xpath_equality_expr_equal : case xpath_equality_expr_not_equal : o_error = false; erpp_arg = NULL; try { v_execute_one (xpath_relational_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_relational_expr, o_skip_only); // this is buggy. should be xpath_equality_expr if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); if (u_sub == xpath_equality_expr_equal) v_function_equal (erpp_arg); else v_function_not_equal (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (5); break; } break; case xpath_relational_expr : switch (u_sub) { case xpath_relational_expr_simple : v_execute_one (xpath_additive_expr, o_skip_only); break; case xpath_relational_expr_lt : case xpath_relational_expr_gt : case xpath_relational_expr_lte : case xpath_relational_expr_gte : o_error = false; erpp_arg = NULL; try { v_execute_one (xpath_additive_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_additive_expr, o_skip_only); // this is buggy. should be xpath_equality_expr if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); v_function_relational (erpp_arg, u_sub); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (6); break; default : assert (false); } break; case xpath_additive_expr : switch (u_sub) { case xpath_additive_expr_simple : v_execute_one (xpath_multiplicative_expr, o_skip_only); break; case xpath_additive_expr_plus : case xpath_additive_expr_minus : try { o_error = false; erpp_arg = NULL; v_execute_one (xpath_multiplicative_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_multiplicative_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); if (u_sub == xpath_additive_expr_plus) v_function_plus (erpp_arg); else v_function_minus (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (7); break; case xpath_additive_expr_more_plus : case xpath_additive_expr_more_minus : // These 2 cases are involved for expressions like a+b+c // The second argument is an additive expression, not a multiplicative as it is the case // when single a+b expressions are encountered try { o_error = false; erpp_arg = NULL; v_execute_one (xpath_multiplicative_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_additive_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); if (u_sub == xpath_additive_expr_more_plus) v_function_plus (erpp_arg); else v_function_minus (erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (7); break; } break; case xpath_multiplicative_expr : switch (u_sub) { case xpath_multiplicative_expr_simple : v_execute_one (xpath_unary_expr, o_skip_only); break; case xpath_multiplicative_expr_star : case xpath_multiplicative_expr_div : case xpath_multiplicative_expr_mod : try { o_error = false; erpp_arg = NULL; v_execute_one (xpath_unary_expr, o_skip_only); if (! o_skip_only) { erpp_arg = new expression_result * [2]; memset (erpp_arg, 0, 2 * sizeof (expression_result *)); erpp_arg [1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } v_execute_one (xpath_unary_expr, o_skip_only); if (! o_skip_only) { erpp_arg [0] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); v_function_mult (erpp_arg, u_sub); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < 2; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (8); break; } break; case xpath_unary_expr : switch (u_sub) { case xpath_unary_expr_simple : // [27] UnaryExpr ::= UnionExpr v_execute_one (xpath_union_expr, o_skip_only); break; case xpath_unary_expr_minus : // [27] UnaryExpr ::= '-' UnaryExpr v_execute_one (xpath_unary_expr, o_skip_only); v_function_opposite (); break; } break; case xpath_union_expr : switch (u_sub) { case xpath_union_expr_simple : v_execute_one (xpath_path_expr, o_skip_only); break; case xpath_union_expr_union : v_execute_one (xpath_union_expr, o_skip_only); if (xs_stack . erp_top () -> e_type != e_node_set) throw execution_error (9); // here after is a block, so that the node_set are locals to it { node_set ns_1, ns_2; ns_1 = ns_pop_node_set (); v_execute_one (xpath_path_expr, o_skip_only); ns_2 = ns_pop_node_set (); v_function_union (ns_1, ns_2); } break; } break; case xpath_path_expr : switch (u_sub) { case xpath_path_expr_location_path : v_execute_one (xpath_location_path, o_skip_only); break; case xpath_path_expr_filter : v_execute_one (xpath_filter_expr, o_skip_only); break; case xpath_path_expr_slash : v_execute_one (xpath_filter_expr, o_skip_only); v_execute_one (xpath_relative_location_path, o_skip_only); break; case xpath_path_expr_2_slash : v_execute_one (xpath_filter_expr, o_skip_only); v_execute_one (xpath_relative_location_path, o_skip_only); break; } break; case xpath_filter_expr : switch (u_sub) { case xpath_filter_expr_primary : v_execute_one (xpath_primary_expr, o_skip_only); break; case xpath_filter_expr_predicate : v_execute_one (xpath_filter_expr, o_skip_only); v_execute_one (xpath_predicate, o_skip_only); break; } break; case xpath_primary_expr : switch (u_sub) { case xpath_primary_expr_variable : v_execute_one (xpath_variable_reference, o_skip_only); break; case xpath_primary_expr_paren_expr : v_execute_one (xpath_expr, o_skip_only); break; case xpath_primary_expr_literal : if (! o_skip_only) v_push_string (S_literal); break; case xpath_primary_expr_number : if (! o_skip_only) { if (strchr (S_literal . c_str (), '.')) v_push_double (atof (S_literal . c_str ())); else v_push_int (atoi (S_literal . c_str ()), "primary number"); } break; case xpath_primary_expr_function_call : v_execute_one (xpath_function_call, o_skip_only); break; } break; case xpath_function_call : erpp_arg = NULL; o_error = false; try { if (u_sub) { // execute arguments if (! o_skip_only) { erpp_arg = new expression_result * [u_variable]; memset (erpp_arg, 0, u_variable * sizeof (expression_result *)); } for (u_arg = 0; u_arg < u_variable; u_arg++) { /// Compute each argument, and store them in a temporary list v_execute_one (xpath_argument, o_skip_only); if (! o_skip_only) { if (! xs_stack . u_get_size ()) throw execution_error (10); erpp_arg [u_variable - u_arg - 1] = new expression_result (* xs_stack . erp_top ()); xs_stack . v_pop (); } } } v_execute_one (xpath_xml_q_name, o_skip_only); if (! o_skip_only) { S_name = S_pop_string (); v_execute_function (S_name, u_variable, erpp_arg); } } catch (execution_error) { o_error = true; } if (erpp_arg) { for (u_arg = 0; u_arg < u_variable; u_arg++) { if (erpp_arg [u_arg]) delete erpp_arg [u_arg]; } delete [] erpp_arg; } if (o_error) throw execution_error (11); break; case xpath_xml_q_name : switch (u_sub) { case xpath_xml_q_name_colon : v_execute_one (xpath_xml_local_part, o_skip_only); v_execute_one (xpath_xml_prefix, o_skip_only); break; case xpath_xml_q_name_simple : v_execute_one (xpath_xml_local_part, o_skip_only); break; } break; case xpath_xml_local_part : if (! o_skip_only) v_push_string (S_literal); break; case xpath_xml_prefix : if (! o_skip_only) { // we replace the current stack content (local_part) by the fully // qualified XML name (prefix:local_part) S_name = S_pop_string (); S_literal += ":"; S_literal += S_name; v_push_string (S_literal); } break; case xpath_argument : v_execute_one (xpath_expr, o_skip_only); break; case xpath_location_path : switch (u_sub) { case xpath_location_path_rel : v_execute_one (xpath_relative_location_path, o_skip_only); break; case xpath_location_path_abs : v_execute_one (xpath_absolute_location_path, o_skip_only); break; } break; case xpath_relative_location_path : switch (u_sub) { case xpath_relative_location_path_rel_step : // RelativeLocationPath ::= RelativeLocationPath '/' Step v_execute_one (xpath_relative_location_path, o_skip_only); // v_execute_step (i_relative_action); break; case xpath_relative_location_path_rel_double_slash_step : // RelativeLocationPath ::= RelativeLocationPath '//' Step break; case xpath_relative_location_path_step : // RelativeLocationPath ::= Step int i_dummy; i_dummy = -2; v_execute_step (i_dummy, o_skip_only); break; } break; case xpath_absolute_location_path : switch (u_sub) { case xpath_absolute_location_path_slash : // AbsoluteLocationPath ::= '/' v_execute_absolute_path (u_variable, false, false); break; case xpath_absolute_location_path_slash_rel : // AbsoluteLocationPath ::= '/' RelativeLocationPath v_execute_absolute_path (u_variable, true, false); break; case xpath_absolute_location_path_abbrev : // AbsoluteLocationPath ::= AbbreviatedAbsoluteLocationPath v_execute_absolute_path (u_variable, true, true); break; } break; case xpath_axis_specifier : switch (u_sub) { case xpath_axis_specifier_at : // AxisSpecifier ::= '@' if (! o_skip_only) // will be used in the v_execute_step v_push_int (1, "axis specifier is at"); break; case xpath_axis_specifier_axis_name : // AxisSpecifier ::= AxisName '::' v_execute_one (xpath_axis_name, o_skip_only); break; case xpath_axis_specifier_empty : if (! o_skip_only) // will be used in the v_execute_step v_push_int (0, "axis specifier is empty"); break; } break; case xpath_axis_name : if (! o_skip_only) // will be used in the v_execute_step v_push_int (u_variable, "axis is a name"); break; case xpath_node_test : // to do : processing instructions ??? switch (u_sub) { case xpath_node_test_reserved_keyword : // will be used in the v_execute_step if (! o_skip_only) { i_pop_int (); v_push_int (u_variable, "axis is a keyword"); S_temp = "*"; v_push_string (S_temp); } break; case xpath_node_test_pi : break; case xpath_node_test_pi_lit : break; case xpath_node_test_name_test : v_execute_one (xpath_name_test, o_skip_only); break; } break; case xpath_predicate : // [8] Predicate ::= '[' PredicateExpr ']' v_execute_one (xpath_predicate_expr, o_skip_only); break; case xpath_predicate_expr : // [9] PredicateExpr ::= Expr v_execute_one (xpath_expr, o_skip_only); break; case xpath_name_test : switch (u_sub) { case xpath_name_test_star : if (! o_skip_only) { S_temp = "*"; v_push_string (S_temp); } break; case xpath_name_test_ncname : break; case xpath_name_test_qname : v_execute_one (xpath_xml_q_name, o_skip_only); break; } break; default : throw execution_error (12); } } /// Execute a full set of absolute/relative/relative/.. computation void xpath_processor::v_execute_absolute_path ( unsigned u_action_position, ///< Position of the placeholder after the rule bool o_with_rel, ///< true if there is some relative path bool o_everywhere) ///< true if it's a '//' path { unsigned u_end_action; int i_relative_action; bool o_do_last; u_end_action = u_action_position; if (o_with_rel) { int i_1, i_2, i_3; int i_bak_position, i_current, i_first, i_relative; TIXML_STRING S_lit; // compute position of the first (absolute) step i_current = as_action_store . i_get_position (); if (o_everywhere) i_relative = i_current - 2; else i_relative = i_current - 1; as_action_store . v_get (i_relative, i_1, i_2, i_3, S_lit); if (i_1 == xpath_relative_location_path) { o_do_last = true; i_first = i_3 - 1; } else { o_do_last = false; i_first = i_relative; } // i_first = i_3 - 1; i_bak_position = as_action_store . i_get_position (); as_action_store . v_set_position (i_first); if (o_everywhere) i_relative_action = -1; else i_relative_action = 0; v_execute_step (i_relative_action, false); bool o_end = false; do { i_relative--; as_action_store . v_get (i_relative, i_1, i_2, i_3, S_lit); if (i_1 != xpath_relative_location_path) o_end = true; else { as_action_store . v_set_position (i_3 - 1); v_execute_step (i_relative_action, false); } } while (! o_end); if (o_do_last) { // apply last one as_action_store . v_set_position (i_relative); v_execute_step (i_relative_action, false); } // resume the execution after the whole path construction as_action_store . v_set_position ((int) u_end_action - 1); } } /// One step execution void xpath_processor ::v_execute_step ( int & i_relative_action, ///< Path position : -1 if first in a '//' path, 0 if first in a '/' path, > 0 if followers bool o_skip_only) { bool o_by_name; int i_axis_type, i_end_store, i_node_store, i_pred_store; unsigned u_nb_node, u_node, u_pred, u_sub, u_variable; xpath_construct xc_action; TIXML_STRING S_literal, S_name; const TiXmlElement * XEp_child, * XEp_elem; const TiXmlNode * XNp_father; const TiXmlAttribute * XAp_attrib; const TiXmlNode * XNp_next, * XNp_parent; node_set ns_source, ns_target; if (! o_skip_only) { /// Initialize the source node set if it's the first step of a path switch (i_relative_action) { case -2 : // relative to context ns_source . v_add_node_in_set (XEp_context); i_relative_action = 1; break; case -1 : // everywhere ns_source . v_copy_selected_node_recursive_root_only (XNp_base_parent, XNp_base); i_relative_action = 1; break; case 0 : // first absolute ns_source . v_add_node_in_set (XNp_base_parent); i_relative_action = 1; break; default : // second and following steps ns_source = * (xs_stack . erp_top () -> nsp_get_node_set ()); xs_stack . v_pop (); break; } } // Pop our step action from the action placeholder v_pop_one_action (xc_action, u_sub, u_variable, S_literal); // Skip the predicates i_pred_store = as_action_store . i_get_position (); for (u_pred = 0; u_pred < u_variable; u_pred++) v_execute_one (xpath_predicate, true); i_node_store = as_action_store . i_get_position (); // Skip the node test v_execute_one (xpath_node_test, true); // Run the axis v_execute_one (xpath_axis_specifier, o_skip_only); i_end_store = as_action_store . i_get_position (); // Run the node test as_action_store . v_set_position (i_node_store); v_execute_one (xpath_node_test, o_skip_only); as_action_store . v_set_position (i_pred_store); if (! o_skip_only) { S_name = S_pop_string (); o_by_name = ! (S_name == "*"); // Retrieve the archive flag stored by the xpath_axis_specifier rule execution // o_attrib_flag = o_pop_bool (); i_axis_type = i_pop_int (); u_nb_node = ns_source . u_get_nb_node_in_set (); for (u_node = 0; u_node < u_nb_node; u_node++) { if (! ns_source . o_is_attrib (u_node)) { XNp_father = ns_source . XNp_get_node_in_set (u_node); if (XNp_father) { switch (i_axis_type) { case 0 : case lex_child : // none XEp_child = XNp_father -> FirstChildElement (); while (XEp_child) { ns_target . v_add_node_in_set_if_name_or_star (XEp_child, S_name); XEp_child = XEp_child -> NextSiblingElement (); } break; case 1 : case lex_attribute : // @ if (XNp_father -> ToElement ()) XAp_attrib = XNp_father -> ToElement () -> FirstAttribute (); else XAp_attrib = NULL; while (XAp_attrib) { ns_target . v_add_attrib_in_set_if_name_or_star (XAp_attrib, S_name); XAp_attrib = XAp_attrib -> Next (); } break; case lex_parent : XNp_parent = XNp_father -> Parent (); if (XNp_parent) ns_target . v_add_node_in_set_if_name_or_star (XNp_parent, S_name); break; case lex_ancestor : XNp_parent = XNp_father -> Parent (); // we have to exclude our own dummy parent while (XNp_parent && XNp_parent != XNp_base_parent) { ns_target . v_add_node_in_set_if_name_or_star (XNp_parent, S_name); XNp_parent = XNp_parent -> Parent (); } break; case lex_ancestor_or_self : if (XNp_father -> ToElement () && XNp_father != XNp_base_parent) ns_target . v_add_node_in_set_if_name_or_star (XNp_father, S_name); XNp_parent = XNp_father -> Parent (); while (XNp_parent && XNp_parent != XNp_base_parent) { ns_target . v_add_node_in_set_if_name_or_star (XNp_parent, S_name); XNp_parent = XNp_parent -> Parent (); } break; case lex_following_sibling : XNp_next = XNp_father -> NextSiblingElement (); while (XNp_next) { ns_target . v_add_node_in_set_if_name_or_star (XNp_next, S_name); XNp_next = XNp_next -> NextSiblingElement (); } break; case lex_preceding_sibling : XNp_next = XNp_father -> PreviousSibling (); while (XNp_next) { if (XNp_next -> Type () == TiXmlNode::TINYXML_ELEMENT) ns_target . v_add_node_in_set_if_name_or_star (XNp_next, S_name); XNp_next = XNp_next -> PreviousSibling (); } break; case lex_descendant : if (XNp_father -> ToElement ()) { if (S_name == "*") ns_target . v_copy_selected_node_recursive_no_attrib (XNp_father, NULL); else ns_target . v_copy_selected_node_recursive_no_attrib (XNp_father, S_name . c_str ()); } break; case lex_descendant_or_self : if (XNp_father -> ToElement ()) { if (XNp_father != XNp_base_parent) ns_target . v_add_node_in_set_if_name_or_star (XNp_father, S_name); if (S_name == "*") ns_target . v_copy_selected_node_recursive_no_attrib (XNp_father, NULL); else ns_target . v_copy_selected_node_recursive_no_attrib (XNp_father, S_name . c_str ()); } break; case lex_self : if (XNp_father -> ToElement ()) { if (XNp_father != XNp_base_parent && XNp_father -> ToElement ()) ns_target . v_add_node_in_set_if_name_or_star (XNp_father, S_name); } break; case lex_following : ns_target . v_add_all_foll_node (XNp_father, S_name); break; case lex_preceding : ns_target . v_add_all_prec_node (XNp_father, S_name); break; case lex_comment : XNp_next = XNp_father -> FirstChild (); while (XNp_next) { if (XNp_next -> Type () == TiXmlNode::TINYXML_COMMENT) ns_target . v_add_node_in_set (XNp_next); XNp_next = XNp_next -> NextSibling (); } break; case lex_text : XNp_next = XNp_father -> FirstChild (); while (XNp_next) { if (XNp_next -> Type () == TiXmlNode::TINYXML_TEXT) ns_target . v_add_node_in_set (XNp_next); XNp_next = XNp_next -> NextSibling (); } break; case lex_node : XNp_next = XNp_father -> FirstChild (); while (XNp_next) { ns_target . v_add_node_in_set (XNp_next); XNp_next = XNp_next -> NextSibling (); } break; default : // an axis name followed by '::' throw error_not_yet (); break; } } } } if (u_variable) { // we have predicates to apply node_set ns_after_predicate; for (u_node = 0; u_node < ns_target .u_get_nb_node_in_set (); u_node++) { if (! ns_target . o_is_attrib (u_node)) { XEp_elem = ns_target . XNp_get_node_in_set (u_node) -> ToElement (); if (XEp_elem) { as_action_store . v_set_position (i_pred_store); if (o_check_predicate (XEp_elem, o_by_name)) ns_after_predicate . v_add_node_in_set (XEp_elem); } } } v_push_node_set (& ns_after_predicate); } else v_push_node_set (& ns_target); } as_action_store . v_set_position (i_end_store); } /// Spec extract : /// \n A PredicateExpr is evaluated by evaluating the Expr and converting the result to a /// boolean. If the result is a number, the result will be converted to true if the number /// is equal to the context position and will be converted to false otherwise; if the result /// is not a number, then the result will be converted as if by a call to the boolean function. /// Thus a location path para[3] is equivalent to para[position()=3]. bool xpath_processor::o_check_predicate (const TiXmlElement * XEp_child, bool o_by_name) { expression_result * erp_top; bool o_keep; v_set_context (XEp_child, o_by_name); v_execute_one (xpath_predicate, false); v_set_context (NULL, false); erp_top = xs_stack . erp_top (); switch (erp_top -> e_type) { case e_double : case e_int : o_keep = (erp_top -> i_get_int () == i_xml_cardinality (XEp_child, o_by_name)); break; default : o_keep = erp_top -> o_get_bool (); break; } xs_stack . v_pop (); return o_keep; } /** Execute an XPath function. The arguments are in normal order in erpp_arg\n Calls one of the following : - v_function_ceiling - v_function_concat - v_function_contains - v_function_count - v_function_false - v_function_floor - v_function_last - v_function_name - v_function_normalize_space - v_function_not - v_function_position - v_function_starts_with - v_function_string_length - v_function_substring - v_function_sum - v_function_true */ void xpath_processor::v_execute_function ( TIXML_STRING & S_name, ///< Function name unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { if (S_name == "ceiling") v_function_ceiling (u_nb_arg, erpp_arg); else if (S_name == "concat") v_function_concat (u_nb_arg, erpp_arg); else if (S_name == "contains") v_function_contains (u_nb_arg, erpp_arg); else if (S_name == "count") v_function_count (u_nb_arg, erpp_arg); else if (S_name == "false") v_function_false (u_nb_arg, erpp_arg); else if (S_name == "floor") v_function_floor (u_nb_arg, erpp_arg); else if (S_name == "last") v_function_last (u_nb_arg, erpp_arg); else if (S_name == "name") v_function_name (u_nb_arg, erpp_arg); else if (S_name == "normalize-space") v_function_normalize_space (u_nb_arg, erpp_arg); else if (S_name == "not") v_function_not (u_nb_arg, erpp_arg); else if (S_name == "position") v_function_position (u_nb_arg, erpp_arg); else if (S_name == "starts-with") v_function_starts_with (u_nb_arg, erpp_arg); else if (S_name == "string-length") v_function_string_length (u_nb_arg, erpp_arg); else if (S_name == "substring") v_function_substring (u_nb_arg, erpp_arg); else if (S_name == "sum") v_function_sum (u_nb_arg, erpp_arg); else if (S_name == "text") v_function_text (u_nb_arg, erpp_arg); else if (S_name == "translate") v_function_translate (u_nb_arg, erpp_arg); else if (S_name == "true") v_function_true (u_nb_arg, erpp_arg); else throw execution_error (13); } /// XPath \b ceiling function void xpath_processor::v_function_ceiling ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { int i_val; if (u_nb_arg != 1) throw execution_error (14); switch (erpp_arg [0] -> e_type) { case e_int : case e_bool : i_val = erpp_arg [0] -> i_get_int (); break; case e_double : i_val = (int) ceil (erpp_arg [0] -> d_get_double ()); break; default : i_val = 0; break; } v_push_int (i_val, "ceiling"); } /// XPath \b concat function void xpath_processor::v_function_concat ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_res; unsigned u_arg; if (! u_nb_arg) throw execution_error (15); S_res = erpp_arg [0] -> S_get_string (); for (u_arg = 1; u_arg < u_nb_arg; u_arg++) S_res += erpp_arg [u_arg] -> S_get_string () . c_str (); v_push_string (S_res); } /// XPath \b contains function void xpath_processor::v_function_contains ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_arg_1, S_arg_2; if (u_nb_arg != 2) throw execution_error (16); S_arg_1 = erpp_arg [0] -> S_get_string (); S_arg_2 = erpp_arg [1] -> S_get_string (); v_push_bool (strstr (S_arg_1 . c_str (), S_arg_2 . c_str ()) ? true : false); } /// XPath \b count function void xpath_processor::v_function_count ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { int i_res; if (! u_nb_arg) throw execution_error (17); if (erpp_arg [0] -> e_type != e_node_set) i_res = 0; else i_res = erpp_arg [0] -> nsp_get_node_set () -> u_get_nb_node_in_set (); v_push_int (i_res, "count result"); } /// XPath \b false function void xpath_processor::v_function_false ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { if (u_nb_arg) throw execution_error (18); v_push_bool (false); } /// XPath \b floor function void xpath_processor::v_function_floor ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { int i_val; if (u_nb_arg != 1) throw execution_error (19); switch (erpp_arg [0] -> e_type) { case e_int : case e_bool : i_val = erpp_arg [0] -> i_get_int (); break; case e_double : i_val = (int) floor (erpp_arg [0] -> d_get_double ()); break; default : i_val = 0; break; } v_push_int (i_val, "floor"); } /// XPath \b last function void xpath_processor::v_function_last ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { const TiXmlElement * XEp_context; if (u_nb_arg) throw execution_error (20); XEp_context = XEp_get_context (); if (! XEp_context) throw execution_error (21); v_push_int (i_xml_family_size (XEp_context), "last()"); } /// XPath \b name function /// \n XPath spec: If the argument it omitted, it defaults to a node-set with the context node as its only member. void xpath_processor::v_function_name ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_res; node_set * nsp_set; switch (u_nb_arg) { case 0 : // name of the context node XEp_context = XEp_get_context (); S_res = XEp_context -> Value (); break; case 1 : // name of the argument S_res = ""; if (erpp_arg [0] -> e_type == e_node_set) { nsp_set = erpp_arg [0] -> nsp_get_node_set (); if (nsp_set -> u_get_nb_node_in_set ()) if (nsp_set -> o_is_attrib (0)) S_res = nsp_set -> XAp_get_attribute_in_set (0) -> Name (); else S_res = nsp_set -> XNp_get_node_in_set (0) -> Value (); } break; default : throw execution_error (22); } v_push_string (S_res); } /// XPath \b normalize-space function void xpath_processor::v_function_normalize_space ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_arg, S_res; if (u_nb_arg != 1) throw execution_error (23); S_arg = erpp_arg [0] -> S_get_string (); S_res = S_remove_lead_trail (S_arg . c_str ()); v_push_string (S_res); } /// XPath \b not function void xpath_processor::v_function_not ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { if (u_nb_arg != 1) throw execution_error (24); v_push_bool (! erpp_arg [0] -> o_get_bool ()); } /// XPath \b position function void xpath_processor::v_function_position ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { const TiXmlElement * XEp_context; if (u_nb_arg) throw execution_error (25); XEp_context = XEp_get_context (); if (! XEp_context) throw execution_error (26); v_push_int (i_xml_cardinality (XEp_context, o_is_context_by_name), "position()"); } /// XPath \b starts-with function void xpath_processor::v_function_starts_with ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_arg_1, S_arg_2; if (u_nb_arg != 2) throw execution_error (27); S_arg_1 = erpp_arg [0] -> S_get_string (); S_arg_2 = erpp_arg [1] -> S_get_string (); v_push_bool (! strncmp (S_arg_1 . c_str (), S_arg_2 . c_str (), S_arg_2 . length ())); } /// XPath \b sttring-length function void xpath_processor::v_function_string_length ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_arg; if (u_nb_arg != 1) throw execution_error (28); S_arg = erpp_arg [0] -> S_get_string (); v_push_int (S_arg . length (), "string-length"); } /** XPath \b substring function\n Standard excerpt:\n The substring function returns the substring of the first argument starting at the position specified in the second argument with length specified in the third argument. For example, substring("12345",2,3) returns "234". If the third argument is not specified, it returns the substring starting at the position specified in the second argument and continuing to the end of the string. For example, substring("12345",2) returns "2345". */ void xpath_processor::v_function_substring ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_base, S_ret; int i_length, i_start; const char * cp_base; char * cp_work; if (u_nb_arg != 2 && u_nb_arg != 3) throw execution_error (29); S_base = erpp_arg [0] -> S_get_string (); i_start = erpp_arg [1] -> i_get_int (); if (u_nb_arg == 3) i_length = erpp_arg [2] -> i_get_int (); else i_length = 0; if (i_start < 1) S_ret = ""; else { i_start--; if (i_start >= (int) S_base . length ()) S_ret = ""; else { cp_base = S_base . c_str () + i_start; if (u_nb_arg == 2 || (int) strlen (cp_base) <= i_length) S_ret = cp_base; else { cp_work = new char [i_length + 1]; strncpy_s (cp_work, sizeof(cp_work), cp_base, i_length); cp_work [i_length] = 0; S_ret = cp_work; delete [] cp_work; } } } v_push_string (S_ret); } /// XPath \b sum function\n /// Standard exerpt :\n /// The sum function returns the sum, for each node in the argument node-set, /// of the result of converting the string-values of the node to a number. void xpath_processor::v_function_sum ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { int i_sum; double d_sum; unsigned u_node; node_set * nsp_set; bool o_out_double; if (u_nb_arg != 1) throw execution_error (30); i_sum = 0; d_sum = 0.0; o_out_double = false; if (erpp_arg [0] -> e_type != e_node_set) throw execution_error (31); nsp_set = erpp_arg [0] -> nsp_get_node_set (); assert (nsp_set); for (u_node = 0; u_node < nsp_set -> u_get_nb_node_in_set (); u_node++) { i_sum += nsp_set -> i_get_value (u_node); d_sum += nsp_set -> d_get_value (u_node); if (strchr (nsp_set -> S_get_value (u_node) . c_str (), '.')) o_out_double = true; } if (o_out_double) v_push_double (d_sum); else v_push_int (i_sum, "sum()"); } /// XPath \b text function void xpath_processor::v_function_text ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { const TiXmlElement * XEp_context; const TiXmlNode * XNp_child; TIXML_STRING S_res; if (u_nb_arg) throw execution_error (38); XEp_context = XEp_get_context (); if (! XEp_context) throw execution_error (39); XNp_child = XEp_context -> FirstChild (); while (XNp_child) { if (XNp_child -> Type () == TiXmlNode::TINYXML_TEXT) S_res += XNp_child -> Value (); XNp_child = XNp_child -> NextSibling (); } v_push_string (S_res); } /// XPath \b translate function\n /// Standard exerpt :\n ///The translate function returns the first argument string with occurrences of ///characters in the second argument string replaced by the character at the ///corresponding position in the third argument string. void xpath_processor::v_function_translate ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { TIXML_STRING S_translated; char* cp_translated = NULL; //pre-conditions if (u_nb_arg != 3) throw execution_error (40); TIXML_STRING S_translate_me = erpp_arg [0] -> S_get_string (); TIXML_STRING S_translation_table_lhs = erpp_arg [1] -> S_get_string (); TIXML_STRING S_translation_table_rhs = erpp_arg [2] -> S_get_string (); // Strings S_translation_table_lhs and S_translation_table_rhs represent // the translation table's left hand side and right hand side respectively // e.g. for "abc" "XYZ" ... we have the table // "a "X // b Y // c Z // " " // lhs rhs cp_translated = new char[ S_translate_me.length() + 1]; unsigned int u_write_at = 0 ; for(unsigned int u_read_at = 0; u_read_at < S_translate_me.length() ; u_read_at++) { //search in the translation scheme table unsigned int u_translation_rule_index = 0; for(; u_translation_rule_index < S_translation_table_lhs.size(); u_translation_rule_index++) { // this also ensures that if we have multiple translation rules for a single character then only the first one is selected if(S_translate_me[u_read_at] == S_translation_table_lhs [u_translation_rule_index]) { //translation rule found for current character break; } } if( u_translation_rule_index < S_translation_table_lhs.size()) { //the current character has a translation rule if(u_translation_rule_index < S_translation_table_rhs.size()) { cp_translated[u_write_at] = S_translation_table_rhs[u_translation_rule_index]; u_write_at++; } else { // else empty translation scheme // so current charater skipped } } else { //no translation scheme for current charater //thus copy it as it is in cp_translated cp_translated[u_write_at] = S_translate_me[u_read_at]; u_write_at++; } } cp_translated [u_write_at] = 0; S_translated = cp_translated; delete [] cp_translated; v_push_string(S_translated); } /// XPath \b true function void xpath_processor::v_function_true ( unsigned u_nb_arg, ///< Nb of arguments expression_result ** erpp_arg) ///< Argument list { if (u_nb_arg) throw execution_error (32); v_push_bool (true); } /** This function is for internal use : evaluation of an equality expression \n Standard excerpt :\n If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. \n If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true. \n If one object to be compared is a node-set and the other is a string, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the string-value of the node and the other string is true. \n If one object to be compared is a node-set and the other is a boolean, then the comparison will be true if and only if the result of performing the comparison on the boolean and on the result of converting the node-set to a boolean using the boolean function is true.\n When neither object to be compared is a node-set and the operator is = or !=, then the objects are compared by converting them to a common type as follows and then comparing them. - If at least one object to be compared is a boolean, then each object to be compared is converted to a boolean as if by applying the boolean function. - Otherwise, if at least one object to be compared is a number, then each object to be compared is converted to a number as if by applying the number function. - Otherwise, both objects to be compared are converted to strings as if by applying the string function. The = comparison will be true if and only if the objects are equal; the != comparison will be true if and only if the objects are not equal. - Numbers are compared for equality according to IEEE 754. - Two booleans are equal if either both are true or both are false. - Two strings are equal if and only if they consist of the same sequence of UCS characters. */ void xpath_processor::v_function_equal (expression_result ** erpp_arg) { bool o_res; assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); if (erpp_arg [0] -> e_type == e_node_set) if (erpp_arg [1] -> e_type == e_node_set) v_function_equal_2_node (erpp_arg [0], erpp_arg [1]); else v_function_equal_node_and_other (erpp_arg [0], erpp_arg [1]); else if (erpp_arg [1] -> e_type == e_node_set) v_function_equal_node_and_other (erpp_arg [1], erpp_arg [0]); else { // none are node sets : alternate decision table on bools, numbers and strings if (erpp_arg [0] -> e_type == e_bool || erpp_arg [1] -> e_type == e_bool) o_res = erpp_arg [0] -> o_get_bool () == erpp_arg [1] -> o_get_bool (); else if (erpp_arg [0] -> e_type == e_int || erpp_arg [1] -> e_type == e_int || erpp_arg [0] -> e_type == e_double || erpp_arg [1] -> e_type == e_double) o_res = erpp_arg [0] -> d_get_double () == erpp_arg [1] -> d_get_double (); else o_res = erpp_arg [0] -> S_get_string () == erpp_arg [1] -> S_get_string (); v_push_bool (o_res); } } /// This function is for internal use : evaluation of a non-equality expression void xpath_processor::v_function_not_equal (expression_result ** erpp_arg) { v_function_equal (erpp_arg); v_push_bool (! o_pop_bool ()); } /** Utility function that evaluates the equality between a node set and a non-node set\n Standard excerpt :\n If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true. \n If one object to be compared is a node-set and the other is a string, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the string-value of the node and the other string is true. \n If one object to be compared is a node-set and the other is a boolean, then the comparison will be true if and only if the result of performing the comparison on the boolean and on the result of converting the node-set to a boolean using the boolean function is true.\n */ void xpath_processor::v_function_equal_node_and_other (expression_result * erp_node_set, expression_result * erp_non) { bool o_res; node_set * nsp_ptr; unsigned u_node; o_res = false; nsp_ptr = erp_node_set -> nsp_get_node_set (); switch (erp_non -> e_type) { case e_bool : o_res = erp_non -> o_get_bool () == erp_node_set -> o_get_bool (); break; case e_int : case e_double : for (u_node = 0; u_node < nsp_ptr -> u_get_nb_node_in_set (); u_node++) if (nsp_ptr -> i_get_value (u_node) == erp_non -> i_get_int ()) o_res = true; break; case e_string : for (u_node = 0; u_node < nsp_ptr -> u_get_nb_node_in_set (); u_node++) if (nsp_ptr -> S_get_value (u_node) == erp_non -> S_get_string ()) o_res = true; break; default : // this case should have been excluded before our call assert (false); break; } v_push_bool (o_res); } /// \todo : Implement this function. We don't compare 2 node sets yet void xpath_processor::v_function_equal_2_node (expression_result * erp_node_set_, expression_result * erp_node_set_2) { throw error_not_yet (); } /// Union function void xpath_processor::v_function_union (node_set & ns_1, node_set & ns_2) { node_set ns_target; unsigned u_node; const TiXmlBase * XBp_base; ns_target = ns_1; for (u_node = 0; u_node < ns_2 . u_get_nb_node_in_set (); u_node++) { XBp_base = ns_2 . XBp_get_base_in_set (u_node); ns_target . v_add_base_in_set (XBp_base, ns_2 . o_is_attrib (u_node)); } v_push_node_set (& ns_target); } /// XPath <b> + </b> function void xpath_processor::v_function_plus (expression_result ** erpp_arg) { assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); if (erpp_arg [0] -> e_type == e_double || erpp_arg [1] -> e_type == e_double) v_push_double (erpp_arg [0] -> d_get_double () + erpp_arg [1] -> d_get_double ()); else v_push_int (erpp_arg [0] -> i_get_int () + erpp_arg [1] -> i_get_int (), "+"); } /// XPath <b> - </b> function void xpath_processor::v_function_minus (expression_result ** erpp_arg) { assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); if (erpp_arg [0] -> e_type == e_double || erpp_arg [1] -> e_type == e_double) v_push_double (erpp_arg [0] -> d_get_double () - erpp_arg [1] -> d_get_double ()); else v_push_int (erpp_arg [0] -> i_get_int () - erpp_arg [1] -> i_get_int (), "-"); } /// XPath \b or function void xpath_processor::v_function_or (expression_result ** erpp_arg) { assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); v_push_bool (erpp_arg [0] -> o_get_bool () || erpp_arg [1] -> o_get_bool ()); } /// XPath \b and function void xpath_processor::v_function_and (expression_result ** erpp_arg) { assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); v_push_bool (erpp_arg [0] -> o_get_bool () && erpp_arg [1] -> o_get_bool ()); } /// XPath relational comparison function void xpath_processor::v_function_relational (expression_result ** erpp_arg, unsigned u_sub) { bool o_res; assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); if (erpp_arg [0] -> e_type == e_double || erpp_arg [1] -> e_type == e_double) { double d_arg_1, d_arg_2; d_arg_1 = erpp_arg [0] -> d_get_double (); d_arg_2 = erpp_arg [1] -> d_get_double (); switch (u_sub) { case xpath_relational_expr_lt : o_res = d_arg_1 < d_arg_2; break; case xpath_relational_expr_gt : o_res = d_arg_1 > d_arg_2; break; case xpath_relational_expr_lte : o_res = d_arg_1 <= d_arg_2; break; case xpath_relational_expr_gte : o_res = d_arg_1 >= d_arg_2; break; default : assert (false); } } else { int i_arg_1, i_arg_2; i_arg_1 = erpp_arg [0] -> i_get_int (); i_arg_2 = erpp_arg [1] -> i_get_int (); switch (u_sub) { case xpath_relational_expr_lt : o_res = i_arg_1 < i_arg_2; break; case xpath_relational_expr_gt : o_res = i_arg_1 > i_arg_2; break; case xpath_relational_expr_lte : o_res = i_arg_1 <= i_arg_2; break; case xpath_relational_expr_gte : o_res = i_arg_1 >= i_arg_2; break; default : assert (false); } } v_push_bool (o_res); } /// XPath <b> * </b> function (arithmetic) void xpath_processor::v_function_mult (expression_result ** erpp_arg, unsigned u_sub) { assert (erpp_arg); assert (erpp_arg [0]); assert (erpp_arg [1]); if (erpp_arg [0] -> e_type == e_double || erpp_arg [1] -> e_type == e_double || u_sub == xpath_multiplicative_expr_div) { double d_arg_1, d_arg_2, d_res; d_arg_1 = erpp_arg [0] -> d_get_double (); d_arg_2 = erpp_arg [1] -> d_get_double (); switch (u_sub) { case xpath_multiplicative_expr_star : d_res = d_arg_1 * d_arg_2; break; case xpath_multiplicative_expr_div : if (fabs (d_arg_2) < 1.0e-6) throw execution_error (33); d_res = d_arg_1 / d_arg_2; break; case xpath_multiplicative_expr_mod : d_res = (int) d_arg_1 % (int) d_arg_2; break; default : assert (false); } v_push_double (d_res); } else { int i_arg_1, i_arg_2, i_res; i_arg_1 = erpp_arg [0] -> i_get_int (); i_arg_2 = erpp_arg [1] -> i_get_int (); switch (u_sub) { case xpath_multiplicative_expr_star : i_res = i_arg_1 * i_arg_2; break; case xpath_multiplicative_expr_mod : i_res = i_arg_1 % i_arg_2; break; default : assert (false); } v_push_int (i_res, "*"); } } /// This function, because it only operates on one argument retrieves it himself from the stack /// \n It computes the mathematical opposite void xpath_processor::v_function_opposite () { expression_result er_arg (XNp_base); er_arg = * xs_stack . erp_top (); xs_stack . v_pop (); switch (er_arg . e_type) { case e_double : v_push_double (-1.0 * er_arg . d_get_double ()); break; default : v_push_int (-1 * er_arg . i_get_int (), "unary -"); break; } } /// Set the current context node for predicate evaluations void xpath_processor::v_set_context ( const TiXmlElement * XEp_in, ///< Context node bool o_by_name) ///< true if the current node search is by name, false if it's a * { XEp_context = XEp_in; o_is_context_by_name = o_by_name; }
mit
cloudwu/skynet
lualib-src/lua-sharedata.c
9
16637
#define LUA_LIB #include <lua.h> #include <lauxlib.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "atomic.h" #define KEYTYPE_INTEGER 0 #define KEYTYPE_STRING 1 #define VALUETYPE_NIL 0 #define VALUETYPE_REAL 1 #define VALUETYPE_STRING 2 #define VALUETYPE_BOOLEAN 3 #define VALUETYPE_TABLE 4 #define VALUETYPE_INTEGER 5 struct table; union value { lua_Number n; lua_Integer d; struct table * tbl; int string; int boolean; }; struct node { union value v; int key; // integer key or index of string table int next; // next slot index uint32_t keyhash; uint8_t keytype; // key type must be integer or string uint8_t valuetype; // value type can be number/string/boolean/table uint8_t nocolliding; // 0 means colliding slot }; struct state { int dirty; ATOM_INT ref; struct table * root; }; struct table { int sizearray; int sizehash; uint8_t *arraytype; union value * array; struct node * hash; lua_State * L; }; struct context { lua_State * L; struct table * tbl; int string_index; }; struct ctrl { struct table * root; struct table * update; }; static int countsize(lua_State *L, int sizearray) { int n = 0; lua_pushnil(L); while (lua_next(L, 1) != 0) { int type = lua_type(L, -2); ++n; if (type == LUA_TNUMBER) { if (!lua_isinteger(L, -2)) { luaL_error(L, "Invalid key %f", lua_tonumber(L, -2)); } lua_Integer nkey = lua_tointeger(L, -2); if (nkey > 0 && nkey <= sizearray) { --n; } } else if (type != LUA_TSTRING && type != LUA_TTABLE) { luaL_error(L, "Invalid key type %s", lua_typename(L, type)); } lua_pop(L, 1); } return n; } static uint32_t calchash(const char * str, size_t l) { uint32_t h = (uint32_t)l; size_t l1; size_t step = (l >> 5) + 1; for (l1 = l; l1 >= step; l1 -= step) { h = h ^ ((h<<5) + (h>>2) + (uint8_t)(str[l1 - 1])); } return h; } static int stringindex(struct context *ctx, const char * str, size_t sz) { lua_State *L = ctx->L; lua_pushlstring(L, str, sz); lua_pushvalue(L, -1); lua_rawget(L, 1); int index; // stringmap(1) str index if (lua_isnil(L, -1)) { index = ++ctx->string_index; lua_pop(L, 1); lua_pushinteger(L, index); lua_rawset(L, 1); } else { index = lua_tointeger(L, -1); lua_pop(L, 2); } return index; } static int convtable(lua_State *L); static void setvalue(struct context * ctx, lua_State *L, int index, struct node *n) { int vt = lua_type(L, index); switch(vt) { case LUA_TNIL: n->valuetype = VALUETYPE_NIL; break; case LUA_TNUMBER: if (lua_isinteger(L, index)) { n->v.d = lua_tointeger(L, index); n->valuetype = VALUETYPE_INTEGER; } else { n->v.n = lua_tonumber(L, index); n->valuetype = VALUETYPE_REAL; } break; case LUA_TSTRING: { size_t sz = 0; const char * str = lua_tolstring(L, index, &sz); n->v.string = stringindex(ctx, str, sz); n->valuetype = VALUETYPE_STRING; break; } case LUA_TBOOLEAN: n->v.boolean = lua_toboolean(L, index); n->valuetype = VALUETYPE_BOOLEAN; break; case LUA_TTABLE: { struct table *tbl = ctx->tbl; ctx->tbl = (struct table *)malloc(sizeof(struct table)); if (ctx->tbl == NULL) { ctx->tbl = tbl; luaL_error(L, "memory error"); // never get here } memset(ctx->tbl, 0, sizeof(struct table)); int absidx = lua_absindex(L, index); lua_pushcfunction(L, convtable); lua_pushvalue(L, absidx); lua_pushlightuserdata(L, ctx); lua_call(L, 2, 0); n->v.tbl = ctx->tbl; n->valuetype = VALUETYPE_TABLE; ctx->tbl = tbl; break; } default: luaL_error(L, "Unsupport value type %s", lua_typename(L, vt)); break; } } static void setarray(struct context *ctx, lua_State *L, int index, int key) { struct node n; setvalue(ctx, L, index, &n); struct table *tbl = ctx->tbl; --key; // base 0 tbl->arraytype[key] = n.valuetype; tbl->array[key] = n.v; } static int ishashkey(struct context * ctx, lua_State *L, int index, int *key, uint32_t *keyhash, int *keytype) { int sizearray = ctx->tbl->sizearray; int kt = lua_type(L, index); if (kt == LUA_TNUMBER) { *key = lua_tointeger(L, index); if (*key > 0 && *key <= sizearray) { return 0; } *keyhash = (uint32_t)*key; *keytype = KEYTYPE_INTEGER; } else { size_t sz = 0; const char * s = lua_tolstring(L, index, &sz); *keyhash = calchash(s, sz); *key = stringindex(ctx, s, sz); *keytype = KEYTYPE_STRING; } return 1; } static void fillnocolliding(lua_State *L, struct context *ctx) { struct table * tbl = ctx->tbl; lua_pushnil(L); while (lua_next(L, 1) != 0) { int key; int keytype; uint32_t keyhash; if (!ishashkey(ctx, L, -2, &key, &keyhash, &keytype)) { setarray(ctx, L, -1, key); } else { struct node * n = &tbl->hash[keyhash % tbl->sizehash]; if (n->valuetype == VALUETYPE_NIL) { n->key = key; n->keytype = keytype; n->keyhash = keyhash; n->next = -1; n->nocolliding = 1; setvalue(ctx, L, -1, n); // set n->v , n->valuetype } } lua_pop(L,1); } } static void fillcolliding(lua_State *L, struct context *ctx) { struct table * tbl = ctx->tbl; int sizehash = tbl->sizehash; int emptyslot = 0; int i; lua_pushnil(L); while (lua_next(L, 1) != 0) { int key; int keytype; uint32_t keyhash; if (ishashkey(ctx, L, -2, &key, &keyhash, &keytype)) { struct node * mainpos = &tbl->hash[keyhash % tbl->sizehash]; if (!(mainpos->keytype == keytype && mainpos->key == key)) { // the key has not insert struct node * n = NULL; for (i=emptyslot;i<sizehash;i++) { if (tbl->hash[i].valuetype == VALUETYPE_NIL) { n = &tbl->hash[i]; emptyslot = i + 1; break; } } assert(n); n->next = mainpos->next; mainpos->next = n - tbl->hash; mainpos->nocolliding = 0; n->key = key; n->keytype = keytype; n->keyhash = keyhash; n->nocolliding = 0; setvalue(ctx, L, -1, n); // set n->v , n->valuetype } } lua_pop(L,1); } } // table need convert // struct context * ctx static int convtable(lua_State *L) { int i; struct context *ctx = lua_touserdata(L,2); struct table *tbl = ctx->tbl; tbl->L = ctx->L; int sizearray = lua_rawlen(L, 1); if (sizearray) { tbl->arraytype = (uint8_t *)malloc(sizearray * sizeof(uint8_t)); if (tbl->arraytype == NULL) { goto memerror; } for (i=0;i<sizearray;i++) { tbl->arraytype[i] = VALUETYPE_NIL; } tbl->array = (union value *)malloc(sizearray * sizeof(union value)); if (tbl->array == NULL) { goto memerror; } tbl->sizearray = sizearray; } int sizehash = countsize(L, sizearray); if (sizehash) { tbl->hash = (struct node *)malloc(sizehash * sizeof(struct node)); if (tbl->hash == NULL) { goto memerror; } for (i=0;i<sizehash;i++) { tbl->hash[i].valuetype = VALUETYPE_NIL; tbl->hash[i].nocolliding = 0; } tbl->sizehash = sizehash; fillnocolliding(L, ctx); fillcolliding(L, ctx); } else { int i; for (i=1;i<=sizearray;i++) { lua_rawgeti(L, 1, i); setarray(ctx, L, -1, i); lua_pop(L,1); } } return 0; memerror: return luaL_error(L, "memory error"); } static void delete_tbl(struct table *tbl) { int i; for (i=0;i<tbl->sizearray;i++) { if (tbl->arraytype[i] == VALUETYPE_TABLE) { delete_tbl(tbl->array[i].tbl); } } for (i=0;i<tbl->sizehash;i++) { if (tbl->hash[i].valuetype == VALUETYPE_TABLE) { delete_tbl(tbl->hash[i].v.tbl); } } free(tbl->arraytype); free(tbl->array); free(tbl->hash); free(tbl); } static int pconv(lua_State *L) { struct context *ctx = lua_touserdata(L,1); lua_State * pL = lua_touserdata(L, 2); int ret; lua_settop(L, 0); // init L (may throw memory error) // create a table for string map lua_newtable(L); lua_pushcfunction(pL, convtable); lua_pushvalue(pL,1); lua_pushlightuserdata(pL, ctx); ret = lua_pcall(pL, 2, 0, 0); if (ret != LUA_OK) { size_t sz = 0; const char * error = lua_tolstring(pL, -1, &sz); lua_pushlstring(L, error, sz); lua_error(L); // never get here } luaL_checkstack(L, ctx->string_index + 3, NULL); lua_settop(L,1); return 1; } static void convert_stringmap(struct context *ctx, struct table *tbl) { lua_State *L = ctx->L; lua_checkstack(L, ctx->string_index + LUA_MINSTACK); lua_settop(L, ctx->string_index + 1); lua_pushvalue(L, 1); struct state * s = lua_newuserdatauv(L, sizeof(*s), 1); s->dirty = 0; ATOM_INIT(&s->ref , 0); s->root = tbl; lua_replace(L, 1); lua_replace(L, -2); lua_pushnil(L); // ... stringmap nil while (lua_next(L, -2) != 0) { int idx = lua_tointeger(L, -1); lua_pop(L, 1); lua_pushvalue(L, -1); lua_replace(L, idx); } lua_pop(L, 1); lua_gc(L, LUA_GCCOLLECT, 0); } static int lnewconf(lua_State *L) { int ret; struct context ctx; struct table * tbl = NULL; luaL_checktype(L,1,LUA_TTABLE); ctx.L = luaL_newstate(); ctx.tbl = NULL; ctx.string_index = 1; // 1 reserved for dirty flag if (ctx.L == NULL) { lua_pushliteral(L, "memory error"); goto error; } tbl = (struct table *)malloc(sizeof(struct table)); if (tbl == NULL) { // lua_pushliteral may fail because of memory error, close first. lua_close(ctx.L); ctx.L = NULL; lua_pushliteral(L, "memory error"); goto error; } memset(tbl, 0, sizeof(struct table)); ctx.tbl = tbl; lua_pushcfunction(ctx.L, pconv); lua_pushlightuserdata(ctx.L , &ctx); lua_pushlightuserdata(ctx.L , L); ret = lua_pcall(ctx.L, 2, 1, 0); if (ret != LUA_OK) { size_t sz = 0; const char * error = lua_tolstring(ctx.L, -1, &sz); lua_pushlstring(L, error, sz); goto error; } convert_stringmap(&ctx, tbl); lua_pushlightuserdata(L, tbl); return 1; error: if (ctx.L) { lua_close(ctx.L); } if (tbl) { delete_tbl(tbl); } lua_error(L); return -1; } static struct table * get_table(lua_State *L, int index) { struct table *tbl = lua_touserdata(L,index); if (tbl == NULL) { luaL_error(L, "Need a conf object"); } return tbl; } static int ldeleteconf(lua_State *L) { struct table *tbl = get_table(L,1); lua_close(tbl->L); delete_tbl(tbl); return 0; } static void pushvalue(lua_State *L, lua_State *sL, uint8_t vt, union value *v) { switch(vt) { case VALUETYPE_REAL: lua_pushnumber(L, v->n); break; case VALUETYPE_INTEGER: lua_pushinteger(L, v->d); break; case VALUETYPE_STRING: { size_t sz = 0; const char *str = lua_tolstring(sL, v->string, &sz); lua_pushlstring(L, str, sz); break; } case VALUETYPE_BOOLEAN: lua_pushboolean(L, v->boolean); break; case VALUETYPE_TABLE: lua_pushlightuserdata(L, v->tbl); break; default: lua_pushnil(L); break; } } static struct node * lookup_key(struct table *tbl, uint32_t keyhash, int key, int keytype, const char *str, size_t sz) { if (tbl->sizehash == 0) return NULL; struct node *n = &tbl->hash[keyhash % tbl->sizehash]; if (keyhash != n->keyhash && n->nocolliding) return NULL; for (;;) { if (keyhash == n->keyhash) { if (n->keytype == KEYTYPE_INTEGER) { if (keytype == KEYTYPE_INTEGER && n->key == key) { return n; } } else { // n->keytype == KEYTYPE_STRING if (keytype == KEYTYPE_STRING) { size_t sz2 = 0; const char * str2 = lua_tolstring(tbl->L, n->key, &sz2); if (sz == sz2 && memcmp(str,str2,sz) == 0) { return n; } } } } if (n->next < 0) { return NULL; } n = &tbl->hash[n->next]; } } static int lindexconf(lua_State *L) { struct table *tbl = get_table(L,1); int kt = lua_type(L,2); uint32_t keyhash; int key = 0; int keytype; size_t sz = 0; const char * str = NULL; if (kt == LUA_TNUMBER) { if (!lua_isinteger(L, 2)) { return luaL_error(L, "Invalid key %f", lua_tonumber(L, 2)); } key = (int)lua_tointeger(L, 2); if (key > 0 && key <= tbl->sizearray) { --key; pushvalue(L, tbl->L, tbl->arraytype[key], &tbl->array[key]); return 1; } keytype = KEYTYPE_INTEGER; keyhash = (uint32_t)key; } else { str = luaL_checklstring(L, 2, &sz); keyhash = calchash(str, sz); keytype = KEYTYPE_STRING; } struct node *n = lookup_key(tbl, keyhash, key, keytype, str, sz); if (n) { pushvalue(L, tbl->L, n->valuetype, &n->v); return 1; } else { return 0; } } static void pushkey(lua_State *L, lua_State *sL, struct node *n) { if (n->keytype == KEYTYPE_INTEGER) { lua_pushinteger(L, n->key); } else { size_t sz = 0; const char * str = lua_tolstring(sL, n->key, &sz); lua_pushlstring(L, str, sz); } } static int pushfirsthash(lua_State *L, struct table * tbl) { if (tbl->sizehash) { pushkey(L, tbl->L, &tbl->hash[0]); return 1; } else { return 0; } } static int lnextkey(lua_State *L) { struct table *tbl = get_table(L,1); if (lua_isnoneornil(L,2)) { if (tbl->sizearray > 0) { int i; for (i=0;i<tbl->sizearray;i++) { if (tbl->arraytype[i] != VALUETYPE_NIL) { lua_pushinteger(L, i+1); return 1; } } } return pushfirsthash(L, tbl); } int kt = lua_type(L,2); uint32_t keyhash; int key = 0; int keytype; size_t sz=0; const char *str = NULL; int sizearray = tbl->sizearray; if (kt == LUA_TNUMBER) { if (!lua_isinteger(L, 2)) { return 0; } key = (int)lua_tointeger(L, 2); if (key > 0 && key <= sizearray) { lua_Integer i; for (i=key;i<sizearray;i++) { if (tbl->arraytype[i] != VALUETYPE_NIL) { lua_pushinteger(L, i+1); return 1; } } return pushfirsthash(L, tbl); } keyhash = (uint32_t)key; keytype = KEYTYPE_INTEGER; } else { str = luaL_checklstring(L, 2, &sz); keyhash = calchash(str, sz); keytype = KEYTYPE_STRING; } struct node *n = lookup_key(tbl, keyhash, key, keytype, str, sz); if (n) { ++n; int index = n-tbl->hash; if (index == tbl->sizehash) { return 0; } pushkey(L, tbl->L, n); return 1; } else { return 0; } } static int llen(lua_State *L) { struct table *tbl = get_table(L,1); lua_pushinteger(L, tbl->sizearray); return 1; } static int lhashlen(lua_State *L) { struct table *tbl = get_table(L,1); lua_pushinteger(L, tbl->sizehash); return 1; } static int releaseobj(lua_State *L) { struct ctrl *c = lua_touserdata(L, 1); struct table *tbl = c->root; struct state *s = lua_touserdata(tbl->L, 1); ATOM_FDEC(&s->ref); c->root = NULL; c->update = NULL; return 0; } static int lboxconf(lua_State *L) { struct table * tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); ATOM_FINC(&s->ref); struct ctrl * c = lua_newuserdatauv(L, sizeof(*c), 1); c->root = tbl; c->update = NULL; if (luaL_newmetatable(L, "confctrl")) { lua_pushcfunction(L, releaseobj); lua_setfield(L, -2, "__gc"); } lua_setmetatable(L, -2); return 1; } static int lmarkdirty(lua_State *L) { struct table *tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); s->dirty = 1; return 0; } static int lisdirty(lua_State *L) { struct table *tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); int d = s->dirty; lua_pushboolean(L, d); return 1; } static int lgetref(lua_State *L) { struct table *tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); lua_pushinteger(L , ATOM_LOAD(&s->ref)); return 1; } static int lincref(lua_State *L) { struct table *tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); int ref = ATOM_FINC(&s->ref)+1; lua_pushinteger(L , ref); return 1; } static int ldecref(lua_State *L) { struct table *tbl = get_table(L,1); struct state * s = lua_touserdata(tbl->L, 1); int ref = ATOM_FDEC(&s->ref)-1; lua_pushinteger(L , ref); return 1; } static int lneedupdate(lua_State *L) { struct ctrl * c = lua_touserdata(L, 1); if (c->update) { lua_pushlightuserdata(L, c->update); lua_getiuservalue(L, 1, 1); return 2; } return 0; } static int lupdate(lua_State *L) { luaL_checktype(L, 1, LUA_TUSERDATA); luaL_checktype(L, 2, LUA_TLIGHTUSERDATA); luaL_checktype(L, 3, LUA_TTABLE); struct ctrl * c= lua_touserdata(L, 1); struct table *n = lua_touserdata(L, 2); if (c->root == n) { return luaL_error(L, "You should update a new object"); } lua_settop(L, 3); lua_setiuservalue(L, 1, 1); c->update = n; return 0; } LUAMOD_API int luaopen_skynet_sharedata_core(lua_State *L) { luaL_Reg l[] = { // used by host { "new", lnewconf }, { "delete", ldeleteconf }, { "markdirty", lmarkdirty }, { "getref", lgetref }, { "incref", lincref }, { "decref", ldecref }, // used by client { "box", lboxconf }, { "index", lindexconf }, { "nextkey", lnextkey }, { "len", llen }, { "hashlen", lhashlen }, { "isdirty", lisdirty }, { "needupdate", lneedupdate }, { "update", lupdate }, { NULL, NULL }, }; luaL_checkversion(L); luaL_newlib(L, l); return 1; }
mit
JTriggerFish/protoplug
Frameworks/JuceModules/juce_core/threads/juce_ThreadPool.cpp
10
10041
/* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ class ThreadPool::ThreadPoolThread : public Thread { public: ThreadPoolThread (ThreadPool& p) : Thread ("Pool"), currentJob (nullptr), pool (p) { } void run() override { while (! threadShouldExit()) if (! pool.runNextJob (*this)) wait (500); } ThreadPoolJob* volatile currentJob; ThreadPool& pool; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread) }; //============================================================================== ThreadPoolJob::ThreadPoolJob (const String& name) : jobName (name), pool (nullptr), shouldStop (false), isActive (false), shouldBeDeleted (false) { } ThreadPoolJob::~ThreadPoolJob() { // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob() // to remove it first! jassert (pool == nullptr || ! pool->contains (this)); } String ThreadPoolJob::getJobName() const { return jobName; } void ThreadPoolJob::setJobName (const String& newName) { jobName = newName; } void ThreadPoolJob::signalJobShouldExit() { shouldStop = true; } ThreadPoolJob* ThreadPoolJob::getCurrentThreadPoolJob() { if (ThreadPool::ThreadPoolThread* t = dynamic_cast<ThreadPool::ThreadPoolThread*> (Thread::getCurrentThread())) return t->currentJob; return nullptr; } //============================================================================== ThreadPool::ThreadPool (const int numThreads) { jassert (numThreads > 0); // not much point having a pool without any threads! createThreads (numThreads); } ThreadPool::ThreadPool() { createThreads (SystemStats::getNumCpus()); } ThreadPool::~ThreadPool() { removeAllJobs (true, 5000); stopThreads(); } void ThreadPool::createThreads (int numThreads) { for (int i = jmax (1, numThreads); --i >= 0;) threads.add (new ThreadPoolThread (*this)); for (int i = threads.size(); --i >= 0;) threads.getUnchecked(i)->startThread(); } void ThreadPool::stopThreads() { for (int i = threads.size(); --i >= 0;) threads.getUnchecked(i)->signalThreadShouldExit(); for (int i = threads.size(); --i >= 0;) threads.getUnchecked(i)->stopThread (500); } void ThreadPool::addJob (ThreadPoolJob* const job, const bool deleteJobWhenFinished) { jassert (job != nullptr); jassert (job->pool == nullptr); if (job->pool == nullptr) { job->pool = this; job->shouldStop = false; job->isActive = false; job->shouldBeDeleted = deleteJobWhenFinished; { const ScopedLock sl (lock); jobs.add (job); } for (int i = threads.size(); --i >= 0;) threads.getUnchecked(i)->notify(); } } int ThreadPool::getNumJobs() const { return jobs.size(); } ThreadPoolJob* ThreadPool::getJob (const int index) const { const ScopedLock sl (lock); return jobs [index]; } bool ThreadPool::contains (const ThreadPoolJob* const job) const { const ScopedLock sl (lock); return jobs.contains (const_cast <ThreadPoolJob*> (job)); } bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const { const ScopedLock sl (lock); return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive; } bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job, const int timeOutMs) const { if (job != nullptr) { const uint32 start = Time::getMillisecondCounter(); while (contains (job)) { if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs) return false; jobFinishedSignal.wait (2); } } return true; } bool ThreadPool::removeJob (ThreadPoolJob* const job, const bool interruptIfRunning, const int timeOutMs) { bool dontWait = true; OwnedArray<ThreadPoolJob> deletionList; if (job != nullptr) { const ScopedLock sl (lock); if (jobs.contains (job)) { if (job->isActive) { if (interruptIfRunning) job->signalJobShouldExit(); dontWait = false; } else { jobs.removeFirstMatchingValue (job); addToDeleteList (deletionList, job); } } } return dontWait || waitForJobToFinish (job, timeOutMs); } bool ThreadPool::removeAllJobs (const bool interruptRunningJobs, const int timeOutMs, ThreadPool::JobSelector* const selectedJobsToRemove) { Array <ThreadPoolJob*> jobsToWaitFor; { OwnedArray<ThreadPoolJob> deletionList; { const ScopedLock sl (lock); for (int i = jobs.size(); --i >= 0;) { ThreadPoolJob* const job = jobs.getUnchecked(i); if (selectedJobsToRemove == nullptr || selectedJobsToRemove->isJobSuitable (job)) { if (job->isActive) { jobsToWaitFor.add (job); if (interruptRunningJobs) job->signalJobShouldExit(); } else { jobs.remove (i); addToDeleteList (deletionList, job); } } } } } const uint32 start = Time::getMillisecondCounter(); for (;;) { for (int i = jobsToWaitFor.size(); --i >= 0;) { ThreadPoolJob* const job = jobsToWaitFor.getUnchecked (i); if (! isJobRunning (job)) jobsToWaitFor.remove (i); } if (jobsToWaitFor.size() == 0) break; if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + (uint32) timeOutMs) return false; jobFinishedSignal.wait (20); } return true; } StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const { StringArray s; const ScopedLock sl (lock); for (int i = 0; i < jobs.size(); ++i) { const ThreadPoolJob* const job = jobs.getUnchecked(i); if (job->isActive || ! onlyReturnActiveJobs) s.add (job->getJobName()); } return s; } bool ThreadPool::setThreadPriorities (const int newPriority) { bool ok = true; for (int i = threads.size(); --i >= 0;) if (! threads.getUnchecked(i)->setPriority (newPriority)) ok = false; return ok; } ThreadPoolJob* ThreadPool::pickNextJobToRun() { OwnedArray<ThreadPoolJob> deletionList; { const ScopedLock sl (lock); for (int i = 0; i < jobs.size(); ++i) { ThreadPoolJob* job = jobs[i]; if (job != nullptr && ! job->isActive) { if (job->shouldStop) { jobs.remove (i); addToDeleteList (deletionList, job); --i; continue; } job->isActive = true; return job; } } } return nullptr; } bool ThreadPool::runNextJob (ThreadPoolThread& thread) { if (ThreadPoolJob* const job = pickNextJobToRun()) { ThreadPoolJob::JobStatus result = ThreadPoolJob::jobHasFinished; thread.currentJob = job; JUCE_TRY { result = job->runJob(); } JUCE_CATCH_ALL_ASSERT thread.currentJob = nullptr; OwnedArray<ThreadPoolJob> deletionList; { const ScopedLock sl (lock); if (jobs.contains (job)) { job->isActive = false; if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop) { jobs.removeFirstMatchingValue (job); addToDeleteList (deletionList, job); jobFinishedSignal.signal(); } else { // move the job to the end of the queue if it wants another go jobs.move (jobs.indexOf (job), -1); } } } return true; } return false; } void ThreadPool::addToDeleteList (OwnedArray<ThreadPoolJob>& deletionList, ThreadPoolJob* const job) const { job->shouldStop = true; job->pool = nullptr; if (job->shouldBeDeleted) deletionList.add (job); }
mit
james54068/CAN_demo
Libraries/STM32_USB_HOST_Library/Class/HID/src/usbh_hid_core.c
11
19444
/** ****************************************************************************** * @file usbh_hid_core.c * @author MCD Application Team * @version V2.1.0 * @date 19-March-2012 * @brief This file is the HID Layer Handlers for USB Host HID class. * * @verbatim * * =================================================================== * HID Class Description * =================================================================== * This module manages the MSC class V1.11 following the "Device Class Definition * for Human Interface Devices (HID) Version 1.11 Jun 27, 2001". * This driver implements the following aspects of the specification: * - The Boot Interface Subclass * - The Mouse and Keyboard protocols * * @endverbatim * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "usbh_hid_core.h" #include "usbh_hid_mouse.h" #include "usbh_hid_keybd.h" /** @addtogroup USBH_LIB * @{ */ /** @addtogroup USBH_CLASS * @{ */ /** @addtogroup USBH_HID_CLASS * @{ */ /** @defgroup USBH_HID_CORE * @brief This file includes HID Layer Handlers for USB Host HID class. * @{ */ /** @defgroup USBH_HID_CORE_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup USBH_HID_CORE_Private_Defines * @{ */ /** * @} */ /** @defgroup USBH_HID_CORE_Private_Macros * @{ */ /** * @} */ /** @defgroup USBH_HID_CORE_Private_Variables * @{ */ #ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma data_alignment=4 #endif #endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */ __ALIGN_BEGIN HID_Machine_TypeDef HID_Machine __ALIGN_END ; #ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma data_alignment=4 #endif #endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */ __ALIGN_BEGIN HID_Report_TypeDef HID_Report __ALIGN_END ; #ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma data_alignment=4 #endif #endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */ __ALIGN_BEGIN USB_Setup_TypeDef HID_Setup __ALIGN_END ; #ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED #if defined ( __ICCARM__ ) /*!< IAR Compiler */ #pragma data_alignment=4 #endif #endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */ __ALIGN_BEGIN USBH_HIDDesc_TypeDef HID_Desc __ALIGN_END ; __IO uint8_t start_toggle = 0; /** * @} */ /** @defgroup USBH_HID_CORE_Private_FunctionPrototypes * @{ */ static USBH_Status USBH_HID_InterfaceInit (USB_OTG_CORE_HANDLE *pdev , void *phost); static void USBH_ParseHIDDesc (USBH_HIDDesc_TypeDef *desc, uint8_t *buf); static void USBH_HID_InterfaceDeInit (USB_OTG_CORE_HANDLE *pdev , void *phost); static USBH_Status USBH_HID_Handle(USB_OTG_CORE_HANDLE *pdev , void *phost); static USBH_Status USBH_HID_ClassRequest(USB_OTG_CORE_HANDLE *pdev , void *phost); static USBH_Status USBH_Get_HID_ReportDescriptor (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint16_t length); static USBH_Status USBH_Get_HID_Descriptor (USB_OTG_CORE_HANDLE *pdev,\ USBH_HOST *phost, uint16_t length); static USBH_Status USBH_Set_Idle (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint8_t duration, uint8_t reportId); static USBH_Status USBH_Set_Protocol (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint8_t protocol); USBH_Class_cb_TypeDef HID_cb = { USBH_HID_InterfaceInit, USBH_HID_InterfaceDeInit, USBH_HID_ClassRequest, USBH_HID_Handle }; /** * @} */ /** @defgroup USBH_HID_CORE_Private_Functions * @{ */ /** * @brief USBH_HID_InterfaceInit * The function init the HID class. * @param pdev: Selected device * @param hdev: Selected device property * @retval USBH_Status :Response for USB HID driver intialization */ static USBH_Status USBH_HID_InterfaceInit ( USB_OTG_CORE_HANDLE *pdev, void *phost) { uint8_t maxEP; USBH_HOST *pphost = phost; uint8_t num =0; USBH_Status status = USBH_BUSY ; HID_Machine.state = HID_ERROR; if(pphost->device_prop.Itf_Desc[0].bInterfaceSubClass == HID_BOOT_CODE) { /*Decode Bootclass Protocl: Mouse or Keyboard*/ if(pphost->device_prop.Itf_Desc[0].bInterfaceProtocol == HID_KEYBRD_BOOT_CODE) { HID_Machine.cb = &HID_KEYBRD_cb; } else if(pphost->device_prop.Itf_Desc[0].bInterfaceProtocol == HID_MOUSE_BOOT_CODE) { HID_Machine.cb = &HID_MOUSE_cb; } HID_Machine.state = HID_IDLE; HID_Machine.ctl_state = HID_REQ_IDLE; HID_Machine.ep_addr = pphost->device_prop.Ep_Desc[0][0].bEndpointAddress; HID_Machine.length = pphost->device_prop.Ep_Desc[0][0].wMaxPacketSize; HID_Machine.poll = pphost->device_prop.Ep_Desc[0][0].bInterval ; if (HID_Machine.poll < HID_MIN_POLL) { HID_Machine.poll = HID_MIN_POLL; } /* Check fo available number of endpoints */ /* Find the number of EPs in the Interface Descriptor */ /* Choose the lower number in order not to overrun the buffer allocated */ maxEP = ( (pphost->device_prop.Itf_Desc[0].bNumEndpoints <= USBH_MAX_NUM_ENDPOINTS) ? pphost->device_prop.Itf_Desc[0].bNumEndpoints : USBH_MAX_NUM_ENDPOINTS); /* Decode endpoint IN and OUT address from interface descriptor */ for (num=0; num < maxEP; num++) { if(pphost->device_prop.Ep_Desc[0][num].bEndpointAddress & 0x80) { HID_Machine.HIDIntInEp = (pphost->device_prop.Ep_Desc[0][num].bEndpointAddress); HID_Machine.hc_num_in =\ USBH_Alloc_Channel(pdev, pphost->device_prop.Ep_Desc[0][num].bEndpointAddress); /* Open channel for IN endpoint */ USBH_Open_Channel (pdev, HID_Machine.hc_num_in, pphost->device_prop.address, pphost->device_prop.speed, EP_TYPE_INTR, HID_Machine.length); } else { HID_Machine.HIDIntOutEp = (pphost->device_prop.Ep_Desc[0][num].bEndpointAddress); HID_Machine.hc_num_out =\ USBH_Alloc_Channel(pdev, pphost->device_prop.Ep_Desc[0][num].bEndpointAddress); /* Open channel for OUT endpoint */ USBH_Open_Channel (pdev, HID_Machine.hc_num_out, pphost->device_prop.address, pphost->device_prop.speed, EP_TYPE_INTR, HID_Machine.length); } } start_toggle =0; status = USBH_OK; } else { pphost->usr_cb->DeviceNotSupported(); } return status; } /** * @brief USBH_HID_InterfaceDeInit * The function DeInit the Host Channels used for the HID class. * @param pdev: Selected device * @param hdev: Selected device property * @retval None */ void USBH_HID_InterfaceDeInit ( USB_OTG_CORE_HANDLE *pdev, void *phost) { //USBH_HOST *pphost = phost; if(HID_Machine.hc_num_in != 0x00) { USB_OTG_HC_Halt(pdev, HID_Machine.hc_num_in); USBH_Free_Channel (pdev, HID_Machine.hc_num_in); HID_Machine.hc_num_in = 0; /* Reset the Channel as Free */ } if(HID_Machine.hc_num_out != 0x00) { USB_OTG_HC_Halt(pdev, HID_Machine.hc_num_out); USBH_Free_Channel (pdev, HID_Machine.hc_num_out); HID_Machine.hc_num_out = 0; /* Reset the Channel as Free */ } start_toggle = 0; } /** * @brief USBH_HID_ClassRequest * The function is responsible for handling HID Class requests * for HID class. * @param pdev: Selected device * @param hdev: Selected device property * @retval USBH_Status :Response for USB Set Protocol request */ static USBH_Status USBH_HID_ClassRequest(USB_OTG_CORE_HANDLE *pdev , void *phost) { USBH_HOST *pphost = phost; USBH_Status status = USBH_BUSY; USBH_Status classReqStatus = USBH_BUSY; /* Switch HID state machine */ switch (HID_Machine.ctl_state) { case HID_IDLE: case HID_REQ_GET_HID_DESC: /* Get HID Desc */ if (USBH_Get_HID_Descriptor (pdev, pphost, USB_HID_DESC_SIZE)== USBH_OK) { USBH_ParseHIDDesc(&HID_Desc, pdev->host.Rx_Buffer); HID_Machine.ctl_state = HID_REQ_GET_REPORT_DESC; } break; case HID_REQ_GET_REPORT_DESC: /* Get Report Desc */ if (USBH_Get_HID_ReportDescriptor(pdev , pphost, HID_Desc.wItemLength) == USBH_OK) { HID_Machine.ctl_state = HID_REQ_SET_IDLE; } break; case HID_REQ_SET_IDLE: classReqStatus = USBH_Set_Idle (pdev, pphost, 0, 0); /* set Idle */ if (classReqStatus == USBH_OK) { HID_Machine.ctl_state = HID_REQ_SET_PROTOCOL; } else if(classReqStatus == USBH_NOT_SUPPORTED) { HID_Machine.ctl_state = HID_REQ_SET_PROTOCOL; } break; case HID_REQ_SET_PROTOCOL: /* set protocol */ if (USBH_Set_Protocol (pdev ,pphost, 0) == USBH_OK) { HID_Machine.ctl_state = HID_REQ_IDLE; /* all requests performed*/ status = USBH_OK; } break; default: break; } return status; } /** * @brief USBH_HID_Handle * The function is for managing state machine for HID data transfers * @param pdev: Selected device * @param hdev: Selected device property * @retval USBH_Status */ static USBH_Status USBH_HID_Handle(USB_OTG_CORE_HANDLE *pdev , void *phost) { USBH_HOST *pphost = phost; USBH_Status status = USBH_OK; switch (HID_Machine.state) { case HID_IDLE: HID_Machine.cb->Init(); HID_Machine.state = HID_SYNC; case HID_SYNC: /* Sync with start of Even Frame */ if(USB_OTG_IsEvenFrame(pdev) == TRUE) { HID_Machine.state = HID_GET_DATA; } break; case HID_GET_DATA: USBH_InterruptReceiveData(pdev, HID_Machine.buff, HID_Machine.length, HID_Machine.hc_num_in); start_toggle = 1; HID_Machine.state = HID_POLL; HID_Machine.timer = HCD_GetCurrentFrame(pdev); break; case HID_POLL: if(( HCD_GetCurrentFrame(pdev) - HID_Machine.timer) >= HID_Machine.poll) { HID_Machine.state = HID_GET_DATA; } else if(HCD_GetURB_State(pdev , HID_Machine.hc_num_in) == URB_DONE) { if(start_toggle == 1) /* handle data once */ { start_toggle = 0; HID_Machine.cb->Decode(HID_Machine.buff); } } else if(HCD_GetURB_State(pdev, HID_Machine.hc_num_in) == URB_STALL) /* IN Endpoint Stalled */ { /* Issue Clear Feature on interrupt IN endpoint */ if( (USBH_ClrFeature(pdev, pphost, HID_Machine.ep_addr, HID_Machine.hc_num_in)) == USBH_OK) { /* Change state to issue next IN token */ HID_Machine.state = HID_GET_DATA; } } break; default: break; } return status; } /** * @brief USBH_Get_HID_ReportDescriptor * Issue report Descriptor command to the device. Once the response * received, parse the report descriptor and update the status. * @param pdev : Selected device * @param Length : HID Report Descriptor Length * @retval USBH_Status : Response for USB HID Get Report Descriptor Request */ static USBH_Status USBH_Get_HID_ReportDescriptor (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint16_t length) { USBH_Status status; status = USBH_GetDescriptor(pdev, phost, USB_REQ_RECIPIENT_INTERFACE | USB_REQ_TYPE_STANDARD, USB_DESC_HID_REPORT, pdev->host.Rx_Buffer, length); /* HID report descriptor is available in pdev->host.Rx_Buffer. In case of USB Boot Mode devices for In report handling , HID report descriptor parsing is not required. In case, for supporting Non-Boot Protocol devices and output reports, user may parse the report descriptor*/ return status; } /** * @brief USBH_Get_HID_Descriptor * Issue HID Descriptor command to the device. Once the response * received, parse the report descriptor and update the status. * @param pdev : Selected device * @param Length : HID Descriptor Length * @retval USBH_Status : Response for USB HID Get Report Descriptor Request */ static USBH_Status USBH_Get_HID_Descriptor (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint16_t length) { USBH_Status status; status = USBH_GetDescriptor(pdev, phost, USB_REQ_RECIPIENT_INTERFACE | USB_REQ_TYPE_STANDARD, USB_DESC_HID, pdev->host.Rx_Buffer, length); return status; } /** * @brief USBH_Set_Idle * Set Idle State. * @param pdev: Selected device * @param duration: Duration for HID Idle request * @param reportID : Targetted report ID for Set Idle request * @retval USBH_Status : Response for USB Set Idle request */ static USBH_Status USBH_Set_Idle (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint8_t duration, uint8_t reportId) { phost->Control.setup.b.bmRequestType = USB_H2D | USB_REQ_RECIPIENT_INTERFACE |\ USB_REQ_TYPE_CLASS; phost->Control.setup.b.bRequest = USB_HID_SET_IDLE; phost->Control.setup.b.wValue.w = (duration << 8 ) | reportId; phost->Control.setup.b.wIndex.w = 0; phost->Control.setup.b.wLength.w = 0; return USBH_CtlReq(pdev, phost, 0 , 0 ); } /** * @brief USBH_Set_Report * Issues Set Report * @param pdev: Selected device * @param reportType : Report type to be sent * @param reportID : Targetted report ID for Set Report request * @param reportLen : Length of data report to be send * @param reportBuff : Report Buffer * @retval USBH_Status : Response for USB Set Idle request */ USBH_Status USBH_Set_Report (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint8_t reportType, uint8_t reportId, uint8_t reportLen, uint8_t* reportBuff) { phost->Control.setup.b.bmRequestType = USB_H2D | USB_REQ_RECIPIENT_INTERFACE |\ USB_REQ_TYPE_CLASS; phost->Control.setup.b.bRequest = USB_HID_SET_REPORT; phost->Control.setup.b.wValue.w = (reportType << 8 ) | reportId; phost->Control.setup.b.wIndex.w = 0; phost->Control.setup.b.wLength.w = reportLen; return USBH_CtlReq(pdev, phost, reportBuff , reportLen ); } /** * @brief USBH_Set_Protocol * Set protocol State. * @param pdev: Selected device * @param protocol : Set Protocol for HID : boot/report protocol * @retval USBH_Status : Response for USB Set Protocol request */ static USBH_Status USBH_Set_Protocol(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost, uint8_t protocol) { phost->Control.setup.b.bmRequestType = USB_H2D | USB_REQ_RECIPIENT_INTERFACE |\ USB_REQ_TYPE_CLASS; phost->Control.setup.b.bRequest = USB_HID_SET_PROTOCOL; if(protocol != 0) { /* Boot Protocol */ phost->Control.setup.b.wValue.w = 0; } else { /*Report Protocol*/ phost->Control.setup.b.wValue.w = 1; } phost->Control.setup.b.wIndex.w = 0; phost->Control.setup.b.wLength.w = 0; return USBH_CtlReq(pdev, phost, 0 , 0 ); } /** * @brief USBH_ParseHIDDesc * This function Parse the HID descriptor * @param buf: Buffer where the source descriptor is available * @retval None */ static void USBH_ParseHIDDesc (USBH_HIDDesc_TypeDef *desc, uint8_t *buf) { desc->bLength = *(uint8_t *) (buf + 0); desc->bDescriptorType = *(uint8_t *) (buf + 1); desc->bcdHID = LE16 (buf + 2); desc->bCountryCode = *(uint8_t *) (buf + 4); desc->bNumDescriptors = *(uint8_t *) (buf + 5); desc->bReportDescriptorType = *(uint8_t *) (buf + 6); desc->wItemLength = LE16 (buf + 7); } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mit
firstval/micropython
cc3200/fatfs/src/drivers/sd_diskio.c
12
14997
//***************************************************************************** // sd_diskio.c // // Low level SD Card access hookup for FatFS // // Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //***************************************************************************** #include <stdbool.h> #include "py/mpconfig.h" #include MICROPY_HAL_H #include "hw_types.h" #include "hw_memmap.h" #include "hw_ints.h" #include "rom.h" #include "rom_map.h" #include "diskio.h" #include "sd_diskio.h" #include "sdhost.h" #include "pin.h" #include "prcm.h" #include "stdcmd.h" #include "utils.h" //***************************************************************************** // Macros //***************************************************************************** #define DISKIO_RETRY_TIMEOUT 0xFFFFFFFF #define CARD_TYPE_UNKNOWN 0 #define CARD_TYPE_MMC 1 #define CARD_TYPE_SDCARD 2 #define CARD_CAP_CLASS_SDSC 0 #define CARD_CAP_CLASS_SDHC 1 #define CARD_VERSION_1 0 #define CARD_VERSION_2 1 //***************************************************************************** // Disk Info for attached disk //***************************************************************************** DiskInfo_t sd_disk_info = {CARD_TYPE_UNKNOWN, CARD_VERSION_1, CARD_CAP_CLASS_SDSC, 0, 0, STA_NOINIT, 0}; //***************************************************************************** // //! Send Command to card //! //! \param ulCmd is the command to be send //! \paran ulArg is the command argument //! //! This function sends command to attached card and check the response status //! if any. //! //! \return Returns 0 on success, 1 otherwise // //***************************************************************************** static unsigned int CardSendCmd (unsigned int ulCmd, unsigned int ulArg) { unsigned long ulStatus; // Clear the interrupt status MAP_SDHostIntClear(SDHOST_BASE,0xFFFFFFFF); // Send command MAP_SDHostCmdSend(SDHOST_BASE,ulCmd,ulArg); // Wait for command complete or error do { ulStatus = MAP_SDHostIntStatus(SDHOST_BASE); ulStatus = (ulStatus & (SDHOST_INT_CC | SDHOST_INT_ERRI)); } while (!ulStatus); // Check error status if (ulStatus & SDHOST_INT_ERRI) { // Reset the command line MAP_SDHostCmdReset(SDHOST_BASE); return 1; } else { return 0; } } //***************************************************************************** // //! Get the capacity of specified card //! //! \param ulRCA is the Relative Card Address (RCA) //! //! This function gets the capacity of card addressed by \e ulRCA paramaeter. //! //! \return Returns 0 on success, 1 otherwise. // //***************************************************************************** static unsigned int CardCapacityGet(DiskInfo_t *psDiskInfo) { unsigned long ulRet; unsigned long ulResp[4]; unsigned long ulBlockSize; unsigned long ulBlockCount; unsigned long ulCSizeMult; unsigned long ulCSize; // Read the CSD register ulRet = CardSendCmd(CMD_SEND_CSD, (psDiskInfo->usRCA << 16)); if(ulRet == 0) { // Read the response MAP_SDHostRespGet(SDHOST_BASE,ulResp); // 136 bit CSD register is read into an array of 4 words. // ulResp[0] = CSD[31:0] // ulResp[1] = CSD[63:32] // ulResp[2] = CSD[95:64] // ulResp[3] = CSD[127:96] if(ulResp[3] >> 30) { ulBlockSize = SD_SECTOR_SIZE * 1024; ulBlockCount = (ulResp[1] >> 16 | ((ulResp[2] & 0x3F) << 16)) + 1; } else { ulBlockSize = 1 << ((ulResp[2] >> 16) & 0xF); ulCSizeMult = ((ulResp[1] >> 15) & 0x7); ulCSize = ((ulResp[1] >> 30) | (ulResp[2] & 0x3FF) << 2); ulBlockCount = (ulCSize + 1) * (1 << (ulCSizeMult + 2)); } // Calculate the card capacity in bytes psDiskInfo->ulBlockSize = ulBlockSize; psDiskInfo->ulNofBlock = ulBlockCount; } return ulRet; } //***************************************************************************** // //! Select a card for reading or writing //! //! \param Card is the pointer to card attribute structure. //! //! This function selects a card for reading or writing using its RCA from //! \e Card parameter. //! //! \return Returns 0 success, 1 otherwise. // //***************************************************************************** static unsigned int CardSelect (DiskInfo_t *sDiskInfo) { unsigned long ulRCA; unsigned long ulRet; ulRCA = sDiskInfo->usRCA; // Send select command with card's RCA. ulRet = CardSendCmd(CMD_SELECT_CARD, (ulRCA << 16)); if (ulRet == 0) { while (!(MAP_SDHostIntStatus(SDHOST_BASE) & SDHOST_INT_TC)); } // Delay 250ms for the card to become ready HAL_Delay (250); return ulRet; } //***************************************************************************** // //! Initializes physical drive //! //! This function initializes the physical drive //! //! \return Returns 0 on succeeded. //***************************************************************************** DSTATUS sd_disk_init (void) { unsigned long ulRet; unsigned long ulResp[4]; if (sd_disk_info.bStatus != 0) { sd_disk_info.bStatus = STA_NODISK; // Send std GO IDLE command if (CardSendCmd(CMD_GO_IDLE_STATE, 0) == 0) { // Get interface operating condition for the card ulRet = CardSendCmd(CMD_SEND_IF_COND,0x000001A5); MAP_SDHostRespGet(SDHOST_BASE,ulResp); // It's a SD ver 2.0 or higher card if (ulRet == 0 && ((ulResp[0] & 0xFF) == 0xA5)) { // Version 1 card do not respond to this command sd_disk_info.ulVersion = CARD_VERSION_2; sd_disk_info.ucCardType = CARD_TYPE_SDCARD; // Wait for card to become ready. do { // Send ACMD41 CardSendCmd(CMD_APP_CMD, 0); ulRet = CardSendCmd(CMD_SD_SEND_OP_COND, 0x40E00000); // Response contains 32-bit OCR register MAP_SDHostRespGet(SDHOST_BASE, ulResp); } while (((ulResp[0] >> 31) == 0)); if (ulResp[0] & (1UL<<30)) { sd_disk_info.ulCapClass = CARD_CAP_CLASS_SDHC; } sd_disk_info.bStatus = 0; } //It's a MMC or SD 1.x card else { // Wait for card to become ready. do { CardSendCmd(CMD_APP_CMD, 0); ulRet = CardSendCmd(CMD_SD_SEND_OP_COND,0x00E00000); if (ulRet == 0) { // Response contains 32-bit OCR register MAP_SDHostRespGet(SDHOST_BASE, ulResp); } } while (((ulRet == 0) && (ulResp[0] >> 31) == 0)); if (ulRet == 0) { sd_disk_info.ucCardType = CARD_TYPE_SDCARD; sd_disk_info.bStatus = 0; } else { if (CardSendCmd(CMD_SEND_OP_COND, 0) == 0) { // MMC not supported by the controller sd_disk_info.ucCardType = CARD_TYPE_MMC; } } } } // Get the RCA of the attached card if (sd_disk_info.bStatus == 0) { ulRet = CardSendCmd(CMD_ALL_SEND_CID, 0); if (ulRet == 0) { CardSendCmd(CMD_SEND_REL_ADDR,0); MAP_SDHostRespGet(SDHOST_BASE, ulResp); // Fill in the RCA sd_disk_info.usRCA = (ulResp[0] >> 16); // Get tha card capacity CardCapacityGet(&sd_disk_info); } // Select the card. ulRet = CardSelect(&sd_disk_info); if (ulRet == 0) { sd_disk_info.bStatus = 0; } } } return sd_disk_info.bStatus; } //***************************************************************************** // //! De-initializes the physical drive //! //! This function de-initializes the physical drive //***************************************************************************** void sd_disk_deinit (void) { sd_disk_info.ucCardType = CARD_TYPE_UNKNOWN; sd_disk_info.ulVersion = CARD_VERSION_1; sd_disk_info.ulCapClass = CARD_CAP_CLASS_SDSC; sd_disk_info.ulNofBlock = 0; sd_disk_info.ulBlockSize = 0; sd_disk_info.bStatus = STA_NOINIT; sd_disk_info.usRCA = 0; } //***************************************************************************** // //! Gets the disk status. //! //! This function gets the current status of the drive. //! //! \return Returns the current status of the specified drive // //***************************************************************************** DSTATUS sd_disk_status (void) { return sd_disk_info.bStatus; } //***************************************************************************** // //! Reads sector(s) from the disk drive. //! //! //! This function reads specified number of sectors from the drive //! //! \return Returns RES_OK on success. // //***************************************************************************** DRESULT sd_disk_read (BYTE* pBuffer, DWORD ulSectorNumber, UINT SectorCount) { DRESULT Res = RES_ERROR; unsigned long ulSize; if (SectorCount > 0) { // Return if disk not initialized if (sd_disk_info.bStatus & STA_NOINIT) { return RES_NOTRDY; } // SDSC uses linear address, SDHC uses block address if (sd_disk_info.ulCapClass == CARD_CAP_CLASS_SDSC) { ulSectorNumber = ulSectorNumber * SD_SECTOR_SIZE; } // Set the block count MAP_SDHostBlockCountSet(SDHOST_BASE, SectorCount); // Compute the number of words ulSize = (SD_SECTOR_SIZE * SectorCount) / 4; // Check if 1 block or multi block transfer if (SectorCount == 1) { // Send single block read command if (CardSendCmd(CMD_READ_SINGLE_BLK, ulSectorNumber) == 0) { // Read the block of data while (ulSize--) { MAP_SDHostDataRead(SDHOST_BASE, (unsigned long *)pBuffer); pBuffer += 4; } Res = RES_OK; } } else { // Send multi block read command if (CardSendCmd(CMD_READ_MULTI_BLK, ulSectorNumber) == 0) { // Read the data while (ulSize--) { MAP_SDHostDataRead(SDHOST_BASE, (unsigned long *)pBuffer); pBuffer += 4; } CardSendCmd(CMD_STOP_TRANS, 0); Res = RES_OK; } } } return Res; } //***************************************************************************** // //! Wrties sector(s) to the disk drive. //! //! //! This function writes specified number of sectors to the drive //! //! \return Returns RES_OK on success. // //***************************************************************************** DRESULT sd_disk_write (const BYTE* pBuffer, DWORD ulSectorNumber, UINT SectorCount) { DRESULT Res = RES_ERROR; unsigned long ulSize; if (SectorCount > 0) { // Return if disk not initialized if (sd_disk_info.bStatus & STA_NOINIT) { return RES_NOTRDY; } // SDSC uses linear address, SDHC uses block address if (sd_disk_info.ulCapClass == CARD_CAP_CLASS_SDSC) { ulSectorNumber = ulSectorNumber * SD_SECTOR_SIZE; } // Set the block count MAP_SDHostBlockCountSet(SDHOST_BASE, SectorCount); // Compute the number of words ulSize = (SD_SECTOR_SIZE * SectorCount) / 4; // Check if 1 block or multi block transfer if (SectorCount == 1) { // Send single block write command if (CardSendCmd(CMD_WRITE_SINGLE_BLK, ulSectorNumber) == 0) { // Write the data while (ulSize--) { MAP_SDHostDataWrite (SDHOST_BASE, (*(unsigned long *)pBuffer)); pBuffer += 4; } // Wait for data transfer complete while (!(MAP_SDHostIntStatus(SDHOST_BASE) & SDHOST_INT_TC)); Res = RES_OK; } } else { // Set the card write block count if (sd_disk_info.ucCardType == CARD_TYPE_SDCARD) { CardSendCmd(CMD_APP_CMD,sd_disk_info.usRCA << 16); CardSendCmd(CMD_SET_BLK_CNT, SectorCount); } // Send multi block write command if (CardSendCmd(CMD_WRITE_MULTI_BLK, ulSectorNumber) == 0) { // Write the data buffer while (ulSize--) { MAP_SDHostDataWrite(SDHOST_BASE, (*(unsigned long *)pBuffer)); pBuffer += 4; } // Wait for transfer complete while (!(MAP_SDHostIntStatus(SDHOST_BASE) & SDHOST_INT_TC)); CardSendCmd(CMD_STOP_TRANS, 0); Res = RES_OK; } } } return Res; }
mit
mmitche/corefx
src/Native/Unix/System.Security.Cryptography.Native/pal_hmac.c
12
1849
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal_config.h" #include "pal_utilities.h" #include "pal_hmac.h" #include <assert.h> HMAC_CTX* CryptoNative_HmacCreate(const uint8_t* key, int32_t keyLen, const EVP_MD* md) { assert(key != NULL || keyLen == 0); assert(keyLen >= 0); assert(md != NULL); HMAC_CTX* ctx = HMAC_CTX_new(); if (ctx == NULL) { // Allocation failed return NULL; } // NOTE: We can't pass NULL as empty key since HMAC_Init_ex will interpret // that as request to reuse the "existing" key. uint8_t _; if (keyLen == 0) key = &_; int ret = HMAC_Init_ex(ctx, key, keyLen, md, NULL); if (!ret) { free(ctx); return NULL; } return ctx; } void CryptoNative_HmacDestroy(HMAC_CTX* ctx) { if (ctx != NULL) { HMAC_CTX_free(ctx); } } int32_t CryptoNative_HmacReset(HMAC_CTX* ctx) { assert(ctx != NULL); return HMAC_Init_ex(ctx, NULL, 0, NULL, NULL); } int32_t CryptoNative_HmacUpdate(HMAC_CTX* ctx, const uint8_t* data, int32_t len) { assert(ctx != NULL); assert(data != NULL || len == 0); assert(len >= 0); if (len < 0) { return 0; } return HMAC_Update(ctx, data, Int32ToSizeT(len)); } int32_t CryptoNative_HmacFinal(HMAC_CTX* ctx, uint8_t* md, int32_t* len) { assert(ctx != NULL); assert(len != NULL); assert(md != NULL || *len == 0); assert(*len >= 0); if (len == NULL || *len < 0) { return 0; } unsigned int unsignedLen = Int32ToUint32(*len); int ret = HMAC_Final(ctx, md, &unsignedLen); *len = Uint32ToInt32(unsignedLen); return ret; }
mit
Portwell/Sense8
Sense8_32u4_boards-master.1.0.0/bootloaders/caterina/LUFA-111009/Projects/Incomplete/StandaloneProgrammer/Lib/SCSI.c
12
13325
/* LUFA Library Copyright (C) Dean Camera, 2011. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * * SCSI command processing routines, for SCSI commands issued by the host. Mass Storage * devices use a thin "Bulk-Only Transport" protocol for issuing commands and status information, * which wrap around standard SCSI device commands for controlling the actual storage medium. */ #define INCLUDE_FROM_SCSI_C #include "SCSI.h" #if defined(USB_CAN_BE_DEVICE) /** Structure to hold the SCSI response data to a SCSI INQUIRY command. This gives information about the device's * features and capabilities. */ static const SCSI_Inquiry_Response_t InquiryData = { .DeviceType = DEVICE_TYPE_BLOCK, .PeripheralQualifier = 0, .Removable = true, .Version = 0, .ResponseDataFormat = 2, .NormACA = false, .TrmTsk = false, .AERC = false, .AdditionalLength = 0x1F, .SoftReset = false, .CmdQue = false, .Linked = false, .Sync = false, .WideBus16Bit = false, .WideBus32Bit = false, .RelAddr = false, .VendorID = "LUFA", .ProductID = "Dataflash Disk", .RevisionID = {'0','.','0','0'}, }; /** Structure to hold the sense data for the last issued SCSI command, which is returned to the host after a SCSI REQUEST SENSE * command is issued. This gives information on exactly why the last command failed to complete. */ static SCSI_Request_Sense_Response_t SenseData = { .ResponseCode = 0x70, .AdditionalLength = 0x0A, }; /** Main routine to process the SCSI command located in the Command Block Wrapper read from the host. This dispatches * to the appropriate SCSI command handling routine if the issued command is supported by the device, else it returns * a command failure due to a ILLEGAL REQUEST. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise */ bool SCSI_DecodeSCSICommand(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { bool CommandSuccess = false; /* Run the appropriate SCSI command hander function based on the passed command */ switch (MSInterfaceInfo->State.CommandBlock.SCSICommandData[0]) { case SCSI_CMD_INQUIRY: CommandSuccess = SCSI_Command_Inquiry(MSInterfaceInfo); break; case SCSI_CMD_REQUEST_SENSE: CommandSuccess = SCSI_Command_Request_Sense(MSInterfaceInfo); break; case SCSI_CMD_READ_CAPACITY_10: CommandSuccess = SCSI_Command_Read_Capacity_10(MSInterfaceInfo); break; case SCSI_CMD_SEND_DIAGNOSTIC: CommandSuccess = SCSI_Command_Send_Diagnostic(MSInterfaceInfo); break; case SCSI_CMD_WRITE_10: CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_WRITE); break; case SCSI_CMD_READ_10: CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_READ); break; case SCSI_CMD_MODE_SENSE_6: CommandSuccess = SCSI_Command_ModeSense_6(MSInterfaceInfo); break; case SCSI_CMD_TEST_UNIT_READY: case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: case SCSI_CMD_VERIFY_10: /* These commands should just succeed, no handling required */ CommandSuccess = true; MSInterfaceInfo->State.CommandBlock.DataTransferLength = 0; break; default: /* Update the SENSE key to reflect the invalid command */ SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST, SCSI_ASENSE_INVALID_COMMAND, SCSI_ASENSEQ_NO_QUALIFIER); break; } /* Check if command was successfully processed */ if (CommandSuccess) { SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD, SCSI_ASENSE_NO_ADDITIONAL_INFORMATION, SCSI_ASENSEQ_NO_QUALIFIER); return true; } return false; } /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features * and capabilities to the host. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_Inquiry(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { uint16_t AllocationLength = SwapEndian_16(*(uint16_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[3]); uint16_t BytesTransferred = MIN(AllocationLength, sizeof(InquiryData)); /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */ if ((MSInterfaceInfo->State.CommandBlock.SCSICommandData[1] & ((1 << 0) | (1 << 1))) || MSInterfaceInfo->State.CommandBlock.SCSICommandData[2]) { /* Optional but unsupported bits set - update the SENSE key and fail the request */ SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST, SCSI_ASENSE_INVALID_FIELD_IN_CDB, SCSI_ASENSEQ_NO_QUALIFIER); return false; } Endpoint_Write_Stream_LE(&InquiryData, BytesTransferred, NULL); /* Pad out remaining bytes with 0x00 */ Endpoint_Null_Stream((AllocationLength - BytesTransferred), NULL); /* Finalize the stream transfer to send the last packet */ Endpoint_ClearIN(); /* Succeed the command and update the bytes transferred counter */ MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred; return true; } /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command, * including the error code and additional error information so that the host can determine why a command failed to complete. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_Request_Sense(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { uint8_t AllocationLength = MSInterfaceInfo->State.CommandBlock.SCSICommandData[4]; uint8_t BytesTransferred = MIN(AllocationLength, sizeof(SenseData)); Endpoint_Write_Stream_LE(&SenseData, BytesTransferred, NULL); Endpoint_Null_Stream((AllocationLength - BytesTransferred), NULL); Endpoint_ClearIN(); /* Succeed the command and update the bytes transferred counter */ MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred; return true; } /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity * on the selected Logical Unit (drive), as a number of OS-sized blocks. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_Read_Capacity_10(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { uint32_t LastBlockAddressInLUN = (VIRTUAL_MEMORY_BLOCKS - 1); uint32_t MediaBlockSize = VIRTUAL_MEMORY_BLOCK_SIZE; Endpoint_Write_Stream_BE(&LastBlockAddressInLUN, sizeof(LastBlockAddressInLUN), NULL); Endpoint_Write_Stream_BE(&MediaBlockSize, sizeof(MediaBlockSize), NULL); Endpoint_ClearIN(); /* Succeed the command and update the bytes transferred counter */ MSInterfaceInfo->State.CommandBlock.DataTransferLength -= 8; return true; } /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the * board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is * supported. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_Send_Diagnostic(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { /* Check to see if the SELF TEST bit is not set */ if (!(MSInterfaceInfo->State.CommandBlock.SCSICommandData[1] & (1 << 2))) { /* Only self-test supported - update SENSE key and fail the command */ SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST, SCSI_ASENSE_INVALID_FIELD_IN_CDB, SCSI_ASENSEQ_NO_QUALIFIER); return false; } /* Check to see if all attached Dataflash ICs are functional */ if (!(DataflashManager_CheckDataflashOperation())) { /* Update SENSE key with a hardware error condition and return command fail */ SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR, SCSI_ASENSE_NO_ADDITIONAL_INFORMATION, SCSI_ASENSEQ_NO_QUALIFIER); return false; } /* Succeed the command and update the bytes transferred counter */ MSInterfaceInfo->State.CommandBlock.DataTransferLength = 0; return true; } /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address * and total number of blocks to process, then calls the appropriate low-level Dataflash routine to handle the actual * reading and writing of the data. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * \param[in] IsDataRead Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE) * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_ReadWrite_10(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo, const bool IsDataRead) { uint32_t BlockAddress; uint16_t TotalBlocks; /* Check if the disk is write protected or not */ if ((IsDataRead == DATA_WRITE) && DISK_READ_ONLY) { /* Block address is invalid, update SENSE key and return command fail */ SCSI_SET_SENSE(SCSI_SENSE_KEY_DATA_PROTECT, SCSI_ASENSE_WRITE_PROTECTED, SCSI_ASENSEQ_NO_QUALIFIER); return false; } /* Load in the 32-bit block address (SCSI uses big-endian, so have to reverse the byte order) */ BlockAddress = SwapEndian_32(*(uint32_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[2]); /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to reverse the byte order) */ TotalBlocks = SwapEndian_16(*(uint16_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[7]); /* Check if the block address is outside the maximum allowable value for the LUN */ if (BlockAddress >= VIRTUAL_MEMORY_BLOCKS) { /* Block address is invalid, update SENSE key and return command fail */ SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST, SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE, SCSI_ASENSEQ_NO_QUALIFIER); return false; } /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */ if (IsDataRead == DATA_READ) DataflashManager_ReadBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks); else DataflashManager_WriteBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks); /* Update the bytes transferred counter and succeed the command */ MSInterfaceInfo->State.CommandBlock.DataTransferLength -= ((uint32_t)TotalBlocks * VIRTUAL_MEMORY_BLOCK_SIZE); return true; } /** Command processing for an issued SCSI MODE SENSE (6) command. This command returns various informational pages about * the SCSI device, as well as the device's Write Protect status. * * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with * * \return Boolean true if the command completed successfully, false otherwise. */ static bool SCSI_Command_ModeSense_6(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) { /* Send an empty header response with the Write Protect flag status */ Endpoint_Write_8(0x00); Endpoint_Write_8(0x00); Endpoint_Write_8(DISK_READ_ONLY ? 0x80 : 0x00); Endpoint_Write_8(0x00); Endpoint_ClearIN(); /* Update the bytes transferred counter and succeed the command */ MSInterfaceInfo->State.CommandBlock.DataTransferLength -= 4; return true; } #endif
mit
falcontersama/chatbot
node_modules/node-sass/src/sass_types/boolean.cpp
781
2455
#include <nan.h> #include "boolean.h" namespace SassTypes { Nan::Persistent<v8::Function> Boolean::constructor; bool Boolean::constructor_locked = false; Boolean::Boolean(bool v) : value(v) {} Boolean& Boolean::get_singleton(bool v) { static Boolean instance_false(false), instance_true(true); return v ? instance_true : instance_false; } v8::Local<v8::Function> Boolean::get_constructor() { Nan::EscapableHandleScope scope; v8::Local<v8::Function> conslocal; if (constructor.IsEmpty()) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("SassBoolean").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeTemplate(tpl, "getValue", Nan::New<v8::FunctionTemplate>(GetValue)); conslocal = Nan::GetFunction(tpl).ToLocalChecked(); constructor.Reset(conslocal); get_singleton(false).js_object.Reset(Nan::NewInstance(conslocal).ToLocalChecked()); Nan::SetInternalFieldPointer(Nan::New(get_singleton(false).js_object), 0, &get_singleton(false)); Nan::Set(conslocal, Nan::New("FALSE").ToLocalChecked(), Nan::New(get_singleton(false).js_object)); get_singleton(true).js_object.Reset(Nan::NewInstance(conslocal).ToLocalChecked()); Nan::SetInternalFieldPointer(Nan::New(get_singleton(true).js_object), 0, &get_singleton(true)); Nan::Set(conslocal, Nan::New("TRUE").ToLocalChecked(), Nan::New(get_singleton(true).js_object)); constructor_locked = true; } else { conslocal = Nan::New(constructor); } return scope.Escape(conslocal); } Sass_Value* Boolean::get_sass_value() { return sass_make_boolean(value); } v8::Local<v8::Object> Boolean::get_js_object() { return Nan::New(this->js_object); } NAN_METHOD(Boolean::New) { if (info.IsConstructCall()) { if (constructor_locked) { return Nan::ThrowTypeError("Cannot instantiate SassBoolean"); } } else { if (info.Length() != 1 || !info[0]->IsBoolean()) { return Nan::ThrowTypeError("Expected one boolean argument"); } info.GetReturnValue().Set(get_singleton(Nan::To<bool>(info[0]).FromJust()).get_js_object()); } } NAN_METHOD(Boolean::GetValue) { Boolean *out; if ((out = static_cast<Boolean*>(Factory::unwrap(info.This())))) { info.GetReturnValue().Set(Nan::New(out->value)); } } }
mit
kongscn/pyctp
stock/ctp/MdApi.cpp
14
161591
#define PY_SSIZE_T_CLEAN #ifndef CYTHON_USE_PYLONG_INTERNALS #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 0 #else #include "pyconfig.h" #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 1 #else #define CYTHON_USE_PYLONG_INTERNALS 0 #endif #endif #endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02040000 #error Cython requires Python 2.4+. #else #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" #define CYTHON_FORMAT_SSIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ (PyErr_Format(PyExc_TypeError, \ "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ (PyObject*)0)) #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ !PyComplex_Check(o)) #define PyIndex_Check __Pyx_PyIndex_Check #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #define __PYX_BUILD_PY_SSIZE_T "i" #else #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #define __Pyx_PyIndex_Check PyIndex_Check #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); #endif #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif #if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_VERSION_HEX < 0x02060000 #define Py_TPFLAGS_HAVE_VERSION_TAG 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_CheckExact PyString_CheckExact #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_DecodeEscape PyString_DecodeEscape #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_Size PyString_Size #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Repr PyString_Repr #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) #endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) #else #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) #else #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) #else #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #define __PYX_HAVE__ctp___MdApi #define __PYX_HAVE_API__ctp___MdApi #include "ThostFtdcUserApiDataTypeSSE.h" #include "ThostFtdcUserApiStructSSE.h" #include "string.h" #include "ThostFtdcMdApiSSE.h" #include "ios" #include "new" #include "stdexcept" #include "typeinfo" #include "CMdApi.h" #include "stdlib.h" #ifdef _OPENMP #include <omp.h> #endif #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #ifndef CYTHON_UNUSED #if defined(__GNUC__) #if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) #define CYTHON_UNUSED __attribute__ ((__unused__)) #else #define CYTHON_UNUSED #endif #elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) #define CYTHON_UNUSED __attribute__ ((__unused__)) #else #define CYTHON_UNUSED #endif #endif typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) #define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) #define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) #define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return u_end - u - 1; } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params() { PyObject* sys = NULL; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (ascii_chars_u == NULL) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", default_encoding_c); goto bad; } } Py_XDECREF(sys); Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return 0; bad: Py_XDECREF(sys); Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params() { PyObject* sys = NULL; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (sys == NULL) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); if (default_encoding == NULL) goto bad; default_encoding_c = PyBytes_AS_STRING(default_encoding); __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(sys); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(sys); Py_XDECREF(default_encoding); return -1; } #endif #endif #ifdef __GNUC__ #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else #define likely(x) (x) #define unlikely(x) (x) #endif #else #define likely(x) (x) #define unlikely(x) (x) #endif static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "MdApi.pyx", }; struct __pyx_obj_3ctp_6_MdApi_MdApi; struct __pyx_obj_3ctp_6_MdApi_MdApi { PyObject_HEAD CZQThostFtdcMdApi *api; CMdSpi *spi; }; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil) \ if (acquire_gil) { \ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ PyGILState_Release(__pyx_gilstate_save); \ } else { \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil) \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext() \ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); #define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) #define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ (((size) <= sizeof(Py_ssize_t)) ? \ __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i))) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { try { if (PyErr_Occurred()) ; else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); static int __Pyx_check_binary_version(void); typedef struct { int code_line; PyCodeObject* code_object; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static PyTypeObject *__pyx_ptype_3ctp_6_MdApi_MdApi = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_addressof = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument = 0; static PyObject *__pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout = 0; static void __pyx_f_3ctp_6_MdApi_MdApi_Release(struct __pyx_obj_3ctp_6_MdApi_MdApi *); #define __Pyx_MODULE_NAME "ctp._MdApi" int __pyx_module_is_main_ctp___MdApi = 0; static void __pyx_pf_3ctp_6_MdApi_5MdApi___dealloc__(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_2Alive(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_4Create(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, const char *__pyx_v_pszFlowPath, bool __pyx_v_bIsUsingUdp); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_6Release(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_8Init(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_10Join(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_12GetTradingDay(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_14RegisterFront(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, char *__pyx_v_pszFrontAddress); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_16SubscribeMarketData(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pInstrumentIDs, char *__pyx_v_pExchageID); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_18UnSubscribeMarketData(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pInstrumentIDs, char *__pyx_v_pExchageID); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_20ReqUserLogin(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pReqUserLogin, int __pyx_v_nRequestID); static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_22ReqUserLogout(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pUserLogout, int __pyx_v_nRequestID); static PyObject *__pyx_tp_new_3ctp_6_MdApi_MdApi(PyTypeObject *t, PyObject *a, PyObject *k); static char __pyx_k_1[] = ""; static char __pyx_k_2[] = "OnRspUnSubMarketData"; static char __pyx_k_3[] = "OnRtnDepthMarketData"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; static char __pyx_k__OnRspError[] = "OnRspError"; static char __pyx_k__nRequestID[] = "nRequestID"; static char __pyx_k__pExchageID[] = "pExchageID"; static char __pyx_k__bIsUsingUdp[] = "bIsUsingUdp"; static char __pyx_k__pUserLogout[] = "pUserLogout"; static char __pyx_k__pszFlowPath[] = "pszFlowPath"; static char __pyx_k__pReqUserLogin[] = "pReqUserLogin"; static char __pyx_k__OnRspUserLogin[] = "OnRspUserLogin"; static char __pyx_k__pInstrumentIDs[] = "pInstrumentIDs"; static char __pyx_k__OnRspUserLogout[] = "OnRspUserLogout"; static char __pyx_k__OnFrontConnected[] = "OnFrontConnected"; static char __pyx_k__OnHeartBeatWarning[] = "OnHeartBeatWarning"; static char __pyx_k__OnRspSubMarketData[] = "OnRspSubMarketData"; static char __pyx_k__OnFrontDisconnected[] = "OnFrontDisconnected"; static PyObject *__pyx_n_s_2; static PyObject *__pyx_n_s_3; static PyObject *__pyx_n_s__OnFrontConnected; static PyObject *__pyx_n_s__OnFrontDisconnected; static PyObject *__pyx_n_s__OnHeartBeatWarning; static PyObject *__pyx_n_s__OnRspError; static PyObject *__pyx_n_s__OnRspSubMarketData; static PyObject *__pyx_n_s__OnRspUserLogin; static PyObject *__pyx_n_s__OnRspUserLogout; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s____test__; static PyObject *__pyx_n_s__bIsUsingUdp; static PyObject *__pyx_n_s__nRequestID; static PyObject *__pyx_n_s__pExchageID; static PyObject *__pyx_n_s__pInstrumentIDs; static PyObject *__pyx_n_s__pReqUserLogin; static PyObject *__pyx_n_s__pUserLogout; static PyObject *__pyx_n_s__pszFlowPath; PyObject *_init(CYTHON_UNUSED PyObject *__pyx_v_self, PyObject *__pyx_v_m) { PyObject *__pyx_v_fa = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_init", 0); __pyx_t_1 = PyImport_ImportModule(S_ctypes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetAttrString(__pyx_t_1, S_addressof); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_addressof); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_addressof); __Pyx_GIVEREF(__pyx_t_2); __pyx_v_3ctp_6_MdApi_ApiStruct_addressof = __pyx_t_2; __pyx_t_2 = 0; __pyx_t_2 = XStr(S_from_address); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_v_fa = __pyx_t_2; __pyx_t_2 = 0; __pyx_t_2 = PyObject_GetAttrString(__pyx_v_m, S_DepthMarketData); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_v_fa); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData); __Pyx_GIVEREF(__pyx_t_1); __pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData = __pyx_t_1; __pyx_t_1 = 0; __pyx_t_1 = PyObject_GetAttrString(__pyx_v_m, S_RspInfo); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 12; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo); __Pyx_GIVEREF(__pyx_t_2); __pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo = __pyx_t_2; __pyx_t_2 = 0; __pyx_t_2 = PyObject_GetAttrString(__pyx_v_m, S_RspUserLogin); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_v_fa); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin); __Pyx_GIVEREF(__pyx_t_1); __pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin = __pyx_t_1; __pyx_t_1 = 0; __pyx_t_1 = PyObject_GetAttrString(__pyx_v_m, S_SpecificInstrument); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument); __Pyx_GIVEREF(__pyx_t_2); __pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument = __pyx_t_2; __pyx_t_2 = 0; __pyx_t_2 = PyObject_GetAttrString(__pyx_v_m, S_UserLogout); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = PyObject_GetAttr(__pyx_t_2, __pyx_v_fa); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XGOTREF(__pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout); __Pyx_DECREF(__pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout); __Pyx_GIVEREF(__pyx_t_1); __pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout = __pyx_t_1; __pyx_t_1 = 0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("ctp._MdApi._init", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_fa); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static void __pyx_f_3ctp_6_MdApi_MdApi_Release(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("MdApi_Release", 0); ReleaseMdApi(__pyx_v_self->api, __pyx_v_self->spi); __pyx_v_self->api = NULL; __pyx_v_self->spi = NULL; __Pyx_RefNannyFinishContext(); } static void __pyx_pw_3ctp_6_MdApi_5MdApi_1__dealloc__(PyObject *__pyx_v_self); static void __pyx_pw_3ctp_6_MdApi_5MdApi_1__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_pf_3ctp_6_MdApi_5MdApi___dealloc__(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); } static void __pyx_pf_3ctp_6_MdApi_5MdApi___dealloc__(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); __pyx_f_3ctp_6_MdApi_MdApi_Release(__pyx_v_self); __Pyx_RefNannyFinishContext(); } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_3Alive(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_3Alive(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Alive (wrapper)", 0); __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_2Alive(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_2Alive(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("Alive", 0); __pyx_t_1 = ((__pyx_v_self->spi != NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyInt_FromLong(__pyx_v_self->spi->tid); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_t_1 = ((__pyx_v_self->api != NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; goto __pyx_L4; } __pyx_L4:; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("ctp._MdApi.MdApi.Alive", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_5Create(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_5Create(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { const char *__pyx_v_pszFlowPath; bool __pyx_v_bIsUsingUdp; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Create (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__pszFlowPath,&__pyx_n_s__bIsUsingUdp,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pszFlowPath); if (value) { values[0] = value; kw_args--; } } case 1: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__bIsUsingUdp); if (value) { values[1] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "Create") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } } if (values[0]) { __pyx_v_pszFlowPath = __Pyx_PyObject_AsString(values[0]); if (unlikely((!__pyx_v_pszFlowPath) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_pszFlowPath = ((const char *)__pyx_k_1); } if (values[1]) { __pyx_v_bIsUsingUdp = __Pyx_PyObject_IsTrue(values[1]); if (unlikely((__pyx_v_bIsUsingUdp == (bool)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_bIsUsingUdp = ((bool)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("Create", 0, 0, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 35; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.Create", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_4Create(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), __pyx_v_pszFlowPath, __pyx_v_bIsUsingUdp); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_4Create(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, const char *__pyx_v_pszFlowPath, bool __pyx_v_bIsUsingUdp) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; CZQThostFtdcMdApi *__pyx_t_2; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("Create", 0); __pyx_t_1 = ((__pyx_v_self->api != NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; try { __pyx_t_2 = CZQThostFtdcMdApi::CreateFtdcMdApi(__pyx_v_pszFlowPath, __pyx_v_bIsUsingUdp); } catch(...) { __Pyx_CppExn2PyErr(); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_self->api = __pyx_t_2; __pyx_t_3 = CheckMemory(__pyx_v_self->api); if (unlikely(__pyx_t_3 == 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.Create", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_7Release(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_7Release(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Release (wrapper)", 0); __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_6Release(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_6Release(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Release", 0); __pyx_f_3ctp_6_MdApi_MdApi_Release(__pyx_v_self); __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_9Init(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_9Init(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Init (wrapper)", 0); __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_8Init(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_8Init(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("Init", 0); __pyx_t_1 = ((__pyx_v_self->api == NULL) != 0); if (!__pyx_t_1) { __pyx_t_2 = ((__pyx_v_self->spi != NULL) != 0); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_v_self->spi = new CMdSpi(((PyObject *)__pyx_v_self)); __pyx_t_4 = CheckMemory(__pyx_v_self->spi); if (unlikely(__pyx_t_4 == 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->api->RegisterSpi(__pyx_v_self->spi); __pyx_v_self->api->Init(); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.Init", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_11Join(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_11Join(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Join (wrapper)", 0); __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_10Join(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_10Join(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { int __pyx_v_ret; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("Join", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_ret = __pyx_v_self->api->Join(); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyInt_FromLong(__pyx_v_ret); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("ctp._MdApi.MdApi.Join", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_13GetTradingDay(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_13GetTradingDay(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("GetTradingDay (wrapper)", 0); __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_12GetTradingDay(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_12GetTradingDay(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self) { const char *__pyx_v_ret; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("GetTradingDay", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_ret = __pyx_v_self->api->GetTradingDay(); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBytes_FromString(__pyx_v_ret); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); __pyx_r = ((PyObject *)__pyx_t_2); __pyx_t_2 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("ctp._MdApi.MdApi.GetTradingDay", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_15RegisterFront(PyObject *__pyx_v_self, PyObject *__pyx_arg_pszFrontAddress); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_15RegisterFront(PyObject *__pyx_v_self, PyObject *__pyx_arg_pszFrontAddress) { char *__pyx_v_pszFrontAddress; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("RegisterFront (wrapper)", 0); assert(__pyx_arg_pszFrontAddress); { __pyx_v_pszFrontAddress = __Pyx_PyObject_AsString(__pyx_arg_pszFrontAddress); if (unlikely((!__pyx_v_pszFrontAddress) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.RegisterFront", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_14RegisterFront(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), ((char *)__pyx_v_pszFrontAddress)); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_14RegisterFront(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, char *__pyx_v_pszFrontAddress) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("RegisterFront", 0); __pyx_t_1 = ((__pyx_v_self->api == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_v_self->api->RegisterFront(__pyx_v_pszFrontAddress); __pyx_r = Py_None; __Pyx_INCREF(Py_None); __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_17SubscribeMarketData(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_17SubscribeMarketData(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_pInstrumentIDs = 0; char *__pyx_v_pExchageID; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SubscribeMarketData (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__pInstrumentIDs,&__pyx_n_s__pExchageID,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pInstrumentIDs)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pExchageID)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SubscribeMarketData", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "SubscribeMarketData") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_pInstrumentIDs = values[0]; __pyx_v_pExchageID = __Pyx_PyObject_AsString(values[1]); if (unlikely((!__pyx_v_pExchageID) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("SubscribeMarketData", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.SubscribeMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_16SubscribeMarketData(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), __pyx_v_pInstrumentIDs, __pyx_v_pExchageID); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_16SubscribeMarketData(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pInstrumentIDs, char *__pyx_v_pExchageID) { int __pyx_v_nCount; char **__pyx_v_ppInstrumentID; long __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; char *__pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("SubscribeMarketData", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_t_2 = PyObject_Length(__pyx_v_pInstrumentIDs); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_nCount = __pyx_t_2; __pyx_v_ppInstrumentID = ((char **)malloc(((sizeof(char *)) * __pyx_v_nCount))); __pyx_t_3 = CheckMemory(__pyx_v_ppInstrumentID); if (unlikely(__pyx_t_3 == 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} { __pyx_t_3 = __pyx_v_nCount; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_3; __pyx_v_i++) { __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_pInstrumentIDs, __pyx_v_i, sizeof(long), PyInt_FromLong, 0, 1, 1); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L5;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_t_4); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L5;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; (__pyx_v_ppInstrumentID[__pyx_v_i]) = __pyx_t_5; } { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_nCount = __pyx_v_self->api->SubscribeMarketData(__pyx_v_ppInstrumentID, __pyx_v_nCount, __pyx_v_pExchageID); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } } { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; __pyx_exc_lineno = 0; __pyx_why = 0; goto __pyx_L6; __pyx_L5: { __pyx_why = 4; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ErrFetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L6; } __pyx_L6:; free(__pyx_v_ppInstrumentID); switch (__pyx_why) { case 4: { __Pyx_ErrRestore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1_error; } } } __Pyx_XDECREF(__pyx_r); __pyx_t_4 = PyInt_FromLong(__pyx_v_nCount); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("ctp._MdApi.MdApi.SubscribeMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_19UnSubscribeMarketData(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_19UnSubscribeMarketData(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_pInstrumentIDs = 0; char *__pyx_v_pExchageID; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("UnSubscribeMarketData (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__pInstrumentIDs,&__pyx_n_s__pExchageID,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pInstrumentIDs)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pExchageID)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("UnSubscribeMarketData", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "UnSubscribeMarketData") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_pInstrumentIDs = values[0]; __pyx_v_pExchageID = __Pyx_PyObject_AsString(values[1]); if (unlikely((!__pyx_v_pExchageID) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("UnSubscribeMarketData", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.UnSubscribeMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_18UnSubscribeMarketData(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), __pyx_v_pInstrumentIDs, __pyx_v_pExchageID); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_18UnSubscribeMarketData(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pInstrumentIDs, char *__pyx_v_pExchageID) { int __pyx_v_nCount; char **__pyx_v_ppInstrumentID; long __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; char *__pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("UnSubscribeMarketData", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_t_2 = PyObject_Length(__pyx_v_pInstrumentIDs); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_nCount = __pyx_t_2; __pyx_v_ppInstrumentID = ((char **)malloc(((sizeof(char *)) * __pyx_v_nCount))); __pyx_t_3 = CheckMemory(__pyx_v_ppInstrumentID); if (unlikely(__pyx_t_3 == 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; __pyx_clineno = __LINE__; goto __pyx_L1_error;} { __pyx_t_3 = __pyx_v_nCount; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_3; __pyx_v_i++) { __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_pInstrumentIDs, __pyx_v_i, sizeof(long), PyInt_FromLong, 0, 1, 1); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L5;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_t_4); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L5;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; (__pyx_v_ppInstrumentID[__pyx_v_i]) = __pyx_t_5; } { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_nCount = __pyx_v_self->api->UnSubscribeMarketData(__pyx_v_ppInstrumentID, __pyx_v_nCount, __pyx_v_pExchageID); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } } { int __pyx_why; PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb; int __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; __pyx_exc_lineno = 0; __pyx_why = 0; goto __pyx_L6; __pyx_L5: { __pyx_why = 4; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ErrFetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb); __pyx_exc_lineno = __pyx_lineno; goto __pyx_L6; } __pyx_L6:; free(__pyx_v_ppInstrumentID); switch (__pyx_why) { case 4: { __Pyx_ErrRestore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb); __pyx_lineno = __pyx_exc_lineno; __pyx_exc_type = 0; __pyx_exc_value = 0; __pyx_exc_tb = 0; goto __pyx_L1_error; } } } __Pyx_XDECREF(__pyx_r); __pyx_t_4 = PyInt_FromLong(__pyx_v_nCount); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("ctp._MdApi.MdApi.UnSubscribeMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_21ReqUserLogin(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_21ReqUserLogin(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_pReqUserLogin = 0; int __pyx_v_nRequestID; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("ReqUserLogin (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__pReqUserLogin,&__pyx_n_s__nRequestID,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pReqUserLogin)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nRequestID)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("ReqUserLogin", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "ReqUserLogin") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_pReqUserLogin = values[0]; __pyx_v_nRequestID = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_nRequestID == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("ReqUserLogin", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 104; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.ReqUserLogin", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_20ReqUserLogin(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), __pyx_v_pReqUserLogin, __pyx_v_nRequestID); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_20ReqUserLogin(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pReqUserLogin, int __pyx_v_nRequestID) { size_t __pyx_v_address; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; size_t __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("ReqUserLogin", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_pReqUserLogin); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_pReqUserLogin); __Pyx_GIVEREF(__pyx_v_pReqUserLogin); __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_addressof, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; __pyx_t_4 = __Pyx_PyInt_AsSize_t(__pyx_t_3); if (unlikely((__pyx_t_4 == (size_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_address = __pyx_t_4; { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_nRequestID = __pyx_v_self->api->ReqUserLogin(((struct CZQThostFtdcReqUserLoginField *)__pyx_v_address), __pyx_v_nRequestID); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("ctp._MdApi.MdApi.ReqUserLogin", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_23ReqUserLogout(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); static PyObject *__pyx_pw_3ctp_6_MdApi_5MdApi_23ReqUserLogout(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_pUserLogout = 0; int __pyx_v_nRequestID; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("ReqUserLogout (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__pUserLogout,&__pyx_n_s__nRequestID,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pUserLogout)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nRequestID)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("ReqUserLogout", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "ReqUserLogout") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_pUserLogout = values[0]; __pyx_v_nRequestID = __Pyx_PyInt_AsInt(values[1]); if (unlikely((__pyx_v_nRequestID == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("ReqUserLogout", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("ctp._MdApi.MdApi.ReqUserLogout", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3ctp_6_MdApi_5MdApi_22ReqUserLogout(((struct __pyx_obj_3ctp_6_MdApi_MdApi *)__pyx_v_self), __pyx_v_pUserLogout, __pyx_v_nRequestID); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3ctp_6_MdApi_5MdApi_22ReqUserLogout(struct __pyx_obj_3ctp_6_MdApi_MdApi *__pyx_v_self, PyObject *__pyx_v_pUserLogout, int __pyx_v_nRequestID) { size_t __pyx_v_address; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; size_t __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("ReqUserLogout", 0); __pyx_t_1 = ((__pyx_v_self->spi == NULL) != 0); if (__pyx_t_1) { __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; goto __pyx_L3; } __pyx_L3:; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_pUserLogout); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_pUserLogout); __Pyx_GIVEREF(__pyx_v_pUserLogout); __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_addressof, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; __pyx_t_4 = __Pyx_PyInt_AsSize_t(__pyx_t_3); if (unlikely((__pyx_t_4 == (size_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_address = __pyx_t_4; { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif { __pyx_v_nRequestID = __pyx_v_self->api->ReqUserLogout(((struct CZQThostFtdcUserLogoutField *)__pyx_v_address), __pyx_v_nRequestID); } { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif } } __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("ctp._MdApi.MdApi.ReqUserLogout", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnFrontConnected(PyObject *__pyx_v_self) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnFrontConnected", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnFrontConnected); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnFrontConnected", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnFrontDisconnected(PyObject *__pyx_v_self, int __pyx_v_nReason) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnFrontDisconnected", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnFrontDisconnected); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromLong(__pyx_v_nReason); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnFrontDisconnected", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnHeartBeatWarning(PyObject *__pyx_v_self, int __pyx_v_nTimeLapse) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnHeartBeatWarning", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnHeartBeatWarning); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromLong(__pyx_v_nTimeLapse); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnHeartBeatWarning", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRspUserLogin(PyObject *__pyx_v_self, struct CZQThostFtdcRspUserLoginField *__pyx_v_pRspUserLogin, struct CZQThostFtdcRspInfoField *__pyx_v_pRspInfo, int __pyx_v_nRequestID, bool __pyx_v_bIsLast) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRspUserLogin", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnRspUserLogin); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pRspUserLogin == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspUserLogin)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } if (((__pyx_v_pRspInfo == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_3 = Py_None; } else { __pyx_t_4 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspInfo)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; } __pyx_t_4 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBool_FromLong(__pyx_v_bIsLast); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRspUserLogin", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRspUserLogout(PyObject *__pyx_v_self, struct CZQThostFtdcUserLogoutField *__pyx_v_pUserLogout, struct CZQThostFtdcRspInfoField *__pyx_v_pRspInfo, int __pyx_v_nRequestID, bool __pyx_v_bIsLast) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRspUserLogout", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnRspUserLogout); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pUserLogout == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pUserLogout)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } if (((__pyx_v_pRspInfo == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_3 = Py_None; } else { __pyx_t_4 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspInfo)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; } __pyx_t_4 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBool_FromLong(__pyx_v_bIsLast); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRspUserLogout", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRspError(PyObject *__pyx_v_self, struct CZQThostFtdcRspInfoField *__pyx_v_pRspInfo, int __pyx_v_nRequestID, bool __pyx_v_bIsLast) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRspError", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnRspError); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pRspInfo == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspInfo)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } __pyx_t_3 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_bIsLast); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRspError", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRspSubMarketData(PyObject *__pyx_v_self, struct CZQThostFtdcSpecificInstrumentField *__pyx_v_pSpecificInstrument, struct CZQThostFtdcRspInfoField *__pyx_v_pRspInfo, int __pyx_v_nRequestID, bool __pyx_v_bIsLast) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRspSubMarketData", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s__OnRspSubMarketData); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pSpecificInstrument == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pSpecificInstrument)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } if (((__pyx_v_pRspInfo == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_3 = Py_None; } else { __pyx_t_4 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspInfo)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; } __pyx_t_4 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBool_FromLong(__pyx_v_bIsLast); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRspSubMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRspUnSubMarketData(PyObject *__pyx_v_self, struct CZQThostFtdcSpecificInstrumentField *__pyx_v_pSpecificInstrument, struct CZQThostFtdcRspInfoField *__pyx_v_pRspInfo, int __pyx_v_nRequestID, bool __pyx_v_bIsLast) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRspUnSubMarketData", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pSpecificInstrument == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pSpecificInstrument)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } if (((__pyx_v_pRspInfo == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_3 = Py_None; } else { __pyx_t_4 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pRspInfo)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; } __pyx_t_4 = PyInt_FromLong(__pyx_v_nRequestID); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBool_FromLong(__pyx_v_bIsLast); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyTuple_New(4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 3, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_6)); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRspUnSubMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } int MdSpi_OnRtnDepthMarketData(PyObject *__pyx_v_self, struct CZQThostFtdcDepthMarketDataField *__pyx_v_pDepthMarketData) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("MdSpi_OnRtnDepthMarketData", 0); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (((__pyx_v_pDepthMarketData == NULL) != 0)) { __Pyx_INCREF(Py_None); __pyx_t_2 = Py_None; } else { __pyx_t_3 = __Pyx_PyInt_FromSize_t(((size_t)__pyx_v_pDepthMarketData)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_2 = __pyx_t_3; __pyx_t_3 = 0; } __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = 0; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("ctp._MdApi.MdSpi_OnRtnDepthMarketData", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_tp_new_3ctp_6_MdApi_MdApi(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { PyObject *o; o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; return o; } static void __pyx_tp_dealloc_3ctp_6_MdApi_MdApi(PyObject *o) { { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_pw_3ctp_6_MdApi_5MdApi_1__dealloc__(o); if (PyErr_Occurred()) PyErr_WriteUnraisable(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } (*Py_TYPE(o)->tp_free)(o); } static PyMethodDef __pyx_methods_3ctp_6_MdApi_MdApi[] = { {__Pyx_NAMESTR("Alive"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_3Alive, METH_NOARGS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("Create"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_5Create, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("Release"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_7Release, METH_NOARGS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("Init"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_9Init, METH_NOARGS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("Join"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_11Join, METH_NOARGS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("GetTradingDay"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_13GetTradingDay, METH_NOARGS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("RegisterFront"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_15RegisterFront, METH_O, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("SubscribeMarketData"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_17SubscribeMarketData, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("UnSubscribeMarketData"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_19UnSubscribeMarketData, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("ReqUserLogin"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_21ReqUserLogin, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, {__Pyx_NAMESTR("ReqUserLogout"), (PyCFunction)__pyx_pw_3ctp_6_MdApi_5MdApi_23ReqUserLogout, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type_3ctp_6_MdApi_MdApi = { PyVarObject_HEAD_INIT(0, 0) __Pyx_NAMESTR("ctp._MdApi.MdApi"), sizeof(struct __pyx_obj_3ctp_6_MdApi_MdApi), 0, __pyx_tp_dealloc_3ctp_6_MdApi_MdApi, 0, 0, 0, #if PY_MAJOR_VERSION < 3 0, #else 0, #endif 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, 0, 0, 0, 0, 0, 0, 0, __pyx_methods_3ctp_6_MdApi_MdApi, 0, 0, 0, 0, 0, 0, 0, 0, 0, __pyx_tp_new_3ctp_6_MdApi_MdApi, 0, 0, 0, 0, 0, 0, 0, 0, #if PY_VERSION_HEX >= 0x02060000 0, #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif __Pyx_NAMESTR("_MdApi"), 0, -1, __pyx_methods , NULL, NULL, NULL, NULL }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 1, 1}, {&__pyx_n_s_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 1, 1}, {&__pyx_n_s__OnFrontConnected, __pyx_k__OnFrontConnected, sizeof(__pyx_k__OnFrontConnected), 0, 0, 1, 1}, {&__pyx_n_s__OnFrontDisconnected, __pyx_k__OnFrontDisconnected, sizeof(__pyx_k__OnFrontDisconnected), 0, 0, 1, 1}, {&__pyx_n_s__OnHeartBeatWarning, __pyx_k__OnHeartBeatWarning, sizeof(__pyx_k__OnHeartBeatWarning), 0, 0, 1, 1}, {&__pyx_n_s__OnRspError, __pyx_k__OnRspError, sizeof(__pyx_k__OnRspError), 0, 0, 1, 1}, {&__pyx_n_s__OnRspSubMarketData, __pyx_k__OnRspSubMarketData, sizeof(__pyx_k__OnRspSubMarketData), 0, 0, 1, 1}, {&__pyx_n_s__OnRspUserLogin, __pyx_k__OnRspUserLogin, sizeof(__pyx_k__OnRspUserLogin), 0, 0, 1, 1}, {&__pyx_n_s__OnRspUserLogout, __pyx_k__OnRspUserLogout, sizeof(__pyx_k__OnRspUserLogout), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, {&__pyx_n_s__bIsUsingUdp, __pyx_k__bIsUsingUdp, sizeof(__pyx_k__bIsUsingUdp), 0, 0, 1, 1}, {&__pyx_n_s__nRequestID, __pyx_k__nRequestID, sizeof(__pyx_k__nRequestID), 0, 0, 1, 1}, {&__pyx_n_s__pExchageID, __pyx_k__pExchageID, sizeof(__pyx_k__pExchageID), 0, 0, 1, 1}, {&__pyx_n_s__pInstrumentIDs, __pyx_k__pInstrumentIDs, sizeof(__pyx_k__pInstrumentIDs), 0, 0, 1, 1}, {&__pyx_n_s__pReqUserLogin, __pyx_k__pReqUserLogin, sizeof(__pyx_k__pReqUserLogin), 0, 0, 1, 1}, {&__pyx_n_s__pUserLogout, __pyx_k__pUserLogout, sizeof(__pyx_k__pUserLogout), 0, 0, 1, 1}, {&__pyx_n_s__pszFlowPath, __pyx_k__pszFlowPath, sizeof(__pyx_k__pszFlowPath), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { return 0; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_MdApi(void); PyMODINIT_FUNC init_MdApi(void) #else PyMODINIT_FUNC PyInit__MdApi(void); PyMODINIT_FUNC PyInit__MdApi(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__MdApi(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD PyEval_InitThreads(); #endif #endif #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4(__Pyx_NAMESTR("_MdApi"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_d); #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!PyDict_GetItemString(modules, "ctp._MdApi")) { if (unlikely(PyDict_SetItemString(modules, "ctp._MdApi", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif if (__pyx_module_is_main_ctp___MdApi) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_3ctp_6_MdApi_ApiStruct_addressof = Py_None; Py_INCREF(Py_None); __pyx_v_3ctp_6_MdApi_ApiStruct_DepthMarketData = Py_None; Py_INCREF(Py_None); __pyx_v_3ctp_6_MdApi_ApiStruct_RspInfo = Py_None; Py_INCREF(Py_None); __pyx_v_3ctp_6_MdApi_ApiStruct_RspUserLogin = Py_None; Py_INCREF(Py_None); __pyx_v_3ctp_6_MdApi_ApiStruct_SpecificInstrument = Py_None; Py_INCREF(Py_None); __pyx_v_3ctp_6_MdApi_ApiStruct_UserLogout = Py_None; Py_INCREF(Py_None); if (PyType_Ready(&__pyx_type_3ctp_6_MdApi_MdApi) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_SetAttrString(__pyx_m, "MdApi", (PyObject *)&__pyx_type_3ctp_6_MdApi_MdApi) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_3ctp_6_MdApi_MdApi = &__pyx_type_3ctp_6_MdApi_MdApi; XFixSysModules(); __pyx_t_1 = PyObject_GetAttrString(__pyx_m, S___name__); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyCFunction_NewEx((&_init_method), NULL, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = PyObject_SetAttrString(__pyx_m, _init_method.ml_name, __pyx_t_2); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { __Pyx_AddTraceback("init ctp._MdApi", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init ctp._MdApi"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%s() got an unexpected keyword argument '%s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (PyErr_ExceptionMatches(PyExc_OverflowError)) PyErr_Clear(); else return NULL; } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_Restore(type, value, tb); #endif } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(type, value, tb); #endif } static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { const unsigned char neg_one = (unsigned char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned char" : "value too large to convert to unsigned char"); } return (unsigned char)-1; } return (unsigned char)val; } return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { const unsigned short neg_one = (unsigned short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned short" : "value too large to convert to unsigned short"); } return (unsigned short)-1; } return (unsigned short)val; } return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { const unsigned int neg_one = (unsigned int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned int" : "value too large to convert to unsigned int"); } return (unsigned int)-1; } return (unsigned int)val; } return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { const char neg_one = (char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to char" : "value too large to convert to char"); } return (char)-1; } return (char)val; } return (char)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { const short neg_one = (short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to short" : "value too large to convert to short"); } return (short)-1; } return (short)val; } return (short)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { const int neg_one = (int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to int" : "value too large to convert to int"); } return (int)-1; } return (int)val; } return (int)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { const signed char neg_one = (signed char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed char" : "value too large to convert to signed char"); } return (signed char)-1; } return (signed char)val; } return (signed char)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { const signed short neg_one = (signed short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed short" : "value too large to convert to signed short"); } return (signed short)-1; } return (signed short)val; } return (signed short)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { const signed int neg_one = (signed int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed int" : "value too large to convert to signed int"); } return (signed int)-1; } return (signed int)val; } return (signed int)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { const int neg_one = (int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to int" : "value too large to convert to int"); } return (int)-1; } return (int)val; } return (int)__Pyx_PyInt_AsLong(x); } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return (unsigned long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return (unsigned long)PyLong_AsUnsignedLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (unsigned long)PyLong_AsLong(x); } } else { unsigned long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned long)-1; val = __Pyx_PyInt_AsUnsignedLong(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { unsigned PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned PY_LONG_LONG)-1; val = __Pyx_PyInt_AsUnsignedLongLong(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return (long)PyLong_AsUnsignedLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (long)PyLong_AsLong(x); } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long)-1; val = __Pyx_PyInt_AsLong(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return (PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1; val = __Pyx_PyInt_AsLongLong(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return (signed long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(signed long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return (signed long)PyLong_AsUnsignedLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(signed long)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (signed long)PyLong_AsLong(x); } } else { signed long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed long)-1; val = __Pyx_PyInt_AsSignedLong(tmp); Py_DECREF(tmp); return val; } } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { switch (Py_SIZE(x)) { case 0: return 0; case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; } } #endif #endif return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { signed PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed PY_LONG_LONG)-1; val = __Pyx_PyInt_AsSignedLongLong(tmp); Py_DECREF(tmp); return val; } } static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); #if PY_VERSION_HEX < 0x02050000 return PyErr_Warn(NULL, message); #else return PyErr_WarnEx(NULL, message, 1); #endif } return 0; } static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = (start + end) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_empty_tuple, py_srcfile, py_funcname, py_line, __pyx_empty_bytes ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_globals = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), py_code, py_globals, 0 ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_DATA_SIZE(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (r < 0) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%s__ returned non-%s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) return PyInt_FromLong((long)ival); else { unsigned char *bytes = (unsigned char *) &ival; int one = 1; int little = (int)*(unsigned char*)&one; return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); } #else return PyInt_FromSize_t(ival); #endif } static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; } #endif
mit
shengwen1997/stm32_pratice
firmware/freertos/queue/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/RX200_RX210-RSK_Renesas/RTOSDemo/Renesas-Files/hd44780.c
14
12258
/*------------------------------------------------------------------------/ / EZ-LCD - Generic control module for HD44780 LCDC - R0.01c /-------------------------------------------------------------------------/ / / Copyright (C) 2010, ChaN, all right reserved. / / * This software is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. / /-------------------------------------------------------------------------/ / Nov 12,'10 R0.01c First release. /------------------------------------------------------------------------*/ #include <machine.h> #include "hd44780.h" /*-------------------------------------------------------------------------*/ /* Platform dependent macros and functions needed to be modified */ /*-------------------------------------------------------------------------*/ /* Bus controls */ #include "iodefine.h" /* Device specific include file */ #include "rskrx210def.h" #define IF_BUS 4 /* Data bus width (4 or 8) */ #define IF_INIT() {} /* Initialize control port */ #define E1_HIGH() LCD_EN = 1 /* Set E(E1) high */ #define E1_LOW() LCD_EN = 0 /* Set E(E1) low */ #define E2_HIGH() /* Set E2 high (dual controller only) */ #define E2_LOW() /* Set E2 low (dual controller only) */ #define RS_HIGH() LCD_RS = 1 /* Set RS high */ #define RS_LOW() LCD_RS = 0 /* Set RS low */ #define OUT_DATA(d) LCD_DATA = (d & 0x0F)//LCD_DATA = ((LCD_DATA & 0xF0) | (d & 0x0F)) /* Output a byte d on the data bus (higher 4 bits of d in 4-bit mode) */ #define IF_DLY60() {nop();nop();nop(); } /* Delay >=60ns (can be blanked for most uC) */ #define IF_DLY450() {unsigned long x; for(x=0; x<22; x++){nop();}} /* Delay >=450ns@3V, >=250ns@5V */ #define DELAY_US(n) {unsigned long x; for(x=0; x<(n*50); x++){nop();}} /* Delay n microseconds */ /* Characteristics of LCD module */ #define LCD_ETIME_1 1530 /* Execution time of Clear Display command [us] */ #define LCD_ETIME_2 43 /* Execution time of other command and data write [us] */ #define LCD_DLF 2.0 /* Delay factor (>=2.0) */ /*-------------------------------------------------------------------------*/ #if _LCD_ROWS >= 2 || _LCD_COLS > 8 #define LCD_IF_2ROW 8 /* 2-row cfg. */ #if _LCD_ROWS == 1 #define LCD_IF_SPLIT 1 /* Half split row */ #else #define LCD_IF_SPLIT 0 /* Direct row */ #endif #else #define LCD_IF_2ROW 0 /* 1-row cfg. */ #endif #if _LCD_ROWS == 4 && _LCD_COLS <= 20 #define LCD_IF_ALTROW 1 /* Alternate row layout */ #else #define LCD_IF_ALTROW 0 /* Incremental row layout */ #endif #if _LCD_ROWS == 4 && _LCD_COLS > 20 #define LCD_IF_DUAL 1 /* Dual controller */ #else #define LCD_IF_DUAL 0 /* Single controller */ #endif #define LCD_DT1 ((uint16_t)(LCD_ETIME_1 * LCD_DLF)) #define LCD_DT2 ((uint16_t)(LCD_ETIME_2 * LCD_DLF)) static uint8_t Row, Column; /* Current cursor position */ #if _USE_CURSOR static uint8_t Csr; /* Current cursor state */ #endif /*----------------------------------------------*/ /* Write a byte to the LCD controller */ /*----------------------------------------------*/ static void lcd_write ( uint8_t reg, /* b0:command(0)/data(1), b2..1:E1(2)/E2(1)/both(0)(don't care on single controller), b3:write high nibble only(don't care on 8-bit bus) */ uint8_t dat /* Byte to be written */ ) { if (reg & 1) /* Select register */ RS_HIGH(); else RS_LOW(); IF_DLY60(); #if IF_BUS == 4 if (!(reg & 8)) { OUT_DATA(dat); #if LCD_IF_DUAL if (!(reg & 2)) E1_HIGH(); if (!(reg & 4)) E2_HIGH(); IF_DLY450(); E1_LOW(); E2_LOW(); #else E1_HIGH(); IF_DLY450(); E1_LOW(); #endif IF_DLY450(); dat <<= 4; } #endif OUT_DATA(dat); #if LCD_IF_DUAL if (!(reg & 2)) E1_HIGH(); if (!(reg & 4)) E2_HIGH(); IF_DLY450(); E1_LOW(); E2_LOW(); #else E1_HIGH(); IF_DLY450(); E1_LOW(); #endif DELAY_US(LCD_DT2); /* Always use timer */ } /*-----------------------------------------------------------------------*/ /* Initialize LCD module */ /*-----------------------------------------------------------------------*/ void lcd_init (void) { uint8_t d; E1_HIGH(); DELAY_US(40000); E1_LOW(); // IF_INIT(); // DELAY_US(40000); lcd_write(8, 0x30); DELAY_US(4100); lcd_write(8, 0x30); DELAY_US(100); lcd_write(8, 0x30); d = (IF_BUS == 4 ? 0x20 : 0x30) | LCD_IF_2ROW; lcd_write(8, d); #if IF_BUS == 4 lcd_write(0, d); #endif lcd_write(0, 0x08); lcd_write(0, 0x01); DELAY_US(LCD_DT1); lcd_write(0, 0x06); lcd_write(0, 0x0C); Row = Column = 0; #if _USE_CURSOR Csr = 0; #endif } /*-----------------------------------------------------------------------*/ /* Set cursor position */ /*-----------------------------------------------------------------------*/ void lcd_locate ( uint8_t row, /* Cursor row position (0.._LCD_ROWS-1) */ uint8_t col /* Cursor column position (0.._LCD_COLS-1) */ ) { Row = row; Column = col; if (row < _LCD_ROWS && col < _LCD_COLS) { if (_LCD_COLS >= 2 && (row & 1)) col += 0x40; if (LCD_IF_SPLIT && col >= _LCD_COLS / 2) col += 0x40 - _LCD_COLS / 2; if (LCD_IF_ALTROW && (row & 2)) col += _LCD_COLS; col |= 0x80; } else { col = 0x0C; } #if LCD_IF_DUAL if (_USE_CURSOR && !(row &= 2)) row |= 4; lcd_write(row, col); #if _USE_CURSOR if (col != 0x0C) lcd_write(row, Csr | 0x0C); row ^= 6; lcd_write(row, 0x0C); #endif #else lcd_write(0, col); #if _USE_CURSOR if (col != 0x0C) lcd_write(0, Csr | 0x0C); #endif #endif } /*-----------------------------------------------------------------------*/ /* Put a character */ /*-----------------------------------------------------------------------*/ void lcd_putc ( uint8_t chr ) { if (chr == '\f') { /* Clear Screen and Return Home */ lcd_write(0, 0x01); DELAY_US(LCD_DT1); lcd_locate(0, 0); return; } if (Row >= _LCD_ROWS) return; if (chr == '\r') { /* Cursor return */ lcd_locate(Row, 0); return; } if (chr == '\n') { /* Next row */ lcd_locate(Row + 1, 0); return; } if (chr == '\b') { /* Cursor back */ if (Column) lcd_locate(Row, Column - 1); return; } if (Column >= _LCD_COLS) return; lcd_write((LCD_IF_DUAL && Row >= 2) ? 3 : 5, chr); Column++; if (LCD_IF_SPLIT && Column == _LCD_COLS / 2) lcd_write(0, 0x40); if (Column >= _LCD_COLS) lcd_locate(Row + 1, 0); } /*-----------------------------------------------------------------------*/ /* Set cursor form */ /*-----------------------------------------------------------------------*/ #if _USE_CURSOR void lcd_cursor ( uint8_t stat /* 0:off, 1:blinking block, 2:under-line */ ) { Csr = stat & 3; lcd_locate(Row, Column); } #endif /*-----------------------------------------------------------------------*/ /* Register user character pattern */ /*-----------------------------------------------------------------------*/ #if _USE_CGRAM void lcd_setcg ( uint8_t chr, /* Character code to be registered (0..7) */ uint8_t n, /* Number of characters to register */ const uint8_t* p /* Pointer to the character pattern (8 * n bytes) */ ) { lcd_write(0, 0x40 | chr * 8); n *= 8; do lcd_write(1, *p++); while (--n); lcd_locate(Row, Column); } #endif /*-----------------------------------------------------------------------*/ /* Put a fuel indicator */ /*-----------------------------------------------------------------------*/ #if _USE_FUEL && _USE_CGRAM void lcd_put_fuel ( int8_t val, /* Fuel level (-1:plugged, 0:empty cell, ..., 5:full cell) */ uint8_t chr /* User character to use */ ) { static const uint8_t plg[8] = {10,10,31,31,14,4,7,0}; uint8_t gfx[8], d, *p; int8_t i; if (val >= 0) { /* Cell (0..5) */ p = &gfx[8]; *(--p) = 0; *(--p) = 0x1F; for (i = 1; i <= 5; i++) { d = 0x1F; if (val < i) d = (i == 5) ? 0x1B : 0x11; *(--p) = d; } *(--p) = 0x0E; } else { /* Plug (-1) */ p = (uint8_t*)plg; } lcd_setcg(chr, 1, p); lcd_putc(chr); } #endif /*-----------------------------------------------------------------------*/ /* Draw bargraph */ /*-----------------------------------------------------------------------*/ #if _USE_BAR && _USE_CGRAM void lcd_put_bar ( uint16_t val, /* Bar length (0 to _MAX_BAR represents bar length from left end) */ uint8_t width, /* Display area (number of chars from cursor position) */ uint8_t chr /* User character code (2 chars used from this) */ ) { static const uint8_t ptn[] = { 0xE0, 0xE0, 0xE0, 0xC0, 0xC0, 0xC0, 0x80, 0, 0xF0, 0xE0, 0xE0, 0xE0, 0xC0, 0xC0, 0xC0, 0, 0xF0, 0xF0, 0xE0, 0xE0, 0xE0, 0xC0, 0xC0, 0 }; const uint8_t *pp; uint16_t n, m, s, gi; uint8_t gfx[16]; for (n = 0; n < 16; n++) /* Register common pattern (space/fill) */ gfx[n] = n < 7 ? 0 : 0xFF; lcd_setcg(_BASE_GRAPH, 2, gfx); /* Draw edge pattern into gfx[] */ val = (unsigned long)val * (width * 18) / (_MAX_BAR + 1); pp = &ptn[(val % 3) * 8]; /* Get edge pattern */ s = val / 3 % 6; /* Bit shift */ for (n = 0; n < 7; n++) { /* Draw edge pattern into the pattern buffer */ m = (*pp++ | 0xFF00) >> s; gfx[n] = m; gfx[n + 8] = m >> 6; } /* Put graphic pattern into the LCD module */ gi = val / 18; /* Indicator start position */ for (n = 1; n <= width; n++) { /* Draw each location in the bargraph */ if (n == gi) { /* When edge pattern is exist at the location */ m = chr + 1; /* A edge pattern */ } else { if (n == gi + 1) { lcd_setcg(chr, 2, gfx); /* Register edge pattern */ m = chr; } else { m = (n >= gi) ? _BASE_GRAPH : _BASE_GRAPH + 1; /* A space or fill */ } } lcd_putc(m); /* Put the character into the LCD */ } } #endif /*-----------------------------------------------------------------------*/ /* Draw point indicator */ /*-----------------------------------------------------------------------*/ #if _USE_POINT && _USE_CGRAM void lcd_put_point ( uint16_t val, /* Dot position (0 to _MAX_POINT represents left end to write end) */ uint8_t width, /* Display area (number of chars from cursor position) */ uint8_t chr /* User character code (2 chars used from this) */ ) { static const uint8_t ptn[] = { 0x06, 0x0C, 0x0C, 0x0C, 0x18, 0x18, 0x18, 0, 0x06, 0x06, 0x0C, 0x0C, 0x0C, 0x18, 0x18, 0, 0x06, 0x06, 0x06, 0x0C, 0x0C, 0x0C, 0x18, 0 }; const uint8_t *pp; uint16_t n, m, s, gi; uint8_t gfx[16]; for (n = 0; n < 16; n++) /* Register common pattern (space) */ gfx[n] = n < 7 ? 0 : 0xFF; lcd_setcg(_BASE_GRAPH, 1, gfx); /* Draw edge pattern into gfx[] */ val = (uint32_t)val * (width * 18 - 12) / (_MAX_BAR + 1); pp = &ptn[(val % 3) * 8]; /* Get edge pattern */ s = val / 3 % 6; /* Bit shift */ for (n = 0; n < 7; n++) { /* Draw edge pattern into the pattern buffer */ m = *pp++; m <<= 6; m >>= s; gfx[n] = m; gfx[n + 8] = m >> 6; } lcd_setcg(chr, 2, gfx); /* Register dot pattern */ /* Put graphic pattern into the LCD module */ gi = val / 18; /* Indicator start position */ for (n = 0; n < width; n++) { /* Draw each location in the bargraph */ if (n == gi) { /* When edge pattern is exist at the location */ m = chr + 1; /* A edge pattern */ } else { if (n == gi + 1) m = chr; else m = _BASE_GRAPH; /* A space */ } lcd_putc(m); /* Put the character into the LCD */ } } #endif
mit
aEchoCoin/Coin
src/qt/overviewpage.cpp
784
7182
#include "overviewpage.h" #include "ui_overviewpage.h" #include "clientmodel.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); }
mit
chizhizhen/DNT
caffe/src/caffe/layers/hinge_loss_layer.cpp
18
2451
#include <algorithm> #include <cfloat> #include <cmath> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int count = bottom[0]->count(); int dim = count / num; caffe_copy(count, bottom_data, bottom_diff); for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { bottom_diff[i * dim + j] = std::max( Dtype(0), 1 + bottom_diff[i * dim + j]); } } Dtype* loss = (*top)[0]->mutable_cpu_data(); switch (this->layer_param_.hinge_loss_param().norm()) { case HingeLossParameter_Norm_L1: loss[0] = caffe_cpu_asum(count, bottom_diff) / num; break; case HingeLossParameter_Norm_L2: loss[0] = caffe_cpu_dot(count, bottom_diff, bottom_diff) / num; break; default: LOG(FATAL) << "Unknown Norm"; } } template <typename Dtype> void HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type_name() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); const Dtype* label = (*bottom)[1]->cpu_data(); int num = (*bottom)[0]->num(); int count = (*bottom)[0]->count(); int dim = count / num; for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } const Dtype loss_weight = top[0]->cpu_diff()[0]; switch (this->layer_param_.hinge_loss_param().norm()) { case HingeLossParameter_Norm_L1: caffe_cpu_sign(count, bottom_diff, bottom_diff); caffe_scal(count, loss_weight / num, bottom_diff); break; case HingeLossParameter_Norm_L2: caffe_scal(count, loss_weight * 2 / num, bottom_diff); break; default: LOG(FATAL) << "Unknown Norm"; } } } INSTANTIATE_CLASS(HingeLossLayer); } // namespace caffe
mit
fanquake/bitcoin
src/clientversion.cpp
19
3764
// Copyright (c) 2012-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <util/translation.h> #include <tinyformat.h> #include <sstream> #include <string> #include <vector> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Satoshi"); #ifdef HAVE_BUILD_INFO #include <obj/build.h> // The <obj/build.h>, which is generated by the build environment (share/genbuild.sh), // could contain only one line of the following: // - "#define BUILD_GIT_TAG ...", if the top commit is tagged // - "#define BUILD_GIT_COMMIT ...", if the top commit is not tagged // - "// No build information available", if proper git information is not available #endif //! git will put "#define GIT_COMMIT_ID ..." on the next line inside archives. $Format:%n#define GIT_COMMIT_ID "%H"$ #ifdef BUILD_GIT_TAG #define BUILD_DESC BUILD_GIT_TAG #define BUILD_SUFFIX "" #else #define BUILD_DESC "v" PACKAGE_VERSION #if CLIENT_VERSION_IS_RELEASE #define BUILD_SUFFIX "" #elif defined(BUILD_GIT_COMMIT) #define BUILD_SUFFIX "-" BUILD_GIT_COMMIT #elif defined(GIT_COMMIT_ID) #define BUILD_SUFFIX "-g" GIT_COMMIT_ID #else #define BUILD_SUFFIX "-unk" #endif #endif static std::string FormatVersion(int nVersion) { return strprintf("%d.%d.%d", nVersion / 10000, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { static const std::string CLIENT_BUILD(BUILD_DESC BUILD_SUFFIX); return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); } std::string CopyrightHolders(const std::string& strPrefix) { const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION); std::string strCopyrightHolders = strPrefix + copyright_devs; // Make sure Bitcoin Core copyright is not removed by accident if (copyright_devs.find("Bitcoin Core") == std::string::npos) { strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers"; } return strCopyrightHolders; } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>"; return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software.").translated, PACKAGE_NAME, "<" PACKAGE_URL ">") + "\n" + strprintf(_("The source code is available from %s.").translated, URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.").translated + "\n" + strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") + "\n"; }
mit
bitmarker/STM32F3_IAR_Template
stm32f3/simple/Libraries/CMSIS/DSP_Lib/Source/FilteringFunctions/arm_fir_init_q15.c
20
5279
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 12. March 2014 * $Revision: V1.4.4 * * Project: CMSIS DSP Library * Title: arm_fir_init_q15.c * * Description: Q15 FIR filter initialization function. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupFilters */ /** * @addtogroup FIR * @{ */ /** * @param[in,out] *S points to an instance of the Q15 FIR filter structure. * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4. * @param[in] *pCoeffs points to the filter coefficients buffer. * @param[in] *pState points to the state buffer. * @param[in] blockSize is number of samples processed per call. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if * <code>numTaps</code> is not greater than or equal to 4 and even. * * <b>Description:</b> * \par * <code>pCoeffs</code> points to the array of filter coefficients stored in time reversed order: * <pre> * {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]} * </pre> * Note that <code>numTaps</code> must be even and greater than or equal to 4. * To implement an odd length filter simply increase <code>numTaps</code> by 1 and set the last coefficient to zero. * For example, to implement a filter with <code>numTaps=3</code> and coefficients * <pre> * {0.3, -0.8, 0.3} * </pre> * set <code>numTaps=4</code> and use the coefficients: * <pre> * {0.3, -0.8, 0.3, 0}. * </pre> * Similarly, to implement a two point filter * <pre> * {0.3, -0.3} * </pre> * set <code>numTaps=4</code> and use the coefficients: * <pre> * {0.3, -0.3, 0, 0}. * </pre> * \par * <code>pState</code> points to the array of state variables. * <code>pState</code> is of length <code>numTaps+blockSize</code>, when running on Cortex-M4 and Cortex-M3 and is of length <code>numTaps+blockSize-1</code>, when running on Cortex-M0 where <code>blockSize</code> is the number of input samples processed by each call to <code>arm_fir_q15()</code>. */ arm_status arm_fir_init_q15( arm_fir_instance_q15 * S, uint16_t numTaps, q15_t * pCoeffs, q15_t * pState, uint32_t blockSize) { arm_status status; #ifndef ARM_MATH_CM0_FAMILY /* Run the below code for Cortex-M4 and Cortex-M3 */ /* The Number of filter coefficients in the filter must be even and at least 4 */ if(numTaps & 0x1u) { status = ARM_MATH_ARGUMENT_ERROR; } else { /* Assign filter taps */ S->numTaps = numTaps; /* Assign coefficient pointer */ S->pCoeffs = pCoeffs; /* Clear the state buffer. The size is always (blockSize + numTaps ) */ memset(pState, 0, (numTaps + (blockSize)) * sizeof(q15_t)); /* Assign state pointer */ S->pState = pState; status = ARM_MATH_SUCCESS; } return (status); #else /* Run the below code for Cortex-M0 */ /* Assign filter taps */ S->numTaps = numTaps; /* Assign coefficient pointer */ S->pCoeffs = pCoeffs; /* Clear the state buffer. The size is always (blockSize + numTaps - 1) */ memset(pState, 0, (numTaps + (blockSize - 1u)) * sizeof(q15_t)); /* Assign state pointer */ S->pState = pState; status = ARM_MATH_SUCCESS; return (status); #endif /* #ifndef ARM_MATH_CM0_FAMILY */ } /** * @} end of FIR group */
mit
ClarkChen633/simplefilewatcher
source/FileWatcherLinux.cpp
21
4586
/** Copyright (c) 2009 James Wynn (james@jameswynn.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. James Wynn james@jameswynn.com */ #include <FileWatcher/FileWatcherLinux.h> #if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_LINUX #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <sys/inotify.h> #define BUFF_SIZE ((sizeof(struct inotify_event)+FILENAME_MAX)*1024) namespace FW { struct WatchStruct { WatchID mWatchID; String mDirName; FileWatchListener* mListener; }; //-------- FileWatcherLinux::FileWatcherLinux() { mFD = inotify_init(); if (mFD < 0) fprintf (stderr, "Error: %s\n", strerror(errno)); mTimeOut.tv_sec = 0; mTimeOut.tv_usec = 0; FD_ZERO(&mDescriptorSet); } //-------- FileWatcherLinux::~FileWatcherLinux() { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { delete iter->second; } mWatches.clear(); } //-------- WatchID FileWatcherLinux::addWatch(const String& directory, FileWatchListener* watcher, bool recursive) { int wd = inotify_add_watch (mFD, directory.c_str(), IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_MOVED_FROM | IN_DELETE); if (wd < 0) { if(errno == ENOENT) throw FileNotFoundException(directory); else throw Exception(strerror(errno)); // fprintf (stderr, "Error: %s\n", strerror(errno)); // return -1; } WatchStruct* pWatch = new WatchStruct(); pWatch->mListener = watcher; pWatch->mWatchID = wd; pWatch->mDirName = directory; mWatches.insert(std::make_pair(wd, pWatch)); return wd; } //-------- void FileWatcherLinux::removeWatch(const String& directory) { WatchMap::iterator iter = mWatches.begin(); WatchMap::iterator end = mWatches.end(); for(; iter != end; ++iter) { if(directory == iter->second->mDirName) { removeWatch(iter->first); return; } } } //-------- void FileWatcherLinux::removeWatch(WatchID watchid) { WatchMap::iterator iter = mWatches.find(watchid); if(iter == mWatches.end()) return; WatchStruct* watch = iter->second; mWatches.erase(iter); inotify_rm_watch(mFD, watchid); delete watch; watch = 0; } //-------- void FileWatcherLinux::update() { FD_SET(mFD, &mDescriptorSet); int ret = select(mFD + 1, &mDescriptorSet, NULL, NULL, &mTimeOut); if(ret < 0) { perror("select"); } else if(FD_ISSET(mFD, &mDescriptorSet)) { ssize_t len, i = 0; char action[81+FILENAME_MAX] = {0}; char buff[BUFF_SIZE] = {0}; len = read (mFD, buff, BUFF_SIZE); while (i < len) { struct inotify_event *pevent = (struct inotify_event *)&buff[i]; WatchStruct* watch = mWatches[pevent->wd]; handleAction(watch, pevent->name, pevent->mask); i += sizeof(struct inotify_event) + pevent->len; } } } //-------- void FileWatcherLinux::handleAction(WatchStruct* watch, const String& filename, unsigned long action) { if(!watch->mListener) return; if(IN_CLOSE_WRITE & action) { watch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename, Actions::Modified); } if(IN_MOVED_TO & action || IN_CREATE & action) { watch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename, Actions::Add); } if(IN_MOVED_FROM & action || IN_DELETE & action) { watch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename, Actions::Delete); } } };//namespace FW #endif//FILEWATCHER_PLATFORM_LINUX
mit
jakzale/ogre
Tools/VRMLConverter/vrmllib/src/indexed_face_set.cpp
21
3909
#include <vrmllib/nodes.h> #include <map> #include <stdexcept> namespace vrmllib { namespace bits { struct index_set { index_set() : geom(0), tex(0), norm(0), col(0) {} int geom; int tex; int norm; int col; }; bool operator<(const index_set &a, const index_set &b) { if (a.geom < b.geom) return true; if (a.geom > b.geom) return false; if (a.tex < b.tex) return true; if (a.tex > b.tex) return false; if (a.norm < b.norm) return true; if (a.norm > b.norm) return false; return a.col < b.col; } } // namespace bits using namespace bits; using std::vector; using std::map; using std::runtime_error; void IndexedFaceSet::geometry(vector<unsigned> &triangles, vector<vec3> &geometry, vector<vec3> &normals, vector<vec2> &texcoords, vector<col3> &colors) const { std::map<index_set, unsigned> index_map; vector<index_set> final_indices; Coordinate *coord = dynamic_cast<Coordinate *>(this->coord); if (!coord) throw runtime_error("no coordinates for indexed face set"); TextureCoordinate *texCoord = dynamic_cast<TextureCoordinate *>(this->texCoord); Normal *normal = dynamic_cast<Normal *>(this->normal); Color *color = dynamic_cast<Color *>(this->color); int colcase = 0; if (color) { colcase += colorIndex.empty() ? 2 : 1; colcase += colorPerVertex ? 2 : 0; } int normcase = 0; if (normal) { normcase += normalIndex.empty() ? 2 : 1; normcase += normalPerVertex ? 2 : 0; } // map vrml index tuples to vertices and output indices triangles.clear(); int facenum = 0, num_in_face = 0; for (unsigned i=0; i!=coordIndex.size(); ++i) { if (coordIndex[i] == -1) { if (num_in_face != 3) throw runtime_error( "polygon is not a triangle"); num_in_face = 0; ++facenum; continue; } else ++num_in_face; index_set is; is.geom = coordIndex[i]; if (texCoord) { if (!texCoordIndex.empty()) is.tex = texCoordIndex[i]; else is.tex = coordIndex[i]; } switch (colcase) { case 1: // !perVertex, !colorIndex.empty is.col = colorIndex[facenum]; break; case 2: // !perVertex, colorIndex.empty is.col = facenum; break; case 3: // perVertex, !colorIndex.empty is.col = colorIndex[i]; break; case 4: // perVertex, colorIndex.empty is.col = coordIndex[i]; break; }; switch (normcase) { case 1: // !perVertex, !normalIndex.empty is.norm = normalIndex[facenum]; break; case 2: // !perVertex, normalIndex.empty is.norm = facenum; break; case 3: // perVertex, !normalIndex.empty is.norm = normalIndex[i]; break; case 4: // perVertex, normalIndex.empty is.norm = coordIndex[i]; break; }; if (final_indices.empty()) { index_map[is] = 0; final_indices.push_back(is); triangles.push_back(0); } else { map<index_set, unsigned>::iterator i = index_map.find(is); if (i == index_map.end()) { index_map[is] = final_indices.size(); triangles.push_back(final_indices.size()); final_indices.push_back(is); } else triangles.push_back(i->second); } } // generate attributes geometry.resize(final_indices.size()); for (unsigned i=0; i!=final_indices.size(); ++i) geometry[i] = coord->point[final_indices[i].geom]; if (normal) { normals.resize(final_indices.size()); for (unsigned i=0; i!=final_indices.size(); ++i) normals[i] = normal->vector[final_indices[i].norm]; } else normals.clear(); if (texCoord) { texcoords.resize(final_indices.size()); for (unsigned i=0; i!=final_indices.size(); ++i) texcoords[i] = texCoord->point[final_indices[i].tex]; } else texcoords.clear(); if (color) { colors.resize(final_indices.size()); for (unsigned i=0; i!=final_indices.size(); ++i) colors[i] = color->color[final_indices[i].col]; } else colors.clear(); // convert to ccw if (!ccw) for (unsigned i=0; i!=triangles.size(); i+=3) std::swap(triangles[i+1], triangles[i+2]); } } // namespace vrmllib
mit
mrochan/gfrnet
caffe-gfrnet/src/caffe/layers/lrn_layer.cpp
22
10883
#include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void LRNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { size_ = this->layer_param_.lrn_param().local_size(); CHECK_EQ(size_ % 2, 1) << "LRN only supports odd values for local_size"; pre_pad_ = (size_ - 1) / 2; alpha_ = this->layer_param_.lrn_param().alpha(); beta_ = this->layer_param_.lrn_param().beta(); k_ = this->layer_param_.lrn_param().k(); if (this->layer_param_.lrn_param().norm_region() == LRNParameter_NormRegion_WITHIN_CHANNEL) { // Set up split_layer_ to use inputs in the numerator and denominator. split_top_vec_.clear(); split_top_vec_.push_back(&product_input_); split_top_vec_.push_back(&square_input_); LayerParameter split_param; split_layer_.reset(new SplitLayer<Dtype>(split_param)); split_layer_->SetUp(bottom, split_top_vec_); // Set up square_layer_ to square the inputs. square_bottom_vec_.clear(); square_top_vec_.clear(); square_bottom_vec_.push_back(&square_input_); square_top_vec_.push_back(&square_output_); LayerParameter square_param; square_param.mutable_power_param()->set_power(Dtype(2)); square_layer_.reset(new PowerLayer<Dtype>(square_param)); square_layer_->SetUp(square_bottom_vec_, square_top_vec_); // Set up pool_layer_ to sum over square neighborhoods of the input. pool_top_vec_.clear(); pool_top_vec_.push_back(&pool_output_); LayerParameter pool_param; pool_param.mutable_pooling_param()->set_pool( PoolingParameter_PoolMethod_AVE); pool_param.mutable_pooling_param()->set_pad(pre_pad_); pool_param.mutable_pooling_param()->set_kernel_size(size_); pool_layer_.reset(new PoolingLayer<Dtype>(pool_param)); pool_layer_->SetUp(square_top_vec_, pool_top_vec_); // Set up power_layer_ to compute (1 + alpha_/N^2 s)^-beta_, where s is // the sum of a squared neighborhood (the output of pool_layer_). power_top_vec_.clear(); power_top_vec_.push_back(&power_output_); LayerParameter power_param; power_param.mutable_power_param()->set_power(-beta_); power_param.mutable_power_param()->set_scale(alpha_); power_param.mutable_power_param()->set_shift(Dtype(1)); power_layer_.reset(new PowerLayer<Dtype>(power_param)); power_layer_->SetUp(pool_top_vec_, power_top_vec_); // Set up a product_layer_ to compute outputs by multiplying inputs by the // inverse demoninator computed by the power layer. product_bottom_vec_.clear(); product_bottom_vec_.push_back(&product_input_); product_bottom_vec_.push_back(&power_output_); LayerParameter product_param; EltwiseParameter* eltwise_param = product_param.mutable_eltwise_param(); eltwise_param->set_operation(EltwiseParameter_EltwiseOp_PROD); product_layer_.reset(new EltwiseLayer<Dtype>(product_param)); product_layer_->SetUp(product_bottom_vec_, top); } } template <typename Dtype> void LRNLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(4, bottom[0]->num_axes()) << "Input must have 4 axes, " << "corresponding to (num, channels, height, width)"; num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); switch (this->layer_param_.lrn_param().norm_region()) { case LRNParameter_NormRegion_ACROSS_CHANNELS: top[0]->Reshape(num_, channels_, height_, width_); scale_.Reshape(num_, channels_, height_, width_); break; case LRNParameter_NormRegion_WITHIN_CHANNEL: split_layer_->Reshape(bottom, split_top_vec_); square_layer_->Reshape(square_bottom_vec_, square_top_vec_); pool_layer_->Reshape(square_top_vec_, pool_top_vec_); power_layer_->Reshape(pool_top_vec_, power_top_vec_); product_layer_->Reshape(product_bottom_vec_, top); break; } } template <typename Dtype> void LRNLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { switch (this->layer_param_.lrn_param().norm_region()) { case LRNParameter_NormRegion_ACROSS_CHANNELS: CrossChannelForward_cpu(bottom, top); break; case LRNParameter_NormRegion_WITHIN_CHANNEL: WithinChannelForward(bottom, top); break; default: LOG(FATAL) << "Unknown normalization region."; } } template <typename Dtype> void LRNLayer<Dtype>::CrossChannelForward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); Dtype* scale_data = scale_.mutable_cpu_data(); // start with the constant value for (int i = 0; i < scale_.count(); ++i) { scale_data[i] = k_; } Blob<Dtype> padded_square(1, channels_ + size_ - 1, height_, width_); Dtype* padded_square_data = padded_square.mutable_cpu_data(); caffe_set(padded_square.count(), Dtype(0), padded_square_data); Dtype alpha_over_size = alpha_ / size_; // go through the images for (int n = 0; n < num_; ++n) { // compute the padded square caffe_sqr(channels_ * height_ * width_, bottom_data + bottom[0]->offset(n), padded_square_data + padded_square.offset(0, pre_pad_)); // Create the first channel scale for (int c = 0; c < size_; ++c) { caffe_axpy<Dtype>(height_ * width_, alpha_over_size, padded_square_data + padded_square.offset(0, c), scale_data + scale_.offset(n, 0)); } for (int c = 1; c < channels_; ++c) { // copy previous scale caffe_copy<Dtype>(height_ * width_, scale_data + scale_.offset(n, c - 1), scale_data + scale_.offset(n, c)); // add head caffe_axpy<Dtype>(height_ * width_, alpha_over_size, padded_square_data + padded_square.offset(0, c + size_ - 1), scale_data + scale_.offset(n, c)); // subtract tail caffe_axpy<Dtype>(height_ * width_, -alpha_over_size, padded_square_data + padded_square.offset(0, c - 1), scale_data + scale_.offset(n, c)); } } // In the end, compute output caffe_powx<Dtype>(scale_.count(), scale_data, -beta_, top_data); caffe_mul<Dtype>(scale_.count(), top_data, bottom_data, top_data); } template <typename Dtype> void LRNLayer<Dtype>::WithinChannelForward( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { split_layer_->Forward(bottom, split_top_vec_); square_layer_->Forward(square_bottom_vec_, square_top_vec_); pool_layer_->Forward(square_top_vec_, pool_top_vec_); power_layer_->Forward(pool_top_vec_, power_top_vec_); product_layer_->Forward(product_bottom_vec_, top); } template <typename Dtype> void LRNLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { switch (this->layer_param_.lrn_param().norm_region()) { case LRNParameter_NormRegion_ACROSS_CHANNELS: CrossChannelBackward_cpu(top, propagate_down, bottom); break; case LRNParameter_NormRegion_WITHIN_CHANNEL: WithinChannelBackward(top, propagate_down, bottom); break; default: LOG(FATAL) << "Unknown normalization region."; } } template <typename Dtype> void LRNLayer<Dtype>::CrossChannelBackward_cpu( const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* top_diff = top[0]->cpu_diff(); const Dtype* top_data = top[0]->cpu_data(); const Dtype* bottom_data = bottom[0]->cpu_data(); const Dtype* scale_data = scale_.cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); Blob<Dtype> padded_ratio(1, channels_ + size_ - 1, height_, width_); Blob<Dtype> accum_ratio(1, 1, height_, width_); Dtype* padded_ratio_data = padded_ratio.mutable_cpu_data(); Dtype* accum_ratio_data = accum_ratio.mutable_cpu_data(); // We hack a little bit by using the diff() to store an additional result Dtype* accum_ratio_times_bottom = accum_ratio.mutable_cpu_diff(); caffe_set(padded_ratio.count(), Dtype(0), padded_ratio_data); Dtype cache_ratio_value = 2. * alpha_ * beta_ / size_; caffe_powx<Dtype>(scale_.count(), scale_data, -beta_, bottom_diff); caffe_mul<Dtype>(scale_.count(), top_diff, bottom_diff, bottom_diff); // go through individual data int inverse_pre_pad = size_ - (size_ + 1) / 2; for (int n = 0; n < num_; ++n) { int block_offset = scale_.offset(n); // first, compute diff_i * y_i / s_i caffe_mul<Dtype>(channels_ * height_ * width_, top_diff + block_offset, top_data + block_offset, padded_ratio_data + padded_ratio.offset(0, inverse_pre_pad)); caffe_div<Dtype>(channels_ * height_ * width_, padded_ratio_data + padded_ratio.offset(0, inverse_pre_pad), scale_data + block_offset, padded_ratio_data + padded_ratio.offset(0, inverse_pre_pad)); // Now, compute the accumulated ratios and the bottom diff caffe_set(accum_ratio.count(), Dtype(0), accum_ratio_data); for (int c = 0; c < size_ - 1; ++c) { caffe_axpy<Dtype>(height_ * width_, 1., padded_ratio_data + padded_ratio.offset(0, c), accum_ratio_data); } for (int c = 0; c < channels_; ++c) { caffe_axpy<Dtype>(height_ * width_, 1., padded_ratio_data + padded_ratio.offset(0, c + size_ - 1), accum_ratio_data); // compute bottom diff caffe_mul<Dtype>(height_ * width_, bottom_data + top[0]->offset(n, c), accum_ratio_data, accum_ratio_times_bottom); caffe_axpy<Dtype>(height_ * width_, -cache_ratio_value, accum_ratio_times_bottom, bottom_diff + top[0]->offset(n, c)); caffe_axpy<Dtype>(height_ * width_, -1., padded_ratio_data + padded_ratio.offset(0, c), accum_ratio_data); } } } template <typename Dtype> void LRNLayer<Dtype>::WithinChannelBackward( const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { vector<bool> product_propagate_down(2, true); product_layer_->Backward(top, product_propagate_down, product_bottom_vec_); power_layer_->Backward(power_top_vec_, propagate_down, pool_top_vec_); pool_layer_->Backward(pool_top_vec_, propagate_down, square_top_vec_); square_layer_->Backward(square_top_vec_, propagate_down, square_bottom_vec_); split_layer_->Backward(split_top_vec_, propagate_down, bottom); } } #ifdef CPU_ONLY STUB_GPU(LRNLayer); STUB_GPU_FORWARD(LRNLayer, CrossChannelForward); STUB_GPU_BACKWARD(LRNLayer, CrossChannelBackward); #endif INSTANTIATE_CLASS(LRNLayer); REGISTER_LAYER_CLASS(LRN); } // namespace caffe
mit
dinkdeng/STM32Plus_IAR
IAR/CommonFiles/F7CommonFiles/DSP_Lib/FilteringFunctions/arm_conv_opt_q7.c
279
11903
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_conv_opt_q7.c * * Description: Convolution of Q7 sequences. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupFilters */ /** * @addtogroup Conv * @{ */ /** * @brief Convolution of Q7 sequences. * @param[in] *pSrcA points to the first input sequence. * @param[in] srcALen length of the first input sequence. * @param[in] *pSrcB points to the second input sequence. * @param[in] srcBLen length of the second input sequence. * @param[out] *pDst points to the location where the output result is written. Length srcALen+srcBLen-1. * @param[in] *pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2. * @param[in] *pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen). * @return none. * * \par Restrictions * If the silicon does not support unaligned memory access enable the macro UNALIGNED_SUPPORT_DISABLE * In this case input, output, scratch1 and scratch2 buffers should be aligned by 32-bit * * @details * <b>Scaling and Overflow Behavior:</b> * * \par * The function is implemented using a 32-bit internal accumulator. * Both the inputs are represented in 1.7 format and multiplications yield a 2.14 result. * The 2.14 intermediate results are accumulated in a 32-bit accumulator in 18.14 format. * This approach provides 17 guard bits and there is no risk of overflow as long as <code>max(srcALen, srcBLen)<131072</code>. * The 18.14 result is then truncated to 18.7 format by discarding the low 7 bits and then saturated to 1.7 format. * */ void arm_conv_opt_q7( q7_t * pSrcA, uint32_t srcALen, q7_t * pSrcB, uint32_t srcBLen, q7_t * pDst, q15_t * pScratch1, q15_t * pScratch2) { q15_t *pScr2, *pScr1; /* Intermediate pointers for scratch pointers */ q15_t x4; /* Temporary input variable */ q7_t *pIn1, *pIn2; /* inputA and inputB pointer */ uint32_t j, k, blkCnt, tapCnt; /* loop counter */ q7_t *px; /* Temporary input1 pointer */ q15_t *py; /* Temporary input2 pointer */ q31_t acc0, acc1, acc2, acc3; /* Accumulator */ q31_t x1, x2, x3, y1; /* Temporary input variables */ q7_t *pOut = pDst; /* output pointer */ q7_t out0, out1, out2, out3; /* temporary variables */ /* The algorithm implementation is based on the lengths of the inputs. */ /* srcB is always made to slide across srcA. */ /* So srcBLen is always considered as shorter or equal to srcALen */ if(srcALen >= srcBLen) { /* Initialization of inputA pointer */ pIn1 = pSrcA; /* Initialization of inputB pointer */ pIn2 = pSrcB; } else { /* Initialization of inputA pointer */ pIn1 = pSrcB; /* Initialization of inputB pointer */ pIn2 = pSrcA; /* srcBLen is always considered as shorter or equal to srcALen */ j = srcBLen; srcBLen = srcALen; srcALen = j; } /* pointer to take end of scratch2 buffer */ pScr2 = pScratch2; /* points to smaller length sequence */ px = pIn2 + srcBLen - 1; /* Apply loop unrolling and do 4 Copies simultaneously. */ k = srcBLen >> 2u; /* First part of the processing with loop unrolling copies 4 data points at a time. ** a second loop below copies for the remaining 1 to 3 samples. */ while(k > 0u) { /* copy second buffer in reversal manner */ x4 = (q15_t) * px--; *pScr2++ = x4; x4 = (q15_t) * px--; *pScr2++ = x4; x4 = (q15_t) * px--; *pScr2++ = x4; x4 = (q15_t) * px--; *pScr2++ = x4; /* Decrement the loop counter */ k--; } /* If the count is not a multiple of 4, copy remaining samples here. ** No loop unrolling is used. */ k = srcBLen % 0x4u; while(k > 0u) { /* copy second buffer in reversal manner for remaining samples */ x4 = (q15_t) * px--; *pScr2++ = x4; /* Decrement the loop counter */ k--; } /* Initialze temporary scratch pointer */ pScr1 = pScratch1; /* Fill (srcBLen - 1u) zeros in scratch buffer */ arm_fill_q15(0, pScr1, (srcBLen - 1u)); /* Update temporary scratch pointer */ pScr1 += (srcBLen - 1u); /* Copy (srcALen) samples in scratch buffer */ /* Apply loop unrolling and do 4 Copies simultaneously. */ k = srcALen >> 2u; /* First part of the processing with loop unrolling copies 4 data points at a time. ** a second loop below copies for the remaining 1 to 3 samples. */ while(k > 0u) { /* copy second buffer in reversal manner */ x4 = (q15_t) * pIn1++; *pScr1++ = x4; x4 = (q15_t) * pIn1++; *pScr1++ = x4; x4 = (q15_t) * pIn1++; *pScr1++ = x4; x4 = (q15_t) * pIn1++; *pScr1++ = x4; /* Decrement the loop counter */ k--; } /* If the count is not a multiple of 4, copy remaining samples here. ** No loop unrolling is used. */ k = srcALen % 0x4u; while(k > 0u) { /* copy second buffer in reversal manner for remaining samples */ x4 = (q15_t) * pIn1++; *pScr1++ = x4; /* Decrement the loop counter */ k--; } #ifndef UNALIGNED_SUPPORT_DISABLE /* Fill (srcBLen - 1u) zeros at end of scratch buffer */ arm_fill_q15(0, pScr1, (srcBLen - 1u)); /* Update pointer */ pScr1 += (srcBLen - 1u); #else /* Apply loop unrolling and do 4 Copies simultaneously. */ k = (srcBLen - 1u) >> 2u; /* First part of the processing with loop unrolling copies 4 data points at a time. ** a second loop below copies for the remaining 1 to 3 samples. */ while(k > 0u) { /* copy second buffer in reversal manner */ *pScr1++ = 0; *pScr1++ = 0; *pScr1++ = 0; *pScr1++ = 0; /* Decrement the loop counter */ k--; } /* If the count is not a multiple of 4, copy remaining samples here. ** No loop unrolling is used. */ k = (srcBLen - 1u) % 0x4u; while(k > 0u) { /* copy second buffer in reversal manner for remaining samples */ *pScr1++ = 0; /* Decrement the loop counter */ k--; } #endif /* Temporary pointer for scratch2 */ py = pScratch2; /* Initialization of pIn2 pointer */ pIn2 = (q7_t *) py; pScr2 = py; /* Actual convolution process starts here */ blkCnt = (srcALen + srcBLen - 1u) >> 2; while(blkCnt > 0) { /* Initialze temporary scratch pointer as scratch1 */ pScr1 = pScratch1; /* Clear Accumlators */ acc0 = 0; acc1 = 0; acc2 = 0; acc3 = 0; /* Read two samples from scratch1 buffer */ x1 = *__SIMD32(pScr1)++; /* Read next two samples from scratch1 buffer */ x2 = *__SIMD32(pScr1)++; tapCnt = (srcBLen) >> 2u; while(tapCnt > 0u) { /* Read four samples from smaller buffer */ y1 = _SIMD32_OFFSET(pScr2); /* multiply and accumlate */ acc0 = __SMLAD(x1, y1, acc0); acc2 = __SMLAD(x2, y1, acc2); /* pack input data */ #ifndef ARM_MATH_BIG_ENDIAN x3 = __PKHBT(x2, x1, 0); #else x3 = __PKHBT(x1, x2, 0); #endif /* multiply and accumlate */ acc1 = __SMLADX(x3, y1, acc1); /* Read next two samples from scratch1 buffer */ x1 = *__SIMD32(pScr1)++; /* pack input data */ #ifndef ARM_MATH_BIG_ENDIAN x3 = __PKHBT(x1, x2, 0); #else x3 = __PKHBT(x2, x1, 0); #endif acc3 = __SMLADX(x3, y1, acc3); /* Read four samples from smaller buffer */ y1 = _SIMD32_OFFSET(pScr2 + 2u); acc0 = __SMLAD(x2, y1, acc0); acc2 = __SMLAD(x1, y1, acc2); acc1 = __SMLADX(x3, y1, acc1); x2 = *__SIMD32(pScr1)++; #ifndef ARM_MATH_BIG_ENDIAN x3 = __PKHBT(x2, x1, 0); #else x3 = __PKHBT(x1, x2, 0); #endif acc3 = __SMLADX(x3, y1, acc3); pScr2 += 4u; /* Decrement the loop counter */ tapCnt--; } /* Update scratch pointer for remaining samples of smaller length sequence */ pScr1 -= 4u; /* apply same above for remaining samples of smaller length sequence */ tapCnt = (srcBLen) & 3u; while(tapCnt > 0u) { /* accumlate the results */ acc0 += (*pScr1++ * *pScr2); acc1 += (*pScr1++ * *pScr2); acc2 += (*pScr1++ * *pScr2); acc3 += (*pScr1++ * *pScr2++); pScr1 -= 3u; /* Decrement the loop counter */ tapCnt--; } blkCnt--; /* Store the result in the accumulator in the destination buffer. */ out0 = (q7_t) (__SSAT(acc0 >> 7u, 8)); out1 = (q7_t) (__SSAT(acc1 >> 7u, 8)); out2 = (q7_t) (__SSAT(acc2 >> 7u, 8)); out3 = (q7_t) (__SSAT(acc3 >> 7u, 8)); *__SIMD32(pOut)++ = __PACKq7(out0, out1, out2, out3); /* Initialization of inputB pointer */ pScr2 = py; pScratch1 += 4u; } blkCnt = (srcALen + srcBLen - 1u) & 0x3; /* Calculate convolution for remaining samples of Bigger length sequence */ while(blkCnt > 0) { /* Initialze temporary scratch pointer as scratch1 */ pScr1 = pScratch1; /* Clear Accumlators */ acc0 = 0; tapCnt = (srcBLen) >> 1u; while(tapCnt > 0u) { acc0 += (*pScr1++ * *pScr2++); acc0 += (*pScr1++ * *pScr2++); /* Decrement the loop counter */ tapCnt--; } tapCnt = (srcBLen) & 1u; /* apply same above for remaining samples of smaller length sequence */ while(tapCnt > 0u) { /* accumlate the results */ acc0 += (*pScr1++ * *pScr2++); /* Decrement the loop counter */ tapCnt--; } blkCnt--; /* Store the result in the accumulator in the destination buffer. */ *pOut++ = (q7_t) (__SSAT(acc0 >> 7u, 8)); /* Initialization of inputB pointer */ pScr2 = py; pScratch1 += 1u; } } /** * @} end of Conv group */
mit
mhdubose/Windows-universal-samples
gyrometer/cpp/scenario1_dataevents.xaml.cpp
24
5813
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario1_DataEvents.xaml.cpp // Implementation of the Scenario1_DataEvents class // #include "pch.h" #include "Scenario1_DataEvents.xaml.h" using namespace GyrometerCPP; using namespace SDKTemplate; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Devices::Sensors; using namespace Windows::Foundation; using namespace Windows::UI::Core; using namespace Platform; Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current), desiredReportInterval(0) { InitializeComponent(); gyrometer = Gyrometer::GetDefault(); if (gyrometer != nullptr) { // Select a report interval that is both suitable for the purposes of the app and supported by the sensor. // This value will be used later to activate the sensor. uint32 minReportInterval = gyrometer->MinimumReportInterval; desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16; } else { rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage); } } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e) { ScenarioEnableButton->IsEnabled = true; ScenarioDisableButton->IsEnabled = false; } /// <summary> /// Invoked when this page is no longer displayed. /// </summary> /// <param name="e"></param> void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e) { // If the navigation is external to the app do not clean up. // This can occur on Phone when suspending the app. if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr) { return; } if (ScenarioDisableButton->IsEnabled) { Window::Current->VisibilityChanged::remove(visibilityToken); gyrometer->ReadingChanged::remove(readingToken); // Restore the default report interval to release resources while the sensor is not in use gyrometer->ReportInterval = 0; } } /// <summary> /// This is the event handler for VisibilityChanged events. You would register for these notifications /// if handling sensor data when the app is not visible could cause unintended actions in the app. /// </summary> /// <param name="sender"></param> /// <param name="e"> /// Event data that can be examined for the current visibility state. /// </param> void Scenario1_DataEvents::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e) { // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate if (ScenarioDisableButton->IsEnabled) { if (e->Visible) { // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume) readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged)); } else { // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension) gyrometer->ReadingChanged::remove(readingToken); } } } void Scenario1_DataEvents::ReadingChanged(Gyrometer^ sender, GyrometerReadingChangedEventArgs^ e) { // We need to dispatch to the UI thread to display the output Dispatcher->RunAsync( CoreDispatcherPriority::Normal, ref new DispatchedHandler( [this, e]() { GyrometerReading^ reading = e->Reading; ScenarioOutput_X->Text = reading->AngularVelocityX.ToString(); ScenarioOutput_Y->Text = reading->AngularVelocityY.ToString(); ScenarioOutput_Z->Text = reading->AngularVelocityZ.ToString(); }, CallbackContext::Any ) ); } void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (gyrometer != nullptr) { // Establish the report interval gyrometer->ReportInterval = desiredReportInterval; visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::VisibilityChanged)); readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged)); ScenarioEnableButton->IsEnabled = false; ScenarioDisableButton->IsEnabled = true; } else { rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage); } } void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { Window::Current->VisibilityChanged::remove(visibilityToken); gyrometer->ReadingChanged::remove(readingToken); // Restore the default report interval to release resources while the sensor is not in use gyrometer->ReportInterval = 0; ScenarioEnableButton->IsEnabled = true; ScenarioDisableButton->IsEnabled = false; }
mit
Dilmacoin/dilmacoin
src/wallet.cpp
537
63585
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "crypter.h" #include "ui_interface.h" #include "base58.h" #include "coincontrol.h" #include <boost/algorithm/string/replace.hpp> using namespace std; ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey()); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); } return false; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { if (!IsLocked()) return false; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a private-key-encrypted wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { int64 nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (txin.prevout.n >= wtx.vout.size()) printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str()); else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { unsigned int latestNow = wtx.nTimeReceived; unsigned int latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64 latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64 nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime; wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else printf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString().c_str(), wtxIn.hashBlock.ToString().c_str()); } } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; #ifndef QT_GUI // If default receiving address gets used, replace it with a new one if (vchDefaultKey.IsValid()) { CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey, false)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } } #endif // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock) { { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } bool CWallet::EraseFromWallet(uint256 hash) { if (!fFileBacked) return false; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return true; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64 CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64 CWalletTx::GetTxTime() const { int64 n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<pair<CTxDestination, int64> >& listReceived, list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: int64 nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64 nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { CTxDestination address; vector<unsigned char> vchPubKey; if (!ExtractDestination(txout.scriptPubKey, address)) { printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); } // Don't report 'change' txouts if (nDebit > 0 && pwallet->IsChange(txout)) continue; if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); if (pwallet->IsMine(txout)) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nReceived, int64& nSent, int64& nFee) const { nReceived = nSent = nFee = 0; int64 allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount); if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions() { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else { continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { CBlock block; block.ReadFromDisk(pindex); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } void CWallet::ReacceptWalletTransactions() { bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; bool fMissing = false; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if (wtx.IsCoinBase() && wtx.IsSpent(0)) continue; CCoins coins; bool fUpdated = false; bool fFound = pcoinsTip->GetCoins(wtx.GetHash(), coins); if (fFound || wtx.GetDepthInMainChain() > 0) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat for (unsigned int i = 0; i < wtx.vout.size(); i++) { if (wtx.IsSpent(i)) continue; if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; fMissing = true; } } if (fUpdated) { printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!wtx.IsCoinBase()) wtx.AcceptWalletTransaction(false); } } if (fMissing) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::RelayWalletTransaction() { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { // Important: versions of bitcoin before 0.8.6 had a bug that inserted // empty transactions into the vtxPrev, which will cause the node to be // banned when retransmitted, hence the check for !tx.vin.empty() if (!tx.IsCoinBase() && !tx.vin.empty()) if (tx.GetDepthInMainChain() == 0) RelayTransaction((CTransaction)tx, tx.GetHash()); } if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); printf("Relaying wtx %s\n", hash.ToString().c_str()); RelayTransaction((CTransaction)*this, hash); } } } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64 nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64 nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); // Rebroadcast any of our txes that aren't in a block yet printf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64 CWallet::GetBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetUnconfirmedBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetImmatureBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const { vCoins.clear(); { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal()) continue; if (fOnlyConfirmed && !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue >= nMinimumInputValue && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain())); } } } } static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue, vector<char>& vfBest, int64& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64 nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; int64 nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; int64 n = pcoin->vout[i].nValue; pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64 nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } //// debug print printf("SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) printf("%s ", FormatMoney(vValue[i].first).c_str()); printf("total %s\n", FormatMoney(nBest).c_str()); } return true; } bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)); } bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); { nFeeRet = nTransactionFee; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust()) { strFailReason = _("Transaction amount too small"); return false; } wtxNew.vout.push_back(txout); } // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl)) { strFailReason = _("Insufficient funds"); return false; } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; //The priority after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1); } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least nMinTxFee // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < CTransaction::nMinTxFee && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, CTransaction::nMinTxFee - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange.SetDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust()) { nFeeRet += nChange; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1); wtxNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000); bool fAllowFree = CTransaction::AllowFree(dPriority); int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) { vector< pair<CScript, int64> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl); } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(true, false)) { // This must not fail. The transaction has already been signed and recorded. printf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64 nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); printf("SendMoney() : %s", strError.c_str()); return strError; } string strError; if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError)) { if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired).c_str()); printf("SendMoney() : %s\n", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired)) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); mapAddressBook[address] = strName; NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { mapAddressBook.erase(address); NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } void CWallet::PrintWallet(const CBlock& block) { { LOCK(cs_wallet); if (mapWallet.count(block.vtx[0].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); } } printf("\n"); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) { if (!pwallet->fFileBacked) return false; strWalletFileOut = pwallet->strWalletFile; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64 nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64 nKeys = max(GetArg("-keypool", 100), (int64)0); for (int i = 0; i < nKeys; i++) { int64 nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool() { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL); while (setKeyPool.size() < (nTargetSize + 1)) { int64 nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); printf("keypool reserve %"PRI64d"\n", nIndex); } } int64 CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64 nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64 nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } printf("keypool keep %"PRI64d"\n", nIndex); } void CWallet::ReturnKey(int64 nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } printf("keypool return %"PRI64d"\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse) { int64 nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (fAllowReuse && vchDefaultKey.IsValid()) { result = vchDefaultKey; return true; } if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64 CWallet::GetOldestKeyPoolTime() { int64 nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, int64> CWallet::GetAddressBalances() { map<CTxDestination, int64> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe() ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH(CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { if (pwallet->vchDefaultKey.IsValid()) { printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } else return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } } void CWallet::LockCoin(COutPoint& output) { setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } }
mit
Priya91/coreclr
src/pal/tests/palsuite/threading/WaitForMultipleObjectsEx/test1/test1.c
26
6088
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================ ** ** Source: test1.c ** ** Purpose: Test for WaitForMultipleObjectsEx. Call the function ** on an array of 4 events, and ensure that it returns correct ** results when we do so. ** ** **=========================================================*/ #include <palsuite.h> /* Originally written as WaitForMultipleObjects/test1 */ /* Number of events in array */ #define MAX_EVENTS 4 BOOL WaitForMultipleObjectsExTest() { BOOL bRet = TRUE; DWORD dwRet = 0; DWORD i = 0, j = 0; LPSECURITY_ATTRIBUTES lpEventAttributes = NULL; BOOL bManualReset = TRUE; BOOL bInitialState = TRUE; LPTSTR lpName[MAX_EVENTS]; HANDLE hEvent[MAX_EVENTS]; /* Run through this for loop and create 4 events */ for (i = 0; i < MAX_EVENTS; i++) { lpName[i] = (TCHAR*)malloc(MAX_PATH); sprintf(lpName[i],"Event #%d",i); hEvent[i] = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName[i]); if (hEvent[i] == INVALID_HANDLE_VALUE) { Trace("WaitForMultipleObjectsExTest:CreateEvent " "%s failed (%x)\n",lpName[i],GetLastError()); bRet = FALSE; break; } /* Set the current event */ bRet = SetEvent(hEvent[i]); if (!bRet) { Trace("WaitForMultipleObjectsExTest:SetEvent %s " "failed (%x)\n",lpName[i],GetLastError()); bRet = FALSE; break; } /* Ensure that this returns the correct value */ dwRet = WaitForSingleObject(hEvent[i],0); if (dwRet != WAIT_OBJECT_0) { Trace("WaitForMultipleObjectsExTest:WaitForSingleObject " "%s failed (%x)\n",lpName[i],GetLastError()); bRet = FALSE; break; } /* Reset the event, and again ensure that the return value of WaitForSingle is correct. */ bRet = ResetEvent(hEvent[i]); if (!bRet) { Trace("WaitForMultipleObjectsExTest:ResetEvent %s " "failed (%x)\n",lpName[i],GetLastError()); bRet = FALSE; break; } dwRet = WaitForSingleObject(hEvent[i],0); if (dwRet != WAIT_TIMEOUT) { Trace("WaitForMultipleObjectsExTest:WaitForSingleObject " "%s failed (%x)\n",lpName[i],GetLastError()); bRet = FALSE; break; } } /* * If the first section of the test passed, move on to the * second. */ if (bRet) { BOOL bWaitAll = TRUE; DWORD nCount = MAX_EVENTS; CONST HANDLE *lpHandles = &hEvent[0]; /* Call WaitForMultipleObjectsEx on all the events, the return should be WAIT_TIMEOUT */ dwRet = WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, 0, FALSE); if (dwRet != WAIT_TIMEOUT) { Trace("WaitForMultipleObjectsExTest: WaitForMultipleObjectsEx " "%s failed (%x)\n",lpName[0],GetLastError()); } else { /* Step through each event and one at a time, set the currect test, while reseting all the other tests */ for (i = 0; i < MAX_EVENTS; i++) { for (j = 0; j < MAX_EVENTS; j++) { if (j == i) { bRet = SetEvent(hEvent[j]); if (!bRet) { Trace("WaitForMultipleObjectsExTest:SetEvent " "%s failed (%x)\n", lpName[j],GetLastError()); break; } } else { bRet = ResetEvent(hEvent[j]); if (!bRet) { Trace("WaitForMultipleObjectsExTest:ResetEvent " "%s failed (%x)\n", lpName[j],GetLastError()); } } } bWaitAll = FALSE; /* Check that WaitFor returns WAIT_OBJECT + i */ dwRet = WaitForMultipleObjectsEx( nCount, lpHandles, bWaitAll, 0, FALSE); if (dwRet != WAIT_OBJECT_0+i) { Trace("WaitForMultipleObjectsExTest: " "WaitForMultipleObjectsEx %s failed (%x)\n", lpName[0],GetLastError()); bRet = FALSE; break; } } } for (i = 0; i < MAX_EVENTS; i++) { bRet = CloseHandle(hEvent[i]); if (!bRet) { Trace("WaitForMultipleObjectsExTest:CloseHandle %s " "failed (%x)\n",lpName[i],GetLastError()); } free((void*)lpName[i]); } } return bRet; } int __cdecl main(int argc, char **argv) { if(0 != (PAL_Initialize(argc, argv))) { return ( FAIL ); } if(!WaitForMultipleObjectsExTest()) { Fail ("Test failed\n"); } PAL_Terminate(); return PASS; }
mit
eiffelqiu/candle
lib/candle/generators/lua/wax/lib/lua/lapi.c
27
22717
/* ** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $ ** Lua API ** See Copyright Notice in lua.h */ #include <assert.h> #include <math.h> #include <stdarg.h> #include <string.h> #define lapi_c #define LUA_CORE #include "lua.h" #include "lapi.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lundump.h" #include "lvm.h" const char lua_ident[] = "$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n" "$Authors: " LUA_AUTHORS " $\n" "$URL: www.lua.org $\n"; #define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base)) #define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject) #define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;} static TValue *index2adr (lua_State *L, int idx) { if (idx > 0) { TValue *o = L->base + (idx - 1); api_check(L, idx <= L->ci->top - L->base); if (o >= L->top) return cast(TValue *, luaO_nilobject); else return o; } else if (idx > LUA_REGISTRYINDEX) { api_check(L, idx != 0 && -idx <= L->top - L->base); return L->top + idx; } else switch (idx) { /* pseudo-indices */ case LUA_REGISTRYINDEX: return registry(L); case LUA_ENVIRONINDEX: { Closure *func = curr_func(L); sethvalue(L, &L->env, func->c.env); return &L->env; } case LUA_GLOBALSINDEX: return gt(L); default: { Closure *func = curr_func(L); idx = LUA_GLOBALSINDEX - idx; return (idx <= func->c.nupvalues) ? &func->c.upvalue[idx-1] : cast(TValue *, luaO_nilobject); } } } static Table *getcurrenv (lua_State *L) { if (L->ci == L->base_ci) /* no enclosing function? */ return hvalue(gt(L)); /* use global table as environment */ else { Closure *func = curr_func(L); return func->c.env; } } void luaA_pushobject (lua_State *L, const TValue *o) { setobj2s(L, L->top, o); api_incr_top(L); } LUA_API int lua_checkstack (lua_State *L, int size) { int res = 1; lua_lock(L); if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK) res = 0; /* stack overflow */ else if (size > 0) { luaD_checkstack(L, size); if (L->ci->top < L->top + size) L->ci->top = L->top + size; } lua_unlock(L); return res; } LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { int i; if (from == to) return; lua_lock(to); api_checknelems(from, n); api_check(from, G(from) == G(to)); api_check(from, to->ci->top - to->top >= n); from->top -= n; for (i = 0; i < n; i++) { setobj2s(to, to->top++, from->top + i); } lua_unlock(to); } LUA_API void lua_setlevel (lua_State *from, lua_State *to) { to->nCcalls = from->nCcalls; } LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { lua_CFunction old; lua_lock(L); old = G(L)->panic; G(L)->panic = panicf; lua_unlock(L); return old; } LUA_API lua_State *lua_newthread (lua_State *L) { lua_State *L1; lua_lock(L); luaC_checkGC(L); L1 = luaE_newthread(L); setthvalue(L, L->top, L1); api_incr_top(L); lua_unlock(L); luai_userstatethread(L, L1); return L1; } /* ** basic stack manipulation */ LUA_API int lua_gettop (lua_State *L) { return cast_int(L->top - L->base); } LUA_API void lua_settop (lua_State *L, int idx) { lua_lock(L); if (idx >= 0) { api_check(L, idx <= L->stack_last - L->base); while (L->top < L->base + idx) setnilvalue(L->top++); L->top = L->base + idx; } else { api_check(L, -(idx+1) <= (L->top - L->base)); L->top += idx+1; /* `subtract' index (index is negative) */ } lua_unlock(L); } LUA_API void lua_remove (lua_State *L, int idx) { StkId p; lua_lock(L); p = index2adr(L, idx); api_checkvalidindex(L, p); while (++p < L->top) setobjs2s(L, p-1, p); L->top--; lua_unlock(L); } LUA_API void lua_insert (lua_State *L, int idx) { StkId p; StkId q; lua_lock(L); p = index2adr(L, idx); api_checkvalidindex(L, p); for (q = L->top; q>p; q--) setobjs2s(L, q, q-1); setobjs2s(L, p, L->top); lua_unlock(L); } LUA_API void lua_replace (lua_State *L, int idx) { StkId o; lua_lock(L); /* explicit test for incompatible code */ if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci) luaG_runerror(L, "no calling environment"); api_checknelems(L, 1); o = index2adr(L, idx); api_checkvalidindex(L, o); if (idx == LUA_ENVIRONINDEX) { Closure *func = curr_func(L); api_check(L, ttistable(L->top - 1)); func->c.env = hvalue(L->top - 1); luaC_barrier(L, func, L->top - 1); } else { setobj(L, o, L->top - 1); if (idx < LUA_GLOBALSINDEX) /* function upvalue? */ luaC_barrier(L, curr_func(L), L->top - 1); } L->top--; lua_unlock(L); } LUA_API void lua_pushvalue (lua_State *L, int idx) { lua_lock(L); setobj2s(L, L->top, index2adr(L, idx)); api_incr_top(L); lua_unlock(L); } /* ** access functions (stack -> C) */ LUA_API int lua_type (lua_State *L, int idx) { StkId o = index2adr(L, idx); return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); } LUA_API const char *lua_typename (lua_State *L, int t) { UNUSED(L); return (t == LUA_TNONE) ? "no value" : luaT_typenames[t]; } LUA_API int lua_iscfunction (lua_State *L, int idx) { StkId o = index2adr(L, idx); return iscfunction(o); } LUA_API int lua_isnumber (lua_State *L, int idx) { TValue n; const TValue *o = index2adr(L, idx); return tonumber(o, &n); } LUA_API int lua_isstring (lua_State *L, int idx) { int t = lua_type(L, idx); return (t == LUA_TSTRING || t == LUA_TNUMBER); } LUA_API int lua_isuserdata (lua_State *L, int idx) { const TValue *o = index2adr(L, idx); return (ttisuserdata(o) || ttislightuserdata(o)); } LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { StkId o1 = index2adr(L, index1); StkId o2 = index2adr(L, index2); return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaO_rawequalObj(o1, o2); } LUA_API int lua_equal (lua_State *L, int index1, int index2) { StkId o1, o2; int i; lua_lock(L); /* may call tag method */ o1 = index2adr(L, index1); o2 = index2adr(L, index2); i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); lua_unlock(L); return i; } LUA_API int lua_lessthan (lua_State *L, int index1, int index2) { StkId o1, o2; int i; lua_lock(L); /* may call tag method */ o1 = index2adr(L, index1); o2 = index2adr(L, index2); i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaV_lessthan(L, o1, o2); lua_unlock(L); return i; } LUA_API lua_Number lua_tonumber (lua_State *L, int idx) { TValue n; const TValue *o = index2adr(L, idx); if (tonumber(o, &n)) return nvalue(o); else return 0; } LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) { TValue n; const TValue *o = index2adr(L, idx); if (tonumber(o, &n)) { lua_Integer res; lua_Number num = nvalue(o); lua_number2integer(res, num); return res; } else return 0; } LUA_API int lua_toboolean (lua_State *L, int idx) { const TValue *o = index2adr(L, idx); return !l_isfalse(o); } LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { StkId o = index2adr(L, idx); if (!ttisstring(o)) { lua_lock(L); /* `luaV_tostring' may create a new string */ if (!luaV_tostring(L, o)) { /* conversion failed? */ if (len != NULL) *len = 0; lua_unlock(L); return NULL; } luaC_checkGC(L); o = index2adr(L, idx); /* previous call may reallocate the stack */ lua_unlock(L); } if (len != NULL) *len = tsvalue(o)->len; return svalue(o); } LUA_API size_t lua_objlen (lua_State *L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TSTRING: return tsvalue(o)->len; case LUA_TUSERDATA: return uvalue(o)->len; case LUA_TTABLE: return luaH_getn(hvalue(o)); case LUA_TNUMBER: { size_t l; lua_lock(L); /* `luaV_tostring' may create a new string */ l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0); lua_unlock(L); return l; } default: return 0; } } LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { StkId o = index2adr(L, idx); return (!iscfunction(o)) ? NULL : clvalue(o)->c.f; } LUA_API void *lua_touserdata (lua_State *L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TUSERDATA: return (rawuvalue(o) + 1); case LUA_TLIGHTUSERDATA: return pvalue(o); default: return NULL; } } LUA_API lua_State *lua_tothread (lua_State *L, int idx) { StkId o = index2adr(L, idx); return (!ttisthread(o)) ? NULL : thvalue(o); } LUA_API const void *lua_topointer (lua_State *L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TTABLE: return hvalue(o); case LUA_TFUNCTION: return clvalue(o); case LUA_TTHREAD: return thvalue(o); case LUA_TUSERDATA: case LUA_TLIGHTUSERDATA: return lua_touserdata(L, idx); default: return NULL; } } /* ** push functions (C -> stack) */ LUA_API void lua_pushnil (lua_State *L) { lua_lock(L); setnilvalue(L->top); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { lua_lock(L); setnvalue(L->top, n); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { lua_lock(L); setnvalue(L->top, cast_num(n)); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { lua_lock(L); luaC_checkGC(L); setsvalue2s(L, L->top, luaS_newlstr(L, s, len)); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushstring (lua_State *L, const char *s) { if (s == NULL) lua_pushnil(L); else lua_pushlstring(L, s, strlen(s)); } LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp) { const char *ret; lua_lock(L); luaC_checkGC(L); ret = luaO_pushvfstring(L, fmt, argp); lua_unlock(L); return ret; } LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { const char *ret; va_list argp; lua_lock(L); luaC_checkGC(L); va_start(argp, fmt); ret = luaO_pushvfstring(L, fmt, argp); va_end(argp); lua_unlock(L); return ret; } LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { Closure *cl; lua_lock(L); luaC_checkGC(L); api_checknelems(L, n); cl = luaF_newCclosure(L, n, getcurrenv(L)); cl->c.f = fn; L->top -= n; while (n--) setobj2n(L, &cl->c.upvalue[n], L->top+n); setclvalue(L, L->top, cl); lua_assert(iswhite(obj2gco(cl))); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushboolean (lua_State *L, int b) { lua_lock(L); setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { lua_lock(L); setpvalue(L->top, p); api_incr_top(L); lua_unlock(L); } LUA_API int lua_pushthread (lua_State *L) { lua_lock(L); setthvalue(L, L->top, L); api_incr_top(L); lua_unlock(L); return (G(L)->mainthread == L); } /* ** get functions (Lua -> stack) */ LUA_API void lua_gettable (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2adr(L, idx); api_checkvalidindex(L, t); luaV_gettable(L, t, L->top - 1, L->top - 1); lua_unlock(L); } LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { StkId t; TValue key; lua_lock(L); t = index2adr(L, idx); api_checkvalidindex(L, t); setsvalue(L, &key, luaS_new(L, k)); luaV_gettable(L, t, &key, L->top); api_incr_top(L); lua_unlock(L); } LUA_API void lua_rawget (lua_State *L, int idx) { StkId t; lua_lock(L); t = index2adr(L, idx); api_check(L, ttistable(t)); setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); lua_unlock(L); } LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { StkId o; lua_lock(L); o = index2adr(L, idx); api_check(L, ttistable(o)); setobj2s(L, L->top, luaH_getnum(hvalue(o), n)); api_incr_top(L); lua_unlock(L); } LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { lua_lock(L); luaC_checkGC(L); sethvalue(L, L->top, luaH_new(L, narray, nrec)); api_incr_top(L); lua_unlock(L); } LUA_API int lua_getmetatable (lua_State *L, int objindex) { const TValue *obj; Table *mt = NULL; int res; lua_lock(L); obj = index2adr(L, objindex); switch (ttype(obj)) { case LUA_TTABLE: mt = hvalue(obj)->metatable; break; case LUA_TUSERDATA: mt = uvalue(obj)->metatable; break; default: mt = G(L)->mt[ttype(obj)]; break; } if (mt == NULL) res = 0; else { sethvalue(L, L->top, mt); api_incr_top(L); res = 1; } lua_unlock(L); return res; } LUA_API void lua_getfenv (lua_State *L, int idx) { StkId o; lua_lock(L); o = index2adr(L, idx); api_checkvalidindex(L, o); switch (ttype(o)) { case LUA_TFUNCTION: sethvalue(L, L->top, clvalue(o)->c.env); break; case LUA_TUSERDATA: sethvalue(L, L->top, uvalue(o)->env); break; case LUA_TTHREAD: setobj2s(L, L->top, gt(thvalue(o))); break; default: setnilvalue(L->top); break; } api_incr_top(L); lua_unlock(L); } /* ** set functions (stack -> Lua) */ LUA_API void lua_settable (lua_State *L, int idx) { StkId t; lua_lock(L); api_checknelems(L, 2); t = index2adr(L, idx); api_checkvalidindex(L, t); luaV_settable(L, t, L->top - 2, L->top - 1); L->top -= 2; /* pop index and value */ lua_unlock(L); } LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { StkId t; TValue key; lua_lock(L); api_checknelems(L, 1); t = index2adr(L, idx); api_checkvalidindex(L, t); setsvalue(L, &key, luaS_new(L, k)); luaV_settable(L, t, &key, L->top - 1); L->top--; /* pop value */ lua_unlock(L); } LUA_API void lua_rawset (lua_State *L, int idx) { StkId t; lua_lock(L); api_checknelems(L, 2); t = index2adr(L, idx); api_check(L, ttistable(t)); setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); luaC_barriert(L, hvalue(t), L->top-1); L->top -= 2; lua_unlock(L); } LUA_API void lua_rawseti (lua_State *L, int idx, int n) { StkId o; lua_lock(L); api_checknelems(L, 1); o = index2adr(L, idx); api_check(L, ttistable(o)); setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1); luaC_barriert(L, hvalue(o), L->top-1); L->top--; lua_unlock(L); } LUA_API int lua_setmetatable (lua_State *L, int objindex) { TValue *obj; Table *mt; lua_lock(L); api_checknelems(L, 1); obj = index2adr(L, objindex); api_checkvalidindex(L, obj); if (ttisnil(L->top - 1)) mt = NULL; else { api_check(L, ttistable(L->top - 1)); mt = hvalue(L->top - 1); } switch (ttype(obj)) { case LUA_TTABLE: { hvalue(obj)->metatable = mt; if (mt) luaC_objbarriert(L, hvalue(obj), mt); break; } case LUA_TUSERDATA: { uvalue(obj)->metatable = mt; if (mt) luaC_objbarrier(L, rawuvalue(obj), mt); break; } default: { G(L)->mt[ttype(obj)] = mt; break; } } L->top--; lua_unlock(L); return 1; } LUA_API int lua_setfenv (lua_State *L, int idx) { StkId o; int res = 1; lua_lock(L); api_checknelems(L, 1); o = index2adr(L, idx); api_checkvalidindex(L, o); api_check(L, ttistable(L->top - 1)); switch (ttype(o)) { case LUA_TFUNCTION: clvalue(o)->c.env = hvalue(L->top - 1); break; case LUA_TUSERDATA: uvalue(o)->env = hvalue(L->top - 1); break; case LUA_TTHREAD: sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1)); break; default: res = 0; break; } if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); L->top--; lua_unlock(L); return res; } /* ** `load' and `call' functions (run Lua code) */ #define adjustresults(L,nres) \ { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; } #define checkresults(L,na,nr) \ api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na))) LUA_API void lua_call (lua_State *L, int nargs, int nresults) { StkId func; lua_lock(L); api_checknelems(L, nargs+1); checkresults(L, nargs, nresults); func = L->top - (nargs+1); luaD_call(L, func, nresults); adjustresults(L, nresults); lua_unlock(L); } /* ** Execute a protected call. */ struct CallS { /* data to `f_call' */ StkId func; int nresults; }; static void f_call (lua_State *L, void *ud) { struct CallS *c = cast(struct CallS *, ud); luaD_call(L, c->func, c->nresults); } LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) { struct CallS c; int status; ptrdiff_t func; lua_lock(L); api_checknelems(L, nargs+1); checkresults(L, nargs, nresults); if (errfunc == 0) func = 0; else { StkId o = index2adr(L, errfunc); api_checkvalidindex(L, o); func = savestack(L, o); } c.func = L->top - (nargs+1); /* function to be called */ c.nresults = nresults; status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); adjustresults(L, nresults); lua_unlock(L); return status; } /* ** Execute a protected C call. */ struct CCallS { /* data to `f_Ccall' */ lua_CFunction func; void *ud; }; static void f_Ccall (lua_State *L, void *ud) { struct CCallS *c = cast(struct CCallS *, ud); Closure *cl; cl = luaF_newCclosure(L, 0, getcurrenv(L)); cl->c.f = c->func; setclvalue(L, L->top, cl); /* push function */ api_incr_top(L); setpvalue(L->top, c->ud); /* push only argument */ api_incr_top(L); luaD_call(L, L->top - 2, 0); } LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) { struct CCallS c; int status; lua_lock(L); c.func = func; c.ud = ud; status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0); lua_unlock(L); return status; } LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname) { ZIO z; int status; lua_lock(L); if (!chunkname) chunkname = "?"; luaZ_init(L, &z, reader, data); status = luaD_protectedparser(L, &z, chunkname); lua_unlock(L); return status; } LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { int status; TValue *o; lua_lock(L); api_checknelems(L, 1); o = L->top - 1; if (isLfunction(o)) status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0); else status = 1; lua_unlock(L); return status; } LUA_API int lua_status (lua_State *L) { return L->status; } /* ** Garbage-collection function */ LUA_API int lua_gc (lua_State *L, int what, int data) { int res = 0; global_State *g; lua_lock(L); g = G(L); switch (what) { case LUA_GCSTOP: { g->GCthreshold = MAX_LUMEM; break; } case LUA_GCRESTART: { g->GCthreshold = g->totalbytes; break; } case LUA_GCCOLLECT: { luaC_fullgc(L); break; } case LUA_GCCOUNT: { /* GC values are expressed in Kbytes: #bytes/2^10 */ res = cast_int(g->totalbytes >> 10); break; } case LUA_GCCOUNTB: { res = cast_int(g->totalbytes & 0x3ff); break; } case LUA_GCSTEP: { lu_mem a = (cast(lu_mem, data) << 10); if (a <= g->totalbytes) g->GCthreshold = g->totalbytes - a; else g->GCthreshold = 0; while (g->GCthreshold <= g->totalbytes) { luaC_step(L); if (g->gcstate == GCSpause) { /* end of cycle? */ res = 1; /* signal it */ break; } } break; } case LUA_GCSETPAUSE: { res = g->gcpause; g->gcpause = data; break; } case LUA_GCSETSTEPMUL: { res = g->gcstepmul; g->gcstepmul = data; break; } default: res = -1; /* invalid option */ } lua_unlock(L); return res; } /* ** miscellaneous functions */ LUA_API int lua_error (lua_State *L) { lua_lock(L); api_checknelems(L, 1); luaG_errormsg(L); lua_unlock(L); return 0; /* to avoid warnings */ } LUA_API int lua_next (lua_State *L, int idx) { StkId t; int more; lua_lock(L); t = index2adr(L, idx); api_check(L, ttistable(t)); more = luaH_next(L, hvalue(t), L->top - 1); if (more) { api_incr_top(L); } else /* no more elements */ L->top -= 1; /* remove key */ lua_unlock(L); return more; } LUA_API void lua_concat (lua_State *L, int n) { lua_lock(L); api_checknelems(L, n); if (n >= 2) { luaC_checkGC(L); luaV_concat(L, n, cast_int(L->top - L->base) - 1); L->top -= (n-1); } else if (n == 0) { /* push empty string */ setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); api_incr_top(L); } /* else n == 1; nothing to do */ lua_unlock(L); } LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { lua_Alloc f; lua_lock(L); if (ud) *ud = G(L)->ud; f = G(L)->frealloc; lua_unlock(L); return f; } LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { lua_lock(L); G(L)->ud = ud; G(L)->frealloc = f; lua_unlock(L); } LUA_API void *lua_newuserdata (lua_State *L, size_t size) { Udata *u; lua_lock(L); luaC_checkGC(L); u = luaS_newudata(L, size, getcurrenv(L)); setuvalue(L, L->top, u); api_incr_top(L); lua_unlock(L); return u + 1; } static const char *aux_upvalue (StkId fi, int n, TValue **val) { Closure *f; if (!ttisfunction(fi)) return NULL; f = clvalue(fi); if (f->c.isC) { if (!(1 <= n && n <= f->c.nupvalues)) return NULL; *val = &f->c.upvalue[n-1]; return ""; } else { Proto *p = f->l.p; if (!(1 <= n && n <= p->sizeupvalues)) return NULL; *val = f->l.upvals[n-1]->v; return getstr(p->upvalues[n-1]); } } LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val; lua_lock(L); name = aux_upvalue(index2adr(L, funcindex), n, &val); if (name) { setobj2s(L, L->top, val); api_incr_top(L); } lua_unlock(L); return name; } LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val; StkId fi; lua_lock(L); fi = index2adr(L, funcindex); api_checknelems(L, 1); name = aux_upvalue(fi, n, &val); if (name) { L->top--; setobj(L, val, L->top); luaC_barrier(L, clvalue(fi), L->top); } lua_unlock(L); return name; }
mit
dawnoble/slimdx
source/direct3d9/BandwidthTimings.cpp
27
3034
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <d3d9.h> #include <d3dx9.h> #include "BandwidthTimings.h" using namespace System; namespace SlimDX { namespace Direct3D9 { bool BandwidthTimings::operator == ( BandwidthTimings left, BandwidthTimings right ) { return BandwidthTimings::Equals( left, right ); } bool BandwidthTimings::operator != ( BandwidthTimings left, BandwidthTimings right ) { return !BandwidthTimings::Equals( left, right ); } int BandwidthTimings::GetHashCode() { return MaximumBandwidthUtilized.GetHashCode() + FrontEndUploadMemoryUtilizedPercent.GetHashCode() + VertexRateUtilizedPercent.GetHashCode() + TriangleSetupRateUtilizedPercent.GetHashCode() + FillRateUtilizedPercent.GetHashCode(); } bool BandwidthTimings::Equals( Object^ value ) { if( value == nullptr ) return false; if( value->GetType() != GetType() ) return false; return Equals( safe_cast<BandwidthTimings>( value ) ); } bool BandwidthTimings::Equals( BandwidthTimings value ) { return ( MaximumBandwidthUtilized == value.MaximumBandwidthUtilized && FrontEndUploadMemoryUtilizedPercent == value.FrontEndUploadMemoryUtilizedPercent && VertexRateUtilizedPercent == value.VertexRateUtilizedPercent && TriangleSetupRateUtilizedPercent == value.TriangleSetupRateUtilizedPercent && FillRateUtilizedPercent == value.FillRateUtilizedPercent ); } bool BandwidthTimings::Equals( BandwidthTimings% value1, BandwidthTimings% value2 ) { return ( value1.MaximumBandwidthUtilized == value2.MaximumBandwidthUtilized && value1.FrontEndUploadMemoryUtilizedPercent == value2.FrontEndUploadMemoryUtilizedPercent && value1.VertexRateUtilizedPercent == value2.VertexRateUtilizedPercent && value1.TriangleSetupRateUtilizedPercent == value2.TriangleSetupRateUtilizedPercent && value1.FillRateUtilizedPercent == value2.FillRateUtilizedPercent ); } } }
mit
quabug/godot
servers/physics/broad_phase_sw.cpp
28
2253
/*************************************************************************/ /* broad_phase_sw.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "broad_phase_sw.h" BroadPhaseSW::CreateFunction BroadPhaseSW::create_func=NULL; BroadPhaseSW::~BroadPhaseSW() { }
mit
atgreen/bitcoin
src/qt/peertablemodel.cpp
30
6256
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "peertablemodel.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "sync.h" #include <QDebug> #include <QList> #include <QTimer> bool NodeLessThan::operator()(const CNodeCombinedStats &left, const CNodeCombinedStats &right) const { const CNodeStats *pLeft = &(left.nodeStats); const CNodeStats *pRight = &(right.nodeStats); if (order == Qt::DescendingOrder) std::swap(pLeft, pRight); switch(column) { case PeerTableModel::Address: return pLeft->addrName.compare(pRight->addrName) < 0; case PeerTableModel::Subversion: return pLeft->cleanSubVer.compare(pRight->cleanSubVer) < 0; case PeerTableModel::Ping: return pLeft->dPingTime < pRight->dPingTime; } return false; } // private implementation class PeerTablePriv { public: /** Local cache of peer information */ QList<CNodeCombinedStats> cachedNodeStats; /** Column to sort nodes by */ int sortColumn; /** Order (ascending or descending) to sort nodes by */ Qt::SortOrder sortOrder; /** Index of rows by node ID */ std::map<NodeId, int> mapNodeRows; /** Pull a full list of peers from vNodes into our cache */ void refreshPeers() { { TRY_LOCK(cs_vNodes, lockNodes); if (!lockNodes) { // skip the refresh if we can't immediately get the lock return; } cachedNodeStats.clear(); #if QT_VERSION >= 0x040700 cachedNodeStats.reserve(vNodes.size()); #endif Q_FOREACH (CNode* pnode, vNodes) { CNodeCombinedStats stats; stats.nodeStateStats.nMisbehavior = 0; stats.nodeStateStats.nSyncHeight = -1; stats.nodeStateStats.nCommonHeight = -1; stats.fNodeStateStatsAvailable = false; pnode->copyStats(stats.nodeStats); cachedNodeStats.append(stats); } } // Try to retrieve the CNodeStateStats for each node. { TRY_LOCK(cs_main, lockMain); if (lockMain) { BOOST_FOREACH(CNodeCombinedStats &stats, cachedNodeStats) stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats); } } if (sortColumn >= 0) // sort cacheNodeStats (use stable sort to prevent rows jumping around unneceesarily) qStableSort(cachedNodeStats.begin(), cachedNodeStats.end(), NodeLessThan(sortColumn, sortOrder)); // build index map mapNodeRows.clear(); int row = 0; Q_FOREACH (const CNodeCombinedStats& stats, cachedNodeStats) mapNodeRows.insert(std::pair<NodeId, int>(stats.nodeStats.nodeid, row++)); } int size() const { return cachedNodeStats.size(); } CNodeCombinedStats *index(int idx) { if (idx >= 0 && idx < cachedNodeStats.size()) return &cachedNodeStats[idx]; return 0; } }; PeerTableModel::PeerTableModel(ClientModel *parent) : QAbstractTableModel(parent), clientModel(parent), timer(0) { columns << tr("Node/Service") << tr("User Agent") << tr("Ping Time"); priv = new PeerTablePriv(); // default to unsorted priv->sortColumn = -1; // set up timer for auto refresh timer = new QTimer(); connect(timer, SIGNAL(timeout()), SLOT(refresh())); timer->setInterval(MODEL_UPDATE_DELAY); // load initial data refresh(); } void PeerTableModel::startAutoRefresh() { timer->start(); } void PeerTableModel::stopAutoRefresh() { timer->stop(); } int PeerTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int PeerTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length();; } QVariant PeerTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); CNodeCombinedStats *rec = static_cast<CNodeCombinedStats*>(index.internalPointer()); if (role == Qt::DisplayRole) { switch(index.column()) { case Address: return QString::fromStdString(rec->nodeStats.addrName); case Subversion: return QString::fromStdString(rec->nodeStats.cleanSubVer); case Ping: return GUIUtil::formatPingTime(rec->nodeStats.dPingTime); } } else if (role == Qt::TextAlignmentRole) { if (index.column() == Ping) return (QVariant)(Qt::AlignRight | Qt::AlignVCenter); } return QVariant(); } QVariant PeerTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags PeerTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; return retval; } QModelIndex PeerTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); CNodeCombinedStats *data = priv->index(row); if (data) return createIndex(row, column, data); return QModelIndex(); } const CNodeCombinedStats *PeerTableModel::getNodeStats(int idx) { return priv->index(idx); } void PeerTableModel::refresh() { Q_EMIT layoutAboutToBeChanged(); priv->refreshPeers(); Q_EMIT layoutChanged(); } int PeerTableModel::getRowByNodeId(NodeId nodeid) { std::map<NodeId, int>::iterator it = priv->mapNodeRows.find(nodeid); if (it == priv->mapNodeRows.end()) return -1; return it->second; } void PeerTableModel::sort(int column, Qt::SortOrder order) { priv->sortColumn = column; priv->sortOrder = order; refresh(); }
mit
jjimenezg93/ai-state_machines
moai/3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.cpp
30
16669
/* * Copyright (c) 2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/b2DynamicTree.h> #include <cstring> #include <cfloat> using namespace std; b2DynamicTree::b2DynamicTree() { m_root = b2_nullNode; m_nodeCapacity = 16; m_nodeCount = 0; m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); // Build a linked list for the free list. for (int32 i = 0; i < m_nodeCapacity - 1; ++i) { m_nodes[i].next = i + 1; m_nodes[i].height = -1; } m_nodes[m_nodeCapacity-1].next = b2_nullNode; m_nodes[m_nodeCapacity-1].height = -1; m_freeList = 0; m_path = 0; m_insertionCount = 0; } b2DynamicTree::~b2DynamicTree() { // This frees the entire tree in one shot. b2Free(m_nodes); } // Allocate a node from the pool. Grow the pool if necessary. int32 b2DynamicTree::AllocateNode() { // Expand the node pool as needed. if (m_freeList == b2_nullNode) { b2Assert(m_nodeCount == m_nodeCapacity); // The free list is empty. Rebuild a bigger pool. b2TreeNode* oldNodes = m_nodes; m_nodeCapacity *= 2; m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); b2Free(oldNodes); // Build a linked list for the free list. The parent // pointer becomes the "next" pointer. for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) { m_nodes[i].next = i + 1; m_nodes[i].height = -1; } m_nodes[m_nodeCapacity-1].next = b2_nullNode; m_nodes[m_nodeCapacity-1].height = -1; m_freeList = m_nodeCount; } // Peel a node off the free list. int32 nodeId = m_freeList; m_freeList = m_nodes[nodeId].next; m_nodes[nodeId].parent = b2_nullNode; m_nodes[nodeId].child1 = b2_nullNode; m_nodes[nodeId].child2 = b2_nullNode; m_nodes[nodeId].height = 0; m_nodes[nodeId].userData = NULL; ++m_nodeCount; return nodeId; } // Return a node to the pool. void b2DynamicTree::FreeNode(int32 nodeId) { b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); b2Assert(0 < m_nodeCount); m_nodes[nodeId].next = m_freeList; m_nodes[nodeId].height = -1; m_freeList = nodeId; --m_nodeCount; } // Create a proxy in the tree as a leaf node. We return the index // of the node instead of a pointer so that we can grow // the node pool. int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) { int32 proxyId = AllocateNode(); // Fatten the aabb. b2Vec2 r(b2_aabbExtension, b2_aabbExtension); m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; m_nodes[proxyId].userData = userData; m_nodes[proxyId].height = 0; InsertLeaf(proxyId); return proxyId; } void b2DynamicTree::DestroyProxy(int32 proxyId) { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); b2Assert(m_nodes[proxyId].IsLeaf()); RemoveLeaf(proxyId); FreeNode(proxyId); } bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); b2Assert(m_nodes[proxyId].IsLeaf()); if (m_nodes[proxyId].aabb.Contains(aabb)) { return false; } RemoveLeaf(proxyId); // Extend AABB. b2AABB b = aabb; b2Vec2 r(b2_aabbExtension, b2_aabbExtension); b.lowerBound = b.lowerBound - r; b.upperBound = b.upperBound + r; // Predict AABB displacement. b2Vec2 d = b2_aabbMultiplier * displacement; if (d.x < 0.0f) { b.lowerBound.x += d.x; } else { b.upperBound.x += d.x; } if (d.y < 0.0f) { b.lowerBound.y += d.y; } else { b.upperBound.y += d.y; } m_nodes[proxyId].aabb = b; InsertLeaf(proxyId); return true; } void b2DynamicTree::InsertLeaf(int32 leaf) { ++m_insertionCount; if (m_root == b2_nullNode) { m_root = leaf; m_nodes[m_root].parent = b2_nullNode; return; } // Find the best sibling for this node b2AABB leafAABB = m_nodes[leaf].aabb; int32 index = m_root; while (m_nodes[index].IsLeaf() == false) { int32 child1 = m_nodes[index].child1; int32 child2 = m_nodes[index].child2; float32 area = m_nodes[index].aabb.GetPerimeter(); b2AABB combinedAABB; combinedAABB.Combine(m_nodes[index].aabb, leafAABB); float32 combinedArea = combinedAABB.GetPerimeter(); // Cost of creating a new parent for this node and the new leaf float32 cost = 2.0f * combinedArea; // Minimum cost of pushing the leaf further down the tree float32 inheritanceCost = 2.0f * (combinedArea - area); // Cost of descending into child1 float32 cost1; if (m_nodes[child1].IsLeaf()) { b2AABB aabb; aabb.Combine(leafAABB, m_nodes[child1].aabb); cost1 = aabb.GetPerimeter() + inheritanceCost; } else { b2AABB aabb; aabb.Combine(leafAABB, m_nodes[child1].aabb); float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); float32 newArea = aabb.GetPerimeter(); cost1 = (newArea - oldArea) + inheritanceCost; } // Cost of descending into child2 float32 cost2; if (m_nodes[child2].IsLeaf()) { b2AABB aabb; aabb.Combine(leafAABB, m_nodes[child2].aabb); cost2 = aabb.GetPerimeter() + inheritanceCost; } else { b2AABB aabb; aabb.Combine(leafAABB, m_nodes[child2].aabb); float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); float32 newArea = aabb.GetPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } // Descend according to the minimum cost. if (cost < cost1 && cost < cost2) { break; } // Descend if (cost1 < cost2) { index = child1; } else { index = child2; } } int32 sibling = index; // Create a new parent. int32 oldParent = m_nodes[sibling].parent; int32 newParent = AllocateNode(); m_nodes[newParent].parent = oldParent; m_nodes[newParent].userData = NULL; m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); m_nodes[newParent].height = m_nodes[sibling].height + 1; if (oldParent != b2_nullNode) { // The sibling was not the root. if (m_nodes[oldParent].child1 == sibling) { m_nodes[oldParent].child1 = newParent; } else { m_nodes[oldParent].child2 = newParent; } m_nodes[newParent].child1 = sibling; m_nodes[newParent].child2 = leaf; m_nodes[sibling].parent = newParent; m_nodes[leaf].parent = newParent; } else { // The sibling was the root. m_nodes[newParent].child1 = sibling; m_nodes[newParent].child2 = leaf; m_nodes[sibling].parent = newParent; m_nodes[leaf].parent = newParent; m_root = newParent; } // Walk back up the tree fixing heights and AABBs index = m_nodes[leaf].parent; while (index != b2_nullNode) { index = Balance(index); int32 child1 = m_nodes[index].child1; int32 child2 = m_nodes[index].child2; b2Assert(child1 != b2_nullNode); b2Assert(child2 != b2_nullNode); m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); index = m_nodes[index].parent; } //Validate(); } void b2DynamicTree::RemoveLeaf(int32 leaf) { if (leaf == m_root) { m_root = b2_nullNode; return; } int32 parent = m_nodes[leaf].parent; int32 grandParent = m_nodes[parent].parent; int32 sibling; if (m_nodes[parent].child1 == leaf) { sibling = m_nodes[parent].child2; } else { sibling = m_nodes[parent].child1; } if (grandParent != b2_nullNode) { // Destroy parent and connect sibling to grandParent. if (m_nodes[grandParent].child1 == parent) { m_nodes[grandParent].child1 = sibling; } else { m_nodes[grandParent].child2 = sibling; } m_nodes[sibling].parent = grandParent; FreeNode(parent); // Adjust ancestor bounds. int32 index = grandParent; while (index != b2_nullNode) { index = Balance(index); int32 child1 = m_nodes[index].child1; int32 child2 = m_nodes[index].child2; m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); index = m_nodes[index].parent; } } else { m_root = sibling; m_nodes[sibling].parent = b2_nullNode; FreeNode(parent); } //Validate(); } // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. int32 b2DynamicTree::Balance(int32 iA) { b2Assert(iA != b2_nullNode); b2TreeNode* A = m_nodes + iA; if (A->IsLeaf() || A->height < 2) { return iA; } int32 iB = A->child1; int32 iC = A->child2; b2Assert(0 <= iB && iB < m_nodeCapacity); b2Assert(0 <= iC && iC < m_nodeCapacity); b2TreeNode* B = m_nodes + iB; b2TreeNode* C = m_nodes + iC; int32 balance = C->height - B->height; // Rotate C up if (balance > 1) { int32 iF = C->child1; int32 iG = C->child2; b2TreeNode* F = m_nodes + iF; b2TreeNode* G = m_nodes + iG; b2Assert(0 <= iF && iF < m_nodeCapacity); b2Assert(0 <= iG && iG < m_nodeCapacity); // Swap A and C C->child1 = iA; C->parent = A->parent; A->parent = iC; // A's old parent should point to C if (C->parent != b2_nullNode) { if (m_nodes[C->parent].child1 == iA) { m_nodes[C->parent].child1 = iC; } else { b2Assert(m_nodes[C->parent].child2 == iA); m_nodes[C->parent].child2 = iC; } } else { m_root = iC; } // Rotate if (F->height > G->height) { C->child2 = iF; A->child2 = iG; G->parent = iA; A->aabb.Combine(B->aabb, G->aabb); C->aabb.Combine(A->aabb, F->aabb); A->height = 1 + b2Max(B->height, G->height); C->height = 1 + b2Max(A->height, F->height); } else { C->child2 = iG; A->child2 = iF; F->parent = iA; A->aabb.Combine(B->aabb, F->aabb); C->aabb.Combine(A->aabb, G->aabb); A->height = 1 + b2Max(B->height, F->height); C->height = 1 + b2Max(A->height, G->height); } return iC; } // Rotate B up if (balance < -1) { int32 iD = B->child1; int32 iE = B->child2; b2TreeNode* D = m_nodes + iD; b2TreeNode* E = m_nodes + iE; b2Assert(0 <= iD && iD < m_nodeCapacity); b2Assert(0 <= iE && iE < m_nodeCapacity); // Swap A and B B->child1 = iA; B->parent = A->parent; A->parent = iB; // A's old parent should point to B if (B->parent != b2_nullNode) { if (m_nodes[B->parent].child1 == iA) { m_nodes[B->parent].child1 = iB; } else { b2Assert(m_nodes[B->parent].child2 == iA); m_nodes[B->parent].child2 = iB; } } else { m_root = iB; } // Rotate if (D->height > E->height) { B->child2 = iD; A->child1 = iE; E->parent = iA; A->aabb.Combine(C->aabb, E->aabb); B->aabb.Combine(A->aabb, D->aabb); A->height = 1 + b2Max(C->height, E->height); B->height = 1 + b2Max(A->height, D->height); } else { B->child2 = iE; A->child1 = iD; D->parent = iA; A->aabb.Combine(C->aabb, D->aabb); B->aabb.Combine(A->aabb, E->aabb); A->height = 1 + b2Max(C->height, D->height); B->height = 1 + b2Max(A->height, E->height); } return iB; } return iA; } int32 b2DynamicTree::GetHeight() const { if (m_root == b2_nullNode) { return 0; } return m_nodes[m_root].height; } // float32 b2DynamicTree::GetAreaRatio() const { if (m_root == b2_nullNode) { return 0.0f; } const b2TreeNode* root = m_nodes + m_root; float32 rootArea = root->aabb.GetPerimeter(); float32 totalArea = 0.0f; for (int32 i = 0; i < m_nodeCapacity; ++i) { const b2TreeNode* node = m_nodes + i; if (node->height < 0) { // Free node in pool continue; } totalArea += node->aabb.GetPerimeter(); } return totalArea / rootArea; } // Compute the height of a sub-tree. int32 b2DynamicTree::ComputeHeight(int32 nodeId) const { b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); b2TreeNode* node = m_nodes + nodeId; if (node->IsLeaf()) { return 0; } int32 height1 = ComputeHeight(node->child1); int32 height2 = ComputeHeight(node->child2); return 1 + b2Max(height1, height2); } int32 b2DynamicTree::ComputeHeight() const { int32 height = ComputeHeight(m_root); return height; } void b2DynamicTree::ValidateStructure(int32 index) const { if (index == b2_nullNode) { return; } if (index == m_root) { b2Assert(m_nodes[index].parent == b2_nullNode); } const b2TreeNode* node = m_nodes + index; int32 child1 = node->child1; int32 child2 = node->child2; if (node->IsLeaf()) { b2Assert(child1 == b2_nullNode); b2Assert(child2 == b2_nullNode); b2Assert(node->height == 0); return; } b2Assert(0 <= child1 && child1 < m_nodeCapacity); b2Assert(0 <= child2 && child2 < m_nodeCapacity); b2Assert(m_nodes[child1].parent == index); b2Assert(m_nodes[child2].parent == index); ValidateStructure(child1); ValidateStructure(child2); } void b2DynamicTree::ValidateMetrics(int32 index) const { if (index == b2_nullNode) { return; } const b2TreeNode* node = m_nodes + index; int32 child1 = node->child1; int32 child2 = node->child2; if (node->IsLeaf()) { b2Assert(child1 == b2_nullNode); b2Assert(child2 == b2_nullNode); b2Assert(node->height == 0); return; } b2Assert(0 <= child1 && child1 < m_nodeCapacity); b2Assert(0 <= child2 && child2 < m_nodeCapacity); int32 height1 = m_nodes[child1].height; int32 height2 = m_nodes[child2].height; int32 height; height = 1 + b2Max(height1, height2); b2Assert(node->height == height); b2AABB aabb; aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); b2Assert(aabb.lowerBound == node->aabb.lowerBound); b2Assert(aabb.upperBound == node->aabb.upperBound); ValidateMetrics(child1); ValidateMetrics(child2); } void b2DynamicTree::Validate() const { ValidateStructure(m_root); ValidateMetrics(m_root); int32 freeCount = 0; int32 freeIndex = m_freeList; while (freeIndex != b2_nullNode) { b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); freeIndex = m_nodes[freeIndex].next; ++freeCount; } b2Assert(GetHeight() == ComputeHeight()); b2Assert(m_nodeCount + freeCount == m_nodeCapacity); } int32 b2DynamicTree::GetMaxBalance() const { int32 maxBalance = 0; for (int32 i = 0; i < m_nodeCapacity; ++i) { const b2TreeNode* node = m_nodes + i; if (node->height <= 1) { continue; } b2Assert(node->IsLeaf() == false); int32 child1 = node->child1; int32 child2 = node->child2; int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); maxBalance = b2Max(maxBalance, balance); } return maxBalance; } void b2DynamicTree::RebuildBottomUp() { int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); int32 count = 0; // Build array of leaves. Free the rest. for (int32 i = 0; i < m_nodeCapacity; ++i) { if (m_nodes[i].height < 0) { // free node in pool continue; } if (m_nodes[i].IsLeaf()) { m_nodes[i].parent = b2_nullNode; nodes[count] = i; ++count; } else { FreeNode(i); } } while (count > 1) { float32 minCost = b2_maxFloat; int32 iMin = -1, jMin = -1; for (int32 i = 0; i < count; ++i) { b2AABB aabbi = m_nodes[nodes[i]].aabb; for (int32 j = i + 1; j < count; ++j) { b2AABB aabbj = m_nodes[nodes[j]].aabb; b2AABB b; b.Combine(aabbi, aabbj); float32 cost = b.GetPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } int32 index1 = nodes[iMin]; int32 index2 = nodes[jMin]; b2TreeNode* child1 = m_nodes + index1; b2TreeNode* child2 = m_nodes + index2; int32 parentIndex = AllocateNode(); b2TreeNode* parent = m_nodes + parentIndex; parent->child1 = index1; parent->child2 = index2; parent->height = 1 + b2Max(child1->height, child2->height); parent->aabb.Combine(child1->aabb, child2->aabb); parent->parent = b2_nullNode; child1->parent = parentIndex; child2->parent = parentIndex; nodes[jMin] = nodes[count-1]; nodes[iMin] = parentIndex; --count; } m_root = nodes[0]; b2Free(nodes); Validate(); }
mit
mitreaadrian/Soccersim
boost/boost_1_59_0/libs/graph/example/dfs.cpp
31
3221
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <boost/config.hpp> #include <assert.h> #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/visitors.hpp> /* This calculates the discover finishing time. Sample Output Tree edge: 0 --> 2 Tree edge: 2 --> 1 Back edge: 1 --> 1 Finish edge: 1 --> 1 Tree edge: 1 --> 3 Back edge: 3 --> 1 Finish edge: 3 --> 1 Tree edge: 3 --> 4 Back edge: 4 --> 0 Finish edge: 4 --> 0 Back edge: 4 --> 1 Finish edge: 4 --> 1 Forward or cross edge: 2 --> 3 Finish edge: 2 --> 3 Finish edge: 0 --> 2 1 10 3 8 2 9 4 7 5 6 */ using namespace boost; using namespace std; template <class VisitorList> struct edge_categorizer : public dfs_visitor<VisitorList> { typedef dfs_visitor<VisitorList> Base; edge_categorizer(const VisitorList& v = null_visitor()) : Base(v) { } template <class Edge, class Graph> void tree_edge(Edge e, Graph& G) { cout << "Tree edge: " << source(e, G) << " --> " << target(e, G) << endl; Base::tree_edge(e, G); } template <class Edge, class Graph> void back_edge(Edge e, Graph& G) { cout << "Back edge: " << source(e, G) << " --> " << target(e, G) << endl; Base::back_edge(e, G); } template <class Edge, class Graph> void forward_or_cross_edge(Edge e, Graph& G) { cout << "Forward or cross edge: " << source(e, G) << " --> " << target(e, G) << endl; Base::forward_or_cross_edge(e, G); } template <class Edge, class Graph> void finish_edge(Edge e, Graph& G) { cout << "Finish edge: " << source(e, G) << " --> " << target(e, G) << endl; Base::finish_edge(e, G); } }; template <class VisitorList> edge_categorizer<VisitorList> categorize_edges(const VisitorList& v) { return edge_categorizer<VisitorList>(v); } int main(int , char* []) { using namespace boost; typedef adjacency_list<> Graph; Graph G(5); add_edge(0, 2, G); add_edge(1, 1, G); add_edge(1, 3, G); add_edge(2, 1, G); add_edge(2, 3, G); add_edge(3, 1, G); add_edge(3, 4, G); add_edge(4, 0, G); add_edge(4, 1, G); typedef graph_traits<Graph>::vertex_descriptor Vertex; typedef graph_traits<Graph>::vertices_size_type size_type; std::vector<size_type> d(num_vertices(G)); std::vector<size_type> f(num_vertices(G)); int t = 0; depth_first_search(G, visitor(categorize_edges( make_pair(stamp_times(&d[0], t, on_discover_vertex()), stamp_times(&f[0], t, on_finish_vertex()))))); std::vector<size_type>::iterator i, j; for (i = d.begin(), j = f.begin(); i != d.end(); ++i, ++j) cout << *i << " " << *j << endl; return 0; }
mit
josteink/coreclr
src/pal/tests/palsuite/c_runtime/_vsnwprintf/test14/test14.c
31
2674
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: test14.c ** ** Purpose: Test #14 for the _vsnwprintf function. ** ** **===================================================================*/ #include <palsuite.h> #include "../_vsnwprintf.h" /* memcmp is used to verify the results, so this test is dependent on it. */ /* ditto with wcslen */ int __cdecl main(int argc, char *argv[]) { double val = 256.0; double neg = -256.0; if (PAL_Initialize(argc, argv) != 0) { return(FAIL); } DoDoubleTest(convert("foo %e"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %le"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %he"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %Le"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %I64e"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %14e"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %-14e"), val, convert("foo 2.560000e+002 "), convert("foo 2.560000e+02 ")); DoDoubleTest(convert("foo %.1e"), val, convert("foo 2.6e+002"), convert("foo 2.6e+02")); DoDoubleTest(convert("foo %.8e"), val, convert("foo 2.56000000e+002"), convert("foo 2.56000000e+02")); DoDoubleTest(convert("foo %014e"), val, convert("foo 02.560000e+002"), convert("foo 002.560000e+02")); DoDoubleTest(convert("foo %#e"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %+e"), val, convert("foo +2.560000e+002"), convert("foo +2.560000e+02")); DoDoubleTest(convert("foo % e"), val, convert("foo 2.560000e+002"), convert("foo 2.560000e+02")); DoDoubleTest(convert("foo %+e"), neg, convert("foo -2.560000e+002"), convert("foo -2.560000e+02")); DoDoubleTest(convert("foo % e"), neg, convert("foo -2.560000e+002"), convert("foo -2.560000e+02")); PAL_Terminate(); return PASS; }
mit
burtonsamograd/urbit
outside/softfloat-3/source/8086-SSE/s_f32UIToCommonNaN.c
34
2546
/*============================================================================ This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic Package, Release 3, by John R. Hauser. Copyright 2011, 2012, 2013, 2014 The Regents of the University of California (Regents). All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions, and the following two paragraphs of disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following two paragraphs of disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Regents nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =============================================================================*/ #include <stdint.h> #include "platform.h" #include "specialize.h" #include "softfloat.h" /*---------------------------------------------------------------------------- | Assuming `uiA' has the bit pattern of a 32-bit floating-point NaN, converts | this NaN to the common NaN form, and stores the resulting common NaN at the | location pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid | exception is raised. *----------------------------------------------------------------------------*/ void softfloat_f32UIToCommonNaN( uint_fast32_t uiA, struct commonNaN *zPtr ) { if ( softfloat_isSigNaNF32UI( uiA ) ) { softfloat_raiseFlags( softfloat_flag_invalid ); } zPtr->sign = uiA>>31; zPtr->v64 = (uint_fast64_t) uiA<<41; zPtr->v0 = 0; }
mit
aspectron/jsx
extern/boost/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_ring.cpp
37
1425
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[boost_polygon_ring //`Shows how to use Boost.Polygon polygon_data within Boost.Geometry #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/adapted/boost_polygon.hpp> int main() { typedef boost::polygon::polygon_data<int> polygon; typedef boost::polygon::polygon_traits<polygon>::point_type point; point pts[5] = { boost::polygon::construct<point>(0, 0), boost::polygon::construct<point>(0, 10), boost::polygon::construct<point>(10, 10), boost::polygon::construct<point>(10, 0), boost::polygon::construct<point>(0, 0) }; polygon poly; boost::polygon::set_points(poly, pts, pts+5); std::cout << "Area (using Boost.Geometry): " << boost::geometry::area(poly) << std::endl; std::cout << "Area (using Boost.Polygon): " << boost::polygon::area(poly) << std::endl; return 0; } //] //[boost_polygon_ring_output /*` Output: [pre Area (using Boost.Geometry): 100 Area (using Boost.Polygon): 100 ] */ //]
mit
vcredit-zj/MiniEcho
MiniEcho/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp
40
1375
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include "impl/weak_realm_notifier.hpp" #include "shared_realm.hpp" #include "util/event_loop_signal.hpp" using namespace realm; using namespace realm::_impl; WeakRealmNotifier::WeakRealmNotifier(const std::shared_ptr<Realm>& realm, bool cache) : m_realm(realm) , m_realm_key(realm.get()) , m_cache(cache) , m_signal(std::make_shared<util::EventLoopSignal<Callback>>(Callback{realm})) { } WeakRealmNotifier::~WeakRealmNotifier() = default; void WeakRealmNotifier::Callback::operator()() { if (auto realm = weak_realm.lock()) { realm->notify(); } } void WeakRealmNotifier::notify() { m_signal->notify(); }
mit
phantasien/falkor
deps/uv/test/test-pipe-close-stdout-read-stdin.c
40
2996
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef _WIN32 #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include "uv.h" #include "task.h" void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t* buf) { static char buffer[1024]; buf->base = buffer; buf->len = sizeof(buffer); } void read_stdin(uv_stream_t *stream, ssize_t nread, const uv_buf_t* buf) { if (nread < 0) { uv_close((uv_handle_t*)stream, NULL); return; } } /* * This test is a reproduction of joyent/libuv#1419 . */ TEST_IMPL(pipe_close_stdout_read_stdin) { int r = -1; int pid; int fd[2]; int status; uv_pipe_t stdin_pipe; r = pipe(fd); ASSERT(r == 0); if ((pid = fork()) == 0) { /* * Make the read side of the pipe our stdin. * The write side will be closed by the parent process. */ close(fd[1]); close(0); r = dup(fd[0]); ASSERT(r != -1); /* Create a stream that reads from the pipe. */ r = uv_pipe_init(uv_default_loop(), (uv_pipe_t *)&stdin_pipe, 0); ASSERT(r == 0); r = uv_pipe_open((uv_pipe_t *)&stdin_pipe, 0); ASSERT(r == 0); r = uv_read_start((uv_stream_t *)&stdin_pipe, alloc_buffer, read_stdin); ASSERT(r == 0); /* * Because the other end of the pipe was closed, there should * be no event left to process after one run of the event loop. * Otherwise, it means that events were not processed correctly. */ ASSERT(uv_run(uv_default_loop(), UV_RUN_NOWAIT) == 0); } else { /* * Close both ends of the pipe so that the child * get a POLLHUP event when it tries to read from * the other end. */ close(fd[1]); close(fd[0]); waitpid(pid, &status, 0); ASSERT(WIFEXITED(status) && WEXITSTATUS(status) == 0); } MAKE_VALGRIND_HAPPY(); return 0; } #endif /* ifndef _WIN32 */
mit
yizhang82/coreclr
src/debug/daccess/request_svr.cpp
42
12341
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //***************************************************************************** // // File: request.cpp // // CorDataAccess::Request implementation. // //***************************************************************************** #include "stdafx.h" #include "dacdbiinterface.h" #include "dacdbiimpl.h" #if defined(FEATURE_SVR_GC) #include <sigformat.h> #include <win32threadpool.h> #include "request_common.h" int GCHeapCount() { if (g_gcDacGlobals->n_heaps == nullptr) return 0; return *g_gcDacGlobals->n_heaps; } HRESULT GetServerHeapData(CLRDATA_ADDRESS addr, DacpHeapSegmentData *pSegment) { // get field values (target addresses) for the heap segment at addr if (!addr) { // PREfix. return E_INVALIDARG; } // marshal the segment from target to host dac_heap_segment *pHeapSegment = __DPtr<dac_heap_segment>(TO_TADDR(addr)); // initialize fields by copying from the marshaled segment (note that these are all target addresses) pSegment->segmentAddr = addr; pSegment->allocated = (CLRDATA_ADDRESS)(ULONG_PTR) pHeapSegment->allocated; pSegment->committed = (CLRDATA_ADDRESS)(ULONG_PTR) pHeapSegment->committed; pSegment->reserved = (CLRDATA_ADDRESS)(ULONG_PTR) pHeapSegment->reserved; pSegment->used = (CLRDATA_ADDRESS)(ULONG_PTR) pHeapSegment->used; pSegment->mem = (CLRDATA_ADDRESS)(ULONG_PTR) (pHeapSegment->mem); pSegment->next = (CLRDATA_ADDRESS)dac_cast<TADDR>(pHeapSegment->next); pSegment->gc_heap = (CLRDATA_ADDRESS)pHeapSegment->heap; return S_OK; } HRESULT GetServerHeaps(CLRDATA_ADDRESS pGCHeaps[], ICorDebugDataTarget * pTarget) { // @todo Microsoft: It would be good to have an assert here to ensure pGCHeaps is large enough to // hold all the addresses. Currently we check that in the only caller, but if we were to call this from // somewhere else in the future, we could have a buffer overrun. // The runtime declares its own global array of gc heap addresses for multiple heap scenarios. We need to get // its starting address. This expression is a little tricky to parse, but in DAC builds, g_heaps is // a DAC global (__GlobalPtr). The __GlobalPtr<...>::GetAddr() function gets the starting address of that global, but // be sure to note this is a target address. We'll use this as our source for getting our local list of // heap addresses. for (int i = 0; i < GCHeapCount(); i++) { pGCHeaps[i] = (CLRDATA_ADDRESS)HeapTableIndex(g_gcDacGlobals->g_heaps, i).GetAddr(); } return S_OK; } #define PTR_CDADDR(ptr) TO_CDADDR(PTR_TO_TADDR(ptr)) #define HOST_CDADDR(host) TO_CDADDR(PTR_HOST_TO_TADDR(host)) HRESULT ClrDataAccess::GetServerAllocData(unsigned int count, struct DacpGenerationAllocData *data, unsigned int *pNeeded) { unsigned int heaps = (unsigned int)GCHeapCount(); if (pNeeded) *pNeeded = heaps; if (data) { if (count > heaps) count = heaps; for (unsigned int n=0; n < heaps; n++) { DPTR(dac_gc_heap) pHeap = HeapTableIndex(g_gcDacGlobals->g_heaps, n); for (int i=0;i<NUMBERGENERATIONS;i++) { dac_generation generation = *ServerGenerationTableIndex(pHeap, i); data[n].allocData[i].allocBytes = (CLRDATA_ADDRESS)(ULONG_PTR) generation.allocation_context.alloc_bytes; data[n].allocData[i].allocBytesLoh = (CLRDATA_ADDRESS)(ULONG_PTR) generation.allocation_context.alloc_bytes_loh; } } } return S_OK; } HRESULT ClrDataAccess::ServerGCHeapDetails(CLRDATA_ADDRESS heapAddr, DacpGcHeapDetails *detailsData) { if (!heapAddr) { // PREfix. return E_INVALIDARG; } DPTR(dac_gc_heap) pHeap = __DPtr<dac_gc_heap>(TO_TADDR(heapAddr)); int i; //get global information first detailsData->heapAddr = heapAddr; detailsData->lowest_address = PTR_CDADDR(g_lowest_address); detailsData->highest_address = PTR_CDADDR(g_highest_address); detailsData->card_table = PTR_CDADDR(g_card_table); // now get information specific to this heap (server mode gives us several heaps; we're getting // information about only one of them. detailsData->alloc_allocated = (CLRDATA_ADDRESS)pHeap->alloc_allocated; detailsData->ephemeral_heap_segment = (CLRDATA_ADDRESS)dac_cast<TADDR>(pHeap->ephemeral_heap_segment); // get bounds for the different generations for (i=0; i<NUMBERGENERATIONS; i++) { DPTR(dac_generation) generation = ServerGenerationTableIndex(pHeap, i); detailsData->generation_table[i].start_segment = (CLRDATA_ADDRESS)dac_cast<TADDR>(generation->start_segment); detailsData->generation_table[i].allocation_start = (CLRDATA_ADDRESS)(ULONG_PTR)generation->allocation_start; DPTR(gc_alloc_context) alloc_context = dac_cast<TADDR>(generation) + offsetof(dac_generation, allocation_context); detailsData->generation_table[i].allocContextPtr = (CLRDATA_ADDRESS)(ULONG_PTR) alloc_context->alloc_ptr; detailsData->generation_table[i].allocContextLimit = (CLRDATA_ADDRESS)(ULONG_PTR) alloc_context->alloc_limit; } DPTR(dac_finalize_queue) fq = pHeap->finalize_queue; DPTR(uint8_t*) pFillPointerArray= dac_cast<TADDR>(fq) + offsetof(dac_finalize_queue, m_FillPointers); for(i=0; i<(NUMBERGENERATIONS+dac_finalize_queue::ExtraSegCount); i++) { detailsData->finalization_fill_pointers[i] = (CLRDATA_ADDRESS) pFillPointerArray[i]; } return S_OK; } HRESULT ClrDataAccess::ServerOomData(CLRDATA_ADDRESS addr, DacpOomData *oomData) { DPTR(dac_gc_heap) pHeap = __DPtr<dac_gc_heap>(TO_TADDR(addr)); oom_history pOOMInfo = pHeap->oom_info; oomData->reason = pOOMInfo.reason; oomData->alloc_size = pOOMInfo.alloc_size; oomData->available_pagefile_mb = pOOMInfo.available_pagefile_mb; oomData->gc_index = pOOMInfo.gc_index; oomData->fgm = pOOMInfo.fgm; oomData->size = pOOMInfo.size; oomData->loh_p = pOOMInfo.loh_p; return S_OK; } HRESULT ClrDataAccess::ServerGCInterestingInfoData(CLRDATA_ADDRESS addr, DacpGCInterestingInfoData *interestingInfoData) { #ifdef GC_CONFIG_DRIVEN dac_gc_heap *pHeap = __DPtr<dac_gc_heap>(TO_TADDR(addr)); size_t* dataPoints = (size_t*)&(pHeap->interesting_data_per_heap); for (int i = 0; i < NUM_GC_DATA_POINTS; i++) interestingInfoData->interestingDataPoints[i] = dataPoints[i]; size_t* mechanisms = (size_t*)&(pHeap->compact_reasons_per_heap); for (int i = 0; i < MAX_COMPACT_REASONS_COUNT; i++) interestingInfoData->compactReasons[i] = mechanisms[i]; mechanisms = (size_t*)&(pHeap->expand_mechanisms_per_heap); for (int i = 0; i < MAX_EXPAND_MECHANISMS_COUNT; i++) interestingInfoData->expandMechanisms[i] = mechanisms[i]; mechanisms = (size_t*)&(pHeap->interesting_mechanism_bits_per_heap); for (int i = 0; i < MAX_GC_MECHANISM_BITS_COUNT; i++) interestingInfoData->bitMechanisms[i] = mechanisms[i]; return S_OK; #else return E_NOTIMPL; #endif //GC_CONFIG_DRIVEN } HRESULT ClrDataAccess::ServerGCHeapAnalyzeData(CLRDATA_ADDRESS heapAddr, DacpGcHeapAnalyzeData *analyzeData) { if (!heapAddr) { // PREfix. return E_INVALIDARG; } DPTR(dac_gc_heap) pHeap = __DPtr<dac_gc_heap>(TO_TADDR(heapAddr)); analyzeData->heapAddr = heapAddr; analyzeData->internal_root_array = (CLRDATA_ADDRESS)pHeap->internal_root_array; analyzeData->internal_root_array_index = (size_t)pHeap->internal_root_array_index; analyzeData->heap_analyze_success = (BOOL)pHeap->heap_analyze_success; return S_OK; } void ClrDataAccess::EnumSvrGlobalMemoryRegions(CLRDataEnumMemoryFlags flags) { SUPPORTS_DAC; if (g_gcDacGlobals->n_heaps == nullptr || g_gcDacGlobals->g_heaps == nullptr) return; g_gcDacGlobals->n_heaps.EnumMem(); int heaps = *g_gcDacGlobals->n_heaps; DacEnumMemoryRegion(g_gcDacGlobals->g_heaps.GetAddr(), sizeof(TADDR) * heaps); g_gcDacGlobals->gc_structures_invalid_cnt.EnumMem(); g_gcDacGlobals->g_heaps.EnumMem(); for (int i = 0; i < heaps; i++) { DPTR(dac_gc_heap) pHeap = HeapTableIndex(g_gcDacGlobals->g_heaps, i); size_t gen_table_size = g_gcDacGlobals->generation_size * (*g_gcDacGlobals->max_gen + 1); DacEnumMemoryRegion(dac_cast<TADDR>(pHeap), sizeof(dac_gc_heap)); DacEnumMemoryRegion(dac_cast<TADDR>(pHeap->finalize_queue), sizeof(dac_finalize_queue)); DacEnumMemoryRegion(dac_cast<TADDR>(pHeap->generation_table), gen_table_size); // enumerating the generations from max (which is normally gen2) to max+1 gives you // the segment list for all the normal segements plus the large heap segment (max+1) // this is the convention in the GC so it is repeated here for (ULONG i = *g_gcDacGlobals->max_gen; i <= *g_gcDacGlobals->max_gen +1; i++) { DPTR(dac_heap_segment) seg = ServerGenerationTableIndex(pHeap, i)->start_segment; while (seg) { DacEnumMemoryRegion(PTR_HOST_TO_TADDR(seg), sizeof(dac_heap_segment)); seg = seg->next; } } } } DWORD DacGetNumHeaps() { if (g_heap_type == GC_HEAP_SVR) return (DWORD)*g_gcDacGlobals->n_heaps; // workstation gc return 1; } HRESULT DacHeapWalker::InitHeapDataSvr(HeapData *&pHeaps, size_t &pCount) { if (g_gcDacGlobals->n_heaps == nullptr || g_gcDacGlobals->g_heaps == nullptr) return S_OK; // Scrape basic heap details int heaps = *g_gcDacGlobals->n_heaps; pCount = heaps; pHeaps = new (nothrow) HeapData[heaps]; if (pHeaps == NULL) return E_OUTOFMEMORY; for (int i = 0; i < heaps; ++i) { // Basic heap info. DPTR(dac_gc_heap) heap = HeapTableIndex(g_gcDacGlobals->g_heaps, i); dac_generation gen0 = *ServerGenerationTableIndex(heap, 0); dac_generation gen1 = *ServerGenerationTableIndex(heap, 1); dac_generation gen2 = *ServerGenerationTableIndex(heap, 2); dac_generation loh = *ServerGenerationTableIndex(heap, 3); pHeaps[i].YoungestGenPtr = (CORDB_ADDRESS)gen0.allocation_context.alloc_ptr; pHeaps[i].YoungestGenLimit = (CORDB_ADDRESS)gen0.allocation_context.alloc_limit; pHeaps[i].Gen0Start = (CORDB_ADDRESS)gen0.allocation_start; pHeaps[i].Gen0End = (CORDB_ADDRESS)heap->alloc_allocated; pHeaps[i].Gen1Start = (CORDB_ADDRESS)gen1.allocation_start; // Segments int count = GetSegmentCount(loh.start_segment); count += GetSegmentCount(gen2.start_segment); pHeaps[i].SegmentCount = count; pHeaps[i].Segments = new (nothrow) SegmentData[count]; if (pHeaps[i].Segments == NULL) return E_OUTOFMEMORY; // Small object heap segments DPTR(dac_heap_segment) seg = gen2.start_segment; int j = 0; for (; seg && (j < count); ++j) { pHeaps[i].Segments[j].Start = (CORDB_ADDRESS)seg->mem; if (seg.GetAddr() == heap->ephemeral_heap_segment.GetAddr()) { pHeaps[i].Segments[j].End = (CORDB_ADDRESS)heap->alloc_allocated; pHeaps[i].EphemeralSegment = j; pHeaps[i].Segments[j].Generation = 1; } else { pHeaps[i].Segments[j].End = (CORDB_ADDRESS)seg->allocated; pHeaps[i].Segments[j].Generation = 2; } seg = seg->next; } // Large object heap segments seg = loh.start_segment; for (; seg && (j < count); ++j) { pHeaps[i].Segments[j].Generation = 3; pHeaps[i].Segments[j].Start = (CORDB_ADDRESS)seg->mem; pHeaps[i].Segments[j].End = (CORDB_ADDRESS)seg->allocated; seg = seg->next; } } return S_OK; } #endif // defined(FEATURE_SVR_GC)
mit
TyRoXx/cdm
original_sources/boost_1_59_0/libs/serialization/test/test_complex.cpp
43
2992
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_complex.cpp // (C) Copyright 2005 Matthias Troyer . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // should pass compilation and execution #include <fstream> #include <cstddef> // NULL #include <cstdlib> // rand #include <cstdio> // remove #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/math/special_functions/next.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) #include <boost/limits.hpp> namespace std{ using ::rand; using ::remove; #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(UNDER_CE) using ::numeric_limits; #endif } #endif #include "test_tools.hpp" #include <boost/preprocessor/stringize.hpp> #include BOOST_PP_STRINGIZE(BOOST_ARCHIVE_TEST) #include <boost/serialization/complex.hpp> #include <iostream> int test_main( int /* argc */, char* /* argv */[] ) { const char * testfile = boost::archive::tmpnam(NULL); BOOST_REQUIRE(NULL != testfile); // test array of objects std::complex<float> a( static_cast<float>(std::rand()) / static_cast<float>(std::rand()), static_cast<float>(std::rand()) / static_cast<float>(std::rand()) ); std::complex<double> b( static_cast<double>(std::rand()) / static_cast<double>(std::rand()), static_cast<double>(std::rand()) / static_cast<double>(std::rand()) ); { test_ostream os(testfile, TEST_STREAM_FLAGS); test_oarchive oa(os); oa << boost::serialization::make_nvp("afloatcomplex", a); oa << boost::serialization::make_nvp("adoublecomplex", b); } std::complex<float> a1; std::complex<double> b1; { test_istream is(testfile, TEST_STREAM_FLAGS); test_iarchive ia(is); ia >> boost::serialization::make_nvp("afloatcomplex", a1); ia >> boost::serialization::make_nvp("adoublecomplex", b1); } std::cerr << "a.real()-a1a.real() distance = " << std::abs( boost::math::float_distance(a.real(), a1.real())) << std::endl; BOOST_CHECK(std::abs(boost::math::float_distance(a.real(), a1.real())) < 2); std::cerr << "a.imag() - a1a.imag() distance = " << std::abs( boost::math::float_distance(a.imag(), a1.imag())) << std::endl; BOOST_CHECK(std::abs(boost::math::float_distance(a.imag(), a1.imag())) < 2); std::cerr << "b.real() - b1.real() distance = " << std::abs( boost::math::float_distance(b.real(), b1.real())) << std::endl; BOOST_CHECK(std::abs(boost::math::float_distance(b.real(), b1.real())) < 2); std::cerr << "b.imag() - b1.imag() distance = " << std::abs( boost::math::float_distance(b.imag(), b1.imag())) << std::endl; BOOST_CHECK(std::abs(boost::math::float_distance(b.imag(), b1.imag())) < 2); std::remove(testfile); return EXIT_SUCCESS; } // EOF
mit
tihovinc/SuperLU_w64_mkl
SuperLU_5.2.1/SRC/ilu_ccolumn_dfs.c
48
7452
/*! \file Copyright (c) 2003, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from U.S. Dept. of Energy) All rights reserved. The source code is distributed under BSD license, see the file License.txt at the top-level directory. */ /*! @file ilu_ccolumn_dfs.c * \brief Performs a symbolic factorization * * <pre> * -- SuperLU routine (version 4.0) -- * Lawrence Berkeley National Laboratory * June 30, 2009 * </pre> */ #include "slu_cdefs.h" /*! \brief * * <pre> * Purpose * ======= * ILU_CCOLUMN_DFS performs a symbolic factorization on column jcol, and * decide the supernode boundary. * * This routine does not use numeric values, but only use the RHS * row indices to start the dfs. * * A supernode representative is the last column of a supernode. * The nonzeros in U[*,j] are segments that end at supernodal * representatives. The routine returns a list of such supernodal * representatives in topological order of the dfs that generates them. * The location of the first nonzero in each such supernodal segment * (supernodal entry location) is also returned. * * Local parameters * ================ * nseg: no of segments in current U[*,j] * jsuper: jsuper=EMPTY if column j does not belong to the same * supernode as j-1. Otherwise, jsuper=nsuper. * * marker2: A-row --> A-row/col (0/1) * repfnz: SuperA-col --> PA-row * parent: SuperA-col --> SuperA-col * xplore: SuperA-col --> index to L-structure * * Return value * ============ * 0 success; * > 0 number of bytes allocated when run out of space. * </pre> */ int ilu_ccolumn_dfs( const int m, /* in - number of rows in the matrix */ const int jcol, /* in */ int *perm_r, /* in */ int *nseg, /* modified - with new segments appended */ int *lsub_col, /* in - defines the RHS vector to start the dfs */ int *segrep, /* modified - with new segments appended */ int *repfnz, /* modified */ int *marker, /* modified */ int *parent, /* working array */ int *xplore, /* working array */ GlobalLU_t *Glu /* modified */ ) { int jcolp1, jcolm1, jsuper, nsuper, nextl; int k, krep, krow, kmark, kperm; int *marker2; /* Used for small panel LU */ int fsupc; /* First column of a snode */ int myfnz; /* First nonz column of a U-segment */ int chperm, chmark, chrep, kchild; int xdfs, maxdfs, kpar, oldrep; int jptr, jm1ptr; int ito, ifrom; /* Used to compress row subscripts */ int mem_error; int *xsup, *supno, *lsub, *xlsub; int nzlmax; int maxsuper; xsup = Glu->xsup; supno = Glu->supno; lsub = Glu->lsub; xlsub = Glu->xlsub; nzlmax = Glu->nzlmax; maxsuper = sp_ienv(7); jcolp1 = jcol + 1; jcolm1 = jcol - 1; nsuper = supno[jcol]; jsuper = nsuper; nextl = xlsub[jcol]; marker2 = &marker[2*m]; /* For each nonzero in A[*,jcol] do dfs */ for (k = 0; lsub_col[k] != EMPTY; k++) { krow = lsub_col[k]; lsub_col[k] = EMPTY; kmark = marker2[krow]; /* krow was visited before, go to the next nonzero */ if ( kmark == jcol ) continue; /* For each unmarked nbr krow of jcol * krow is in L: place it in structure of L[*,jcol] */ marker2[krow] = jcol; kperm = perm_r[krow]; if ( kperm == EMPTY ) { lsub[nextl++] = krow; /* krow is indexed into A */ if ( nextl >= nzlmax ) { if ((mem_error = cLUMemXpand(jcol, nextl, LSUB, &nzlmax, Glu))) return (mem_error); lsub = Glu->lsub; } if ( kmark != jcolm1 ) jsuper = EMPTY;/* Row index subset testing */ } else { /* krow is in U: if its supernode-rep krep * has been explored, update repfnz[*] */ krep = xsup[supno[kperm]+1] - 1; myfnz = repfnz[krep]; if ( myfnz != EMPTY ) { /* Visited before */ if ( myfnz > kperm ) repfnz[krep] = kperm; /* continue; */ } else { /* Otherwise, perform dfs starting at krep */ oldrep = EMPTY; parent[krep] = oldrep; repfnz[krep] = kperm; xdfs = xlsub[xsup[supno[krep]]]; maxdfs = xlsub[krep + 1]; do { /* * For each unmarked kchild of krep */ while ( xdfs < maxdfs ) { kchild = lsub[xdfs]; xdfs++; chmark = marker2[kchild]; if ( chmark != jcol ) { /* Not reached yet */ marker2[kchild] = jcol; chperm = perm_r[kchild]; /* Case kchild is in L: place it in L[*,k] */ if ( chperm == EMPTY ) { lsub[nextl++] = kchild; if ( nextl >= nzlmax ) { if ( (mem_error = cLUMemXpand(jcol,nextl, LSUB,&nzlmax,Glu)) ) return (mem_error); lsub = Glu->lsub; } if ( chmark != jcolm1 ) jsuper = EMPTY; } else { /* Case kchild is in U: * chrep = its supernode-rep. If its rep has * been explored, update its repfnz[*] */ chrep = xsup[supno[chperm]+1] - 1; myfnz = repfnz[chrep]; if ( myfnz != EMPTY ) { /* Visited before */ if ( myfnz > chperm ) repfnz[chrep] = chperm; } else { /* Continue dfs at super-rep of kchild */ xplore[krep] = xdfs; oldrep = krep; krep = chrep; /* Go deeper down G(L^t) */ parent[krep] = oldrep; repfnz[krep] = chperm; xdfs = xlsub[xsup[supno[krep]]]; maxdfs = xlsub[krep + 1]; } /* else */ } /* else */ } /* if */ } /* while */ /* krow has no more unexplored nbrs; * place supernode-rep krep in postorder DFS. * backtrack dfs to its parent */ segrep[*nseg] = krep; ++(*nseg); kpar = parent[krep]; /* Pop from stack, mimic recursion */ if ( kpar == EMPTY ) break; /* dfs done */ krep = kpar; xdfs = xplore[krep]; maxdfs = xlsub[krep + 1]; } while ( kpar != EMPTY ); /* Until empty stack */ } /* else */ } /* else */ } /* for each nonzero ... */ /* Check to see if j belongs in the same supernode as j-1 */ if ( jcol == 0 ) { /* Do nothing for column 0 */ nsuper = supno[0] = 0; } else { fsupc = xsup[nsuper]; jptr = xlsub[jcol]; /* Not compressed yet */ jm1ptr = xlsub[jcolm1]; if ( (nextl-jptr != jptr-jm1ptr-1) ) jsuper = EMPTY; /* Always start a new supernode for a singular column */ if ( nextl == jptr ) jsuper = EMPTY; /* Make sure the number of columns in a supernode doesn't exceed threshold. */ if ( jcol - fsupc >= maxsuper ) jsuper = EMPTY; /* If jcol starts a new supernode, reclaim storage space in * lsub from the previous supernode. Note we only store * the subscript set of the first columns of the supernode. */ if ( jsuper == EMPTY ) { /* starts a new supernode */ if ( (fsupc < jcolm1) ) { /* >= 2 columns in nsuper */ #ifdef CHK_COMPRESS printf(" Compress lsub[] at super %d-%d\n", fsupc, jcolm1); #endif ito = xlsub[fsupc+1]; xlsub[jcolm1] = ito; xlsub[jcol] = ito; for (ifrom = jptr; ifrom < nextl; ++ifrom, ++ito) lsub[ito] = lsub[ifrom]; nextl = ito; } nsuper++; supno[jcol] = nsuper; } /* if a new supernode */ } /* else: jcol > 0 */ /* Tidy up the pointers before exit */ xsup[nsuper+1] = jcolp1; supno[jcolp1] = nsuper; xlsub[jcolp1] = nextl; return 0; }
mit
eunomie/nodegit
vendor/openssl/openssl/crypto/ocsp/ocsp_asn.c
829
7300
/* ocsp_asn.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2000. */ /* ==================================================================== * Copyright (c) 2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/ocsp.h> ASN1_SEQUENCE(OCSP_SIGNATURE) = { ASN1_SIMPLE(OCSP_SIGNATURE, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_SIGNATURE, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SIGNATURE, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_SIGNATURE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SIGNATURE) ASN1_SEQUENCE(OCSP_CERTID) = { ASN1_SIMPLE(OCSP_CERTID, hashAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_CERTID, issuerNameHash, ASN1_OCTET_STRING), ASN1_SIMPLE(OCSP_CERTID, issuerKeyHash, ASN1_OCTET_STRING), ASN1_SIMPLE(OCSP_CERTID, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(OCSP_CERTID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTID) ASN1_SEQUENCE(OCSP_ONEREQ) = { ASN1_SIMPLE(OCSP_ONEREQ, reqCert, OCSP_CERTID), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_ONEREQ, singleRequestExtensions, X509_EXTENSION, 0) } ASN1_SEQUENCE_END(OCSP_ONEREQ) IMPLEMENT_ASN1_FUNCTIONS(OCSP_ONEREQ) ASN1_SEQUENCE(OCSP_REQINFO) = { ASN1_EXP_OPT(OCSP_REQINFO, version, ASN1_INTEGER, 0), ASN1_EXP_OPT(OCSP_REQINFO, requestorName, GENERAL_NAME, 1), ASN1_SEQUENCE_OF(OCSP_REQINFO, requestList, OCSP_ONEREQ), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_REQINFO, requestExtensions, X509_EXTENSION, 2) } ASN1_SEQUENCE_END(OCSP_REQINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQINFO) ASN1_SEQUENCE(OCSP_REQUEST) = { ASN1_SIMPLE(OCSP_REQUEST, tbsRequest, OCSP_REQINFO), ASN1_EXP_OPT(OCSP_REQUEST, optionalSignature, OCSP_SIGNATURE, 0) } ASN1_SEQUENCE_END(OCSP_REQUEST) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQUEST) /* OCSP_RESPONSE templates */ ASN1_SEQUENCE(OCSP_RESPBYTES) = { ASN1_SIMPLE(OCSP_RESPBYTES, responseType, ASN1_OBJECT), ASN1_SIMPLE(OCSP_RESPBYTES, response, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OCSP_RESPBYTES) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPBYTES) ASN1_SEQUENCE(OCSP_RESPONSE) = { ASN1_SIMPLE(OCSP_RESPONSE, responseStatus, ASN1_ENUMERATED), ASN1_EXP_OPT(OCSP_RESPONSE, responseBytes, OCSP_RESPBYTES, 0) } ASN1_SEQUENCE_END(OCSP_RESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPONSE) ASN1_CHOICE(OCSP_RESPID) = { ASN1_EXP(OCSP_RESPID, value.byName, X509_NAME, 1), ASN1_EXP(OCSP_RESPID, value.byKey, ASN1_OCTET_STRING, 2) } ASN1_CHOICE_END(OCSP_RESPID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPID) ASN1_SEQUENCE(OCSP_REVOKEDINFO) = { ASN1_SIMPLE(OCSP_REVOKEDINFO, revocationTime, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_REVOKEDINFO, revocationReason, ASN1_ENUMERATED, 0) } ASN1_SEQUENCE_END(OCSP_REVOKEDINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REVOKEDINFO) ASN1_CHOICE(OCSP_CERTSTATUS) = { ASN1_IMP(OCSP_CERTSTATUS, value.good, ASN1_NULL, 0), ASN1_IMP(OCSP_CERTSTATUS, value.revoked, OCSP_REVOKEDINFO, 1), ASN1_IMP(OCSP_CERTSTATUS, value.unknown, ASN1_NULL, 2) } ASN1_CHOICE_END(OCSP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTSTATUS) ASN1_SEQUENCE(OCSP_SINGLERESP) = { ASN1_SIMPLE(OCSP_SINGLERESP, certId, OCSP_CERTID), ASN1_SIMPLE(OCSP_SINGLERESP, certStatus, OCSP_CERTSTATUS), ASN1_SIMPLE(OCSP_SINGLERESP, thisUpdate, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_SINGLERESP, nextUpdate, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SINGLERESP, singleExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_SINGLERESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SINGLERESP) ASN1_SEQUENCE(OCSP_RESPDATA) = { ASN1_EXP_OPT(OCSP_RESPDATA, version, ASN1_INTEGER, 0), ASN1_SIMPLE(OCSP_RESPDATA, responderId, OCSP_RESPID), ASN1_SIMPLE(OCSP_RESPDATA, producedAt, ASN1_GENERALIZEDTIME), ASN1_SEQUENCE_OF(OCSP_RESPDATA, responses, OCSP_SINGLERESP), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_RESPDATA, responseExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_RESPDATA) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPDATA) ASN1_SEQUENCE(OCSP_BASICRESP) = { ASN1_SIMPLE(OCSP_BASICRESP, tbsResponseData, OCSP_RESPDATA), ASN1_SIMPLE(OCSP_BASICRESP, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_BASICRESP, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_BASICRESP, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_BASICRESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_BASICRESP) ASN1_SEQUENCE(OCSP_CRLID) = { ASN1_EXP_OPT(OCSP_CRLID, crlUrl, ASN1_IA5STRING, 0), ASN1_EXP_OPT(OCSP_CRLID, crlNum, ASN1_INTEGER, 1), ASN1_EXP_OPT(OCSP_CRLID, crlTime, ASN1_GENERALIZEDTIME, 2) } ASN1_SEQUENCE_END(OCSP_CRLID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CRLID) ASN1_SEQUENCE(OCSP_SERVICELOC) = { ASN1_SIMPLE(OCSP_SERVICELOC, issuer, X509_NAME), ASN1_SEQUENCE_OF_OPT(OCSP_SERVICELOC, locator, ACCESS_DESCRIPTION) } ASN1_SEQUENCE_END(OCSP_SERVICELOC) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SERVICELOC)
mit
zmaruo/coreclr
src/pal/tests/palsuite/c_runtime/swscanf/test2/test2.c
62
1295
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================================ ** ** Source: test2.c ** ** Purpose: Test to see if swscanf handles whitespace correctly ** ** **==========================================================================*/ #include <palsuite.h> #include "../swscanf.h" /* * Tests out how it handles whitespace. Seems to accept anything that qualifies * as isspace (space, tab, vertical tab, line feed, carriage return and form * feed), even if it says it only wants spaces tabs and newlines. */ int __cdecl main(int argc, char *argv[]) { if (PAL_Initialize(argc, argv)) { return FAIL; } DoStrTest(convert("foo bar"), convert("foo %S"), "bar"); DoStrTest(convert("foo\tbar"), convert("foo %S"), "bar"); DoStrTest(convert("foo\nbar"), convert("foo %S"), "bar"); DoStrTest(convert("foo\rbar"), convert("foo %S"), "bar"); DoStrTest(convert("foo\vbar"), convert("foo %S"), "bar"); DoStrTest(convert("foo\fbar"), convert("foo %S"), "bar"); DoStrTest(convert("foo \t\n\r\v\fbar"), convert("foo %S"), "bar"); PAL_Terminate(); return PASS; }
mit
rkq/cxxexp
third-party/src/boost_1_56_0/libs/preprocessor/doc/examples/linear_fib.c
63
3046
# /* Copyright (C) 2002 # * Housemarque Oy # * http://www.housemarque.com # * # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # /* This example shows how BOOST_PP_WHILE() can be used for implementing macros. */ # # include <stdio.h> # # include <boost/preprocessor/arithmetic/add.hpp> # include <boost/preprocessor/arithmetic/sub.hpp> # include <boost/preprocessor/comparison/less_equal.hpp> # include <boost/preprocessor/control/while.hpp> # include <boost/preprocessor/list/adt.hpp> # include <boost/preprocessor/tuple/elem.hpp> # # /* First consider the following C implementation of Fibonacci. */ typedef struct linear_fib_state { int a0, a1, n; } linear_fib_state; static int linear_fib_c(linear_fib_state p) { return p.n; } static linear_fib_state linear_fib_f(linear_fib_state p) { linear_fib_state r = { p.a1, p.a0 + p.a1, p.n - 1 }; return r; } static int linear_fib(int n) { linear_fib_state p = { 0, 1, n }; while (linear_fib_c(p)) { p = linear_fib_f(p); } return p.a0; } # /* Then consider the following preprocessor implementation of Fibonacci. */ # # define LINEAR_FIB(n) LINEAR_FIB_D(1, n) # /* Since the macro is implemented using BOOST_PP_WHILE, the actual # * implementation takes a depth as a parameters so that it can be called # * inside a BOOST_PP_WHILE. The above easy-to-use version simply uses 1 # * as the depth and cannot be called inside a BOOST_PP_WHILE. # */ # # define LINEAR_FIB_D(d, n) \ BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_WHILE_ ## d(LINEAR_FIB_C, LINEAR_FIB_F, (0, 1, n))) # /* ^^^^ ^^^^^ ^^ ^^ ^^^^^^^ # * #1 #2 #3 #3 #4 # * # * 1) The state is a 3-element tuple. After the iteration is finished, the first # * element of the tuple is the result. # * # * 2) The WHILE primitive is "invoked" directly. BOOST_PP_WHILE(D, ...) # * can't be used because it would not be expanded by the preprocessor. # * # * 3) ???_C is the condition and ???_F is the iteration macro. # */ # # define LINEAR_FIB_C(d, p) \ /* p.n */ BOOST_PP_TUPLE_ELEM(3, 2, p) \ /**/ # # define LINEAR_FIB_F(d, p) \ ( \ /* p.a1 */ BOOST_PP_TUPLE_ELEM(3, 1, p), \ /* p.a0 + p.a1 */ BOOST_PP_ADD_D(d, BOOST_PP_TUPLE_ELEM(3, 0, p), BOOST_PP_TUPLE_ELEM(3, 1, p)), \ /* ^^ ^ \ * BOOST_PP_ADD() uses BOOST_PP_WHILE(). Therefore we \ * pass the recursion depth explicitly to BOOST_PP_ADD_D(). \ */ \ /* p.n - 1 */ BOOST_PP_DEC(BOOST_PP_TUPLE_ELEM(3, 2, p)) \ ) \ /**/ int main() { printf("linear_fib(10) = %d\n", linear_fib(10)); printf("LINEAR_FIB(10) = %d\n", LINEAR_FIB(10)); return 0; }
mit
Godin/coreclr
src/pal/prebuilt/idl/fusionpriv_i.c
66
3292
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 8.00.0603 */ /* @@MIDL_FILE_HEADING( ) */ #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IHistoryAssembly,0xe6096a07,0xe188,0x4a49,0x8d,0x50,0x2a,0x01,0x72,0xa0,0xd2,0x05); MIDL_DEFINE_GUID(IID, IID_IHistoryReader,0x1d23df4d,0xa1e2,0x4b8b,0x93,0xd6,0x6e,0xa3,0xdc,0x28,0x5a,0x54); MIDL_DEFINE_GUID(IID, IID_IFusionBindLog,0x67E9F87D,0x8B8A,0x4a90,0x9D,0x3E,0x85,0xED,0x5B,0x2D,0xCC,0x83); MIDL_DEFINE_GUID(IID, IID_IAssemblyManifestImport,0xde9a68ba,0x0fa2,0x11d3,0x94,0xaa,0x00,0xc0,0x4f,0xc3,0x08,0xff); MIDL_DEFINE_GUID(IID, IID_IApplicationContext,0x7c23ff90,0x33af,0x11d3,0x95,0xda,0x00,0xa0,0x24,0xa8,0x5b,0x51); MIDL_DEFINE_GUID(IID, IID_IAssemblyNameBinder,0x56972d9d,0x0f6c,0x47de,0xa0,0x38,0xe8,0x2d,0x5d,0xe3,0xa7,0x77); MIDL_DEFINE_GUID(IID, IID_IAssembly,0xff08d7d4,0x04c2,0x11d3,0x94,0xaa,0x00,0xc0,0x4f,0xc3,0x08,0xff); MIDL_DEFINE_GUID(IID, IID_IAssemblyBindingClosureEnumerator,0xb3f1e4ed,0xcb09,0x4b85,0x9a,0x1b,0x68,0x09,0x58,0x2f,0x1e,0xbc); MIDL_DEFINE_GUID(IID, IID_IAssemblyBindingClosure,0x415c226a,0xe513,0x41ba,0x96,0x51,0x9c,0x48,0xe9,0x7a,0xa5,0xde); MIDL_DEFINE_GUID(IID, IID_IAssemblyBindSink,0xaf0bc960,0x0b9a,0x11d3,0x95,0xca,0x00,0xa0,0x24,0xa8,0x5b,0x51); MIDL_DEFINE_GUID(IID, IID_IAssemblyBinding,0xcfe52a80,0x12bd,0x11d3,0x95,0xca,0x00,0xa0,0x24,0xa8,0x5b,0x51); MIDL_DEFINE_GUID(IID, IID_IAssemblyModuleImport,0xda0cd4b0,0x1117,0x11d3,0x95,0xca,0x00,0xa0,0x24,0xa8,0x5b,0x51); MIDL_DEFINE_GUID(IID, IID_IAssemblyScavenger,0x21b8916c,0xf28e,0x11d2,0xa4,0x73,0x00,0xcc,0xff,0x8e,0xf4,0x48); MIDL_DEFINE_GUID(IID, IID_ICodebaseList,0xD8FB9BD6,0x3969,0x11d3,0xB4,0xAF,0x00,0xC0,0x4F,0x8E,0xCB,0x26); MIDL_DEFINE_GUID(IID, IID_IDownloadMgr,0x0A6F16F8,0xACD7,0x11d3,0xB4,0xED,0x00,0xC0,0x4F,0x8E,0xCB,0x26); MIDL_DEFINE_GUID(IID, IID_IHostAssembly,0x711f7c2d,0x8234,0x4505,0xb0,0x2f,0x75,0x54,0xf4,0x6c,0xbf,0x29); MIDL_DEFINE_GUID(IID, IID_IHostAssemblyModuleImport,0xb6f2729d,0x6c0f,0x4944,0xb6,0x92,0xe5,0xa2,0xce,0x2c,0x6e,0x7a); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif
mit
Verteiron/JContainers
JContainers/lib/boost/libs/serialization/test/test_const_save_warn4_nvp.cpp
68
1117
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_const.cpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // compile only #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/nvp.hpp> using namespace boost::archive; struct A { template<class Archive> void serialize(Archive & ar, unsigned int version) { } }; // comment out this test case as a reminder not to keep inserting it !!! // we don't trap this as an error in order to permit things like // X * xptr; // save(..){ // ar << xptr; // } // // for rational - consider the following example from demo.cpp // // std::list<pair<trip_info, bus_route_info *> > schedule // // its not obvious to me how this can be cast to: // // std::list<pair<trip_info, const bus_route_info * const> > schedule void f4(text_oarchive & oa, A * const & a){ oa << BOOST_SERIALIZATION_NVP(a); }
mit
chcbaram/SmartRobotBD
Ex13_IMU/LIB_USB/DRV/usb_int.c
79
6310
/** ****************************************************************************** * @file usb_int.c * @author MCD Application Team * @version V4.0.0 * @date 28-August-2012 * @brief Endpoint CTR (Low and High) interrupt's service routines ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint16_t SaveRState; __IO uint16_t SaveTState; /* Extern variables ----------------------------------------------------------*/ extern void (*pEpInt_IN[7])(void); /* Handles IN interrupts */ extern void (*pEpInt_OUT[7])(void); /* Handles OUT interrupts */ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : CTR_LP. * Description : Low priority Endpoint Correct Transfer interrupt's service * routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CTR_LP(void) { __IO uint16_t wEPVal = 0; /* stay in loop while pending interrupts */ while (((wIstr = _GetISTR()) & ISTR_CTR) != 0) { /* extract highest priority endpoint number */ EPindex = (uint8_t)(wIstr & ISTR_EP_ID); if (EPindex == 0) { /* Decode and service control endpoint interrupt */ /* calling related service routine */ /* (Setup0_Process, In0_Process, Out0_Process) */ /* save RX & TX status */ /* and set both to NAK */ SaveRState = _GetENDPOINT(ENDP0); SaveTState = SaveRState & EPTX_STAT; SaveRState &= EPRX_STAT; _SetEPRxTxStatus(ENDP0,EP_RX_NAK,EP_TX_NAK); /* DIR bit = origin of the interrupt */ if ((wIstr & ISTR_DIR) == 0) { /* DIR = 0 */ /* DIR = 0 => IN int */ /* DIR = 0 implies that (EP_CTR_TX = 1) always */ _ClearEP_CTR_TX(ENDP0); In0_Process(); /* before terminate set Tx & Rx status */ _SetEPRxTxStatus(ENDP0,SaveRState,SaveTState); return; } else { /* DIR = 1 */ /* DIR = 1 & CTR_RX => SETUP or OUT int */ /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ wEPVal = _GetENDPOINT(ENDP0); if ((wEPVal &EP_SETUP) != 0) { _ClearEP_CTR_RX(ENDP0); /* SETUP bit kept frozen while CTR_RX = 1 */ Setup0_Process(); /* before terminate set Tx & Rx status */ _SetEPRxTxStatus(ENDP0,SaveRState,SaveTState); return; } else if ((wEPVal & EP_CTR_RX) != 0) { _ClearEP_CTR_RX(ENDP0); Out0_Process(); /* before terminate set Tx & Rx status */ _SetEPRxTxStatus(ENDP0,SaveRState,SaveTState); return; } } }/* if(EPindex == 0) */ else { /* Decode and service non control endpoints interrupt */ /* process related endpoint register */ wEPVal = _GetENDPOINT(EPindex); if ((wEPVal & EP_CTR_RX) != 0) { /* clear int flag */ _ClearEP_CTR_RX(EPindex); /* call OUT service function */ (*pEpInt_OUT[EPindex-1])(); } /* if((wEPVal & EP_CTR_RX) */ if ((wEPVal & EP_CTR_TX) != 0) { /* clear int flag */ _ClearEP_CTR_TX(EPindex); /* call IN service function */ (*pEpInt_IN[EPindex-1])(); } /* if((wEPVal & EP_CTR_TX) != 0) */ }/* if(EPindex == 0) else */ }/* while(...) */ } /******************************************************************************* * Function Name : CTR_HP. * Description : High Priority Endpoint Correct Transfer interrupt's service * routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CTR_HP(void) { uint32_t wEPVal = 0; while (((wIstr = _GetISTR()) & ISTR_CTR) != 0) { _SetISTR((uint16_t)CLR_CTR); /* clear CTR flag */ /* extract highest priority endpoint number */ EPindex = (uint8_t)(wIstr & ISTR_EP_ID); /* process related endpoint register */ wEPVal = _GetENDPOINT(EPindex); if ((wEPVal & EP_CTR_RX) != 0) { /* clear int flag */ _ClearEP_CTR_RX(EPindex); /* call OUT service function */ (*pEpInt_OUT[EPindex-1])(); } /* if((wEPVal & EP_CTR_RX) */ else if ((wEPVal & EP_CTR_TX) != 0) { /* clear int flag */ _ClearEP_CTR_TX(EPindex); /* call IN service function */ (*pEpInt_IN[EPindex-1])(); } /* if((wEPVal & EP_CTR_TX) != 0) */ }/* while(...) */ } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mit
jdegraft/Windows-universal-samples
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
81
5216
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario2_CardioidSound.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; Scenario2_CardioidSound::Scenario2_CardioidSound() : _rootPage(MainPage::Current) { InitializeComponent(); auto hr = _cardioidSound.Initialize(L"assets//MonoSound.wav"); if (SUCCEEDED(hr)) { _timer = ref new DispatcherTimer(); _timer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario2_CardioidSound::OnTimerTick); TimeSpan timespan; timespan.Duration = 10000 / 30; _timer->Interval = timespan; EnvironmentComboBox->SelectedIndex = static_cast<int>(_cardioidSound.GetEnvironment()); _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage); } else { if (hr == E_NOTIMPL) { _rootPage->NotifyUser("HRTF API is not supported on this platform. Use X3DAudio API instead - https://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933", NotifyType::ErrorMessage); } else { throw ref new COMException(hr); } } _initialized = SUCCEEDED(hr); } void SDKTemplate::Scenario2_CardioidSound::EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { if (_initialized) { _cardioidSound.SetEnvironment(static_cast<HrtfEnvironment>(EnvironmentComboBox->SelectedIndex)); } } void SDKTemplate::Scenario2_CardioidSound::ScalingSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { UpdateScalingAndOrder(); } void SDKTemplate::Scenario2_CardioidSound::OrderSlider_ValudChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { UpdateScalingAndOrder(); } void SDKTemplate::Scenario2_CardioidSound::YawSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _yaw = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::PitchSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _pitch = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::RollSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _roll = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (_initialized) { _cardioidSound.Start(); _state = PlayState::Playing; _rootPage->NotifyUser("Playing", NotifyType::StatusMessage); } } void SDKTemplate::Scenario2_CardioidSound::StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { if (_initialized) { _cardioidSound.Stop(); _state = PlayState::Stopped; _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage); } } void SDKTemplate::Scenario2_CardioidSound::OnTimerTick(Object^ sender, Object^ e) { // Update the sound position and orientation on every dispatcher timer tick. _cardioidSound.OnUpdate(_x, _y, _z, _pitch, _yaw, _roll); } void SDKTemplate::Scenario2_CardioidSound::UpdateScalingAndOrder() { if (_initialized) { _timer->Stop(); _cardioidSound.ConfigureApo(static_cast<float>(ScalingSlider->Value), static_cast<float>(OrderSlider->Value)); _timer->Start(); if (_state == PlayState::Playing) { _cardioidSound.Start(); } } } void SDKTemplate::Scenario2_CardioidSound::SourcePositionX_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _x = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::SourcePositionY_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _y = static_cast<float>(e->NewValue); } void SDKTemplate::Scenario2_CardioidSound::SourcePositionZ_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e) { _z = static_cast<float>(e->NewValue); }
mit
EVE-Team/GameDesign
cocos2d/extensions/Particle3D/PU/CCPUGravityAffectorTranslator.cpp
97
2574
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCPUGravityAffectorTranslator.h" #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h" #include "extensions/Particle3D/PU/CCPUDynamicAttribute.h" #include "extensions/Particle3D/PU/CCPUDynamicAttributeTranslator.h" NS_CC_BEGIN PUGravityAffectorTranslator::PUGravityAffectorTranslator() { } //------------------------------------------------------------------------- bool PUGravityAffectorTranslator::translateChildProperty( PUScriptCompiler* compiler, PUAbstractNode *node ) { PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>(node); PUAffector* af = static_cast<PUAffector*>(prop->parent->context); PUGravityAffector* affector = static_cast<PUGravityAffector*>(af); if (prop->name == token[TOKEN_GRAVITY]) { if (passValidateProperty(compiler, prop, token[TOKEN_GRAVITY], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { affector->setGravity(val); return true; } } } return false; } bool PUGravityAffectorTranslator::translateChildObject( PUScriptCompiler* compiler, PUAbstractNode *node ) { // No objects return false; } NS_CC_END
mit
JosephTremoulet/coreclr
src/pal/tests/palsuite/c_runtime/_vsnwprintf_s/test16/test16.cpp
106
2435
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: test16.c ** ** Purpose: Test #16 for the _vsnwprintf_s function. ** ** **===================================================================*/ #include <palsuite.h> #include "../_vsnwprintf_s.h" /* memcmp is used to verify the results, so this test is dependent on it. */ /* ditto with wcslen */ int __cdecl main(int argc, char *argv[]) { double val = 2560.001; double neg = -2560.001; if (PAL_Initialize(argc, argv) != 0) { return(FAIL); } DoDoubleTest(convert("foo %f"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %lf"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %hf"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %Lf"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %I64f"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %12f"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %-12f"), val, convert("foo 2560.001000 "), convert("foo 2560.001000 ")); DoDoubleTest(convert("foo %.1f"), val, convert("foo 2560.0"), convert("foo 2560.0")); DoDoubleTest(convert("foo %.8f"), val, convert("foo 2560.00100000"), convert("foo 2560.00100000")); DoDoubleTest(convert("foo %012f"), val, convert("foo 02560.001000"), convert("foo 02560.001000")); DoDoubleTest(convert("foo %#f"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %+f"), val, convert("foo +2560.001000"), convert("foo +2560.001000")); DoDoubleTest(convert("foo % f"), val, convert("foo 2560.001000"), convert("foo 2560.001000")); DoDoubleTest(convert("foo %+f"), neg, convert("foo -2560.001000"), convert("foo -2560.001000")); DoDoubleTest(convert("foo % f"), neg, convert("foo -2560.001000"), convert("foo -2560.001000")); PAL_Terminate(); return PASS; }
mit
pastaread/TanksBattle
cocos2d/external/Box2D/Dynamics/Joints/b2MotorJoint.cpp
368
8087
/* * Copyright (c) 2006-2012 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/Joints/b2MotorJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Point-to-point constraint // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB) { bodyA = bA; bodyB = bB; b2Vec2 xB = bodyB->GetPosition(); linearOffset = bodyA->GetLocalPoint(xB); float32 angleA = bodyA->GetAngle(); float32 angleB = bodyB->GetAngle(); angularOffset = angleB - angleA; } b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def) : b2Joint(def) { m_linearOffset = def->linearOffset; m_angularOffset = def->angularOffset; m_linearImpulse.SetZero(); m_angularImpulse = 0.0f; m_maxForce = def->maxForce; m_maxTorque = def->maxTorque; m_correctionFactor = def->correctionFactor; } void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); // Compute the effective mass matrix. m_rA = b2Mul(qA, -m_localCenterA); m_rB = b2Mul(qB, -m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Mat22 K; K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; m_linearMass = K.GetInverse(); m_angularMass = iA + iB; if (m_angularMass > 0.0f) { m_angularMass = 1.0f / m_angularMass; } m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset); m_angularError = aB - aA - m_angularOffset; if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_linearImpulse *= data.step.dtRatio; m_angularImpulse *= data.step.dtRatio; b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); } else { m_linearImpulse.SetZero(); m_angularImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; float32 h = data.step.dt; float32 inv_h = data.step.inv_dt; // Solve angular friction { float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError; float32 impulse = -m_angularMass * Cdot; float32 oldImpulse = m_angularImpulse; float32 maxImpulse = h * m_maxTorque; m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError; b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); b2Vec2 oldImpulse = m_linearImpulse; m_linearImpulse += impulse; float32 maxImpulse = h * m_maxForce; if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { m_linearImpulse.Normalize(); m_linearImpulse *= maxImpulse; } impulse = m_linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; wB += iB * b2Cross(m_rB, impulse); } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data) { B2_NOT_USED(data); return true; } b2Vec2 b2MotorJoint::GetAnchorA() const { return m_bodyA->GetPosition(); } b2Vec2 b2MotorJoint::GetAnchorB() const { return m_bodyB->GetPosition(); } b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const { return inv_dt * m_linearImpulse; } float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_angularImpulse; } void b2MotorJoint::SetMaxForce(float32 force) { b2Assert(b2IsValid(force) && force >= 0.0f); m_maxForce = force; } float32 b2MotorJoint::GetMaxForce() const { return m_maxForce; } void b2MotorJoint::SetMaxTorque(float32 torque) { b2Assert(b2IsValid(torque) && torque >= 0.0f); m_maxTorque = torque; } float32 b2MotorJoint::GetMaxTorque() const { return m_maxTorque; } void b2MotorJoint::SetCorrectionFactor(float32 factor) { b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f); m_correctionFactor = factor; } float32 b2MotorJoint::GetCorrectionFactor() const { return m_correctionFactor; } void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset) { if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_linearOffset = linearOffset; } } const b2Vec2& b2MotorJoint::GetLinearOffset() const { return m_linearOffset; } void b2MotorJoint::SetAngularOffset(float32 angularOffset) { if (angularOffset != m_angularOffset) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_angularOffset = angularOffset; } } float32 b2MotorJoint::GetAngularOffset() const { return m_angularOffset; } void b2MotorJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2MotorJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y); b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset); b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
mit
Krugercoin/krugercoins
BuildDeps/deps/ssl/crypto/dh/p1024.c
881
4162
/* crypto/dh/p1024.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <openssl/bn.h> #include <openssl/asn1.h> #include <openssl/dh.h> #include <openssl/pem.h> unsigned char data[]={0x97,0xF6,0x42,0x61,0xCA,0xB5,0x05,0xDD, 0x28,0x28,0xE1,0x3F,0x1D,0x68,0xB6,0xD3, 0xDB,0xD0,0xF3,0x13,0x04,0x7F,0x40,0xE8, 0x56,0xDA,0x58,0xCB,0x13,0xB8,0xA1,0xBF, 0x2B,0x78,0x3A,0x4C,0x6D,0x59,0xD5,0xF9, 0x2A,0xFC,0x6C,0xFF,0x3D,0x69,0x3F,0x78, 0xB2,0x3D,0x4F,0x31,0x60,0xA9,0x50,0x2E, 0x3E,0xFA,0xF7,0xAB,0x5E,0x1A,0xD5,0xA6, 0x5E,0x55,0x43,0x13,0x82,0x8D,0xA8,0x3B, 0x9F,0xF2,0xD9,0x41,0xDE,0xE9,0x56,0x89, 0xFA,0xDA,0xEA,0x09,0x36,0xAD,0xDF,0x19, 0x71,0xFE,0x63,0x5B,0x20,0xAF,0x47,0x03, 0x64,0x60,0x3C,0x2D,0xE0,0x59,0xF5,0x4B, 0x65,0x0A,0xD8,0xFA,0x0C,0xF7,0x01,0x21, 0xC7,0x47,0x99,0xD7,0x58,0x71,0x32,0xBE, 0x9B,0x99,0x9B,0xB9,0xB7,0x87,0xE8,0xAB, }; main() { DH *dh; dh=DH_new(); dh->p=BN_bin2bn(data,sizeof(data),NULL); dh->g=BN_new(); BN_set_word(dh->g,2); PEM_write_DHparams(stdout,dh); }
mit
TrustPlus/TrustPlus
src/keystore.cpp
1138
5819
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "keystore.h" #include "script.h" bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const { CKey key; if (!GetKey(address, key)) return false; vchPubKeyOut = key.GetPubKey(); return true; } bool CBasicKeyStore::AddKey(const CKey& key) { bool fCompressed = false; CSecret secret = key.GetSecret(fCompressed); { LOCK(cs_KeyStore); mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed); } return true; } bool CBasicKeyStore::AddCScript(const CScript& redeemScript) { { LOCK(cs_KeyStore); mapScripts[redeemScript.GetID()] = redeemScript; } return true; } bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const { bool result; { LOCK(cs_KeyStore); result = (mapScripts.count(hash) > 0); } return result; } bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const { { LOCK(cs_KeyStore); ScriptMap::const_iterator mi = mapScripts.find(hash); if (mi != mapScripts.end()) { redeemScriptOut = (*mi).second; return true; } } return false; } bool CCryptoKeyStore::SetCrypted() { { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; } return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; CKey key; key.SetPubKey(vchPubKey); key.SetSecret(vchSecret); if (key.GetPubKey() == vchPubKey) break; return false; } vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKey(const CKey& key) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKey(key); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CPubKey vchPubKey = key.GetPubKey(); bool fCompressed; if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.SetPubKey(vchPubKey); keyOut.SetSecret(vchSecret); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { CKey key; if (!key.SetSecret(mKey.second.first, mKey.second.second)) return false; const CPubKey vchPubKey = key.GetPubKey(); std::vector<unsigned char> vchCryptedSecret; bool fCompressed; if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; }
mit
xunmengfeng/WinObjC
deps/3rdparty/icu/icu/source/test/intltest/tokiter.cpp
376
3040
/* ********************************************************************** * Copyright (c) 2004-2011, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: March 22 2004 * Since: ICU 3.0 ********************************************************************** */ #include "tokiter.h" #include "textfile.h" #include "patternprops.h" #include "util.h" #include "uprops.h" TokenIterator::TokenIterator(TextFile* r) { reader = r; done = haveLine = FALSE; pos = lastpos = -1; } TokenIterator::~TokenIterator() { } UBool TokenIterator::next(UnicodeString& token, UErrorCode& ec) { if (done || U_FAILURE(ec)) { return FALSE; } token.truncate(0); for (;;) { if (!haveLine) { if (!reader->readLineSkippingComments(line, ec)) { done = TRUE; return FALSE; } haveLine = TRUE; pos = 0; } lastpos = pos; if (!nextToken(token, ec)) { haveLine = FALSE; if (U_FAILURE(ec)) return FALSE; continue; } return TRUE; } } int32_t TokenIterator::getLineNumber() const { return reader->getLineNumber(); } /** * Read the next token from 'this->line' and append it to 'token'. * Tokens are separated by Pattern_White_Space. Tokens may also be * delimited by double or single quotes. The closing quote must match * the opening quote. If a '#' is encountered, the rest of the line * is ignored, unless it is backslash-escaped or within quotes. * @param token the token is appended to this StringBuffer * @param ec input-output error code * @return TRUE if a valid token is found, or FALSE if the end * of the line is reached or an error occurs */ UBool TokenIterator::nextToken(UnicodeString& token, UErrorCode& ec) { ICU_Utility::skipWhitespace(line, pos, TRUE); if (pos == line.length()) { return FALSE; } UChar c = line.charAt(pos++); UChar quote = 0; switch (c) { case 34/*'"'*/: case 39/*'\\'*/: quote = c; break; case 35/*'#'*/: return FALSE; default: token.append(c); break; } while (pos < line.length()) { c = line.charAt(pos); // 16-bit ok if (c == 92/*'\\'*/) { UChar32 c32 = line.unescapeAt(pos); if (c32 < 0) { ec = U_MALFORMED_UNICODE_ESCAPE; return FALSE; } token.append(c32); } else if ((quote != 0 && c == quote) || (quote == 0 && PatternProps::isWhiteSpace(c))) { ++pos; return TRUE; } else if (quote == 0 && c == '#') { return TRUE; // do NOT increment } else { token.append(c); ++pos; } } if (quote != 0) { ec = U_UNTERMINATED_QUOTE; return FALSE; } return TRUE; }
mit
kishoredbn/barrelfish
lib/devif/backends/net/mlx4/drivers/infiniband/hw/mthca/mthca_pd.c
15490
2597
/* * Copyright (c) 2004 Topspin Communications. All rights reserved. * Copyright (c) 2005 Cisco Systems. All rights reserved. * Copyright (c) 2005 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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. */ #include <linux/errno.h> #include "mthca_dev.h" int mthca_pd_alloc(struct mthca_dev *dev, int privileged, struct mthca_pd *pd) { int err = 0; pd->privileged = privileged; atomic_set(&pd->sqp_count, 0); pd->pd_num = mthca_alloc(&dev->pd_table.alloc); if (pd->pd_num == -1) return -ENOMEM; if (privileged) { err = mthca_mr_alloc_notrans(dev, pd->pd_num, MTHCA_MPT_FLAG_LOCAL_READ | MTHCA_MPT_FLAG_LOCAL_WRITE, &pd->ntmr); if (err) mthca_free(&dev->pd_table.alloc, pd->pd_num); } return err; } void mthca_pd_free(struct mthca_dev *dev, struct mthca_pd *pd) { if (pd->privileged) mthca_free_mr(dev, &pd->ntmr); mthca_free(&dev->pd_table.alloc, pd->pd_num); } int mthca_init_pd_table(struct mthca_dev *dev) { return mthca_alloc_init(&dev->pd_table.alloc, dev->limits.num_pds, (1 << 24) - 1, dev->limits.reserved_pds); } void mthca_cleanup_pd_table(struct mthca_dev *dev) { /* XXX check if any PDs are still allocated? */ mthca_alloc_cleanup(&dev->pd_table.alloc); }
mit
gdos/WinObjC
deps/3rdparty/iculegacy/source/samples/numfmt/capi.c
388
2460
/******************************************************************** * COPYRIGHT: * Copyright (c) 1999-2002, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ #include "unicode/unum.h" #include "unicode/ustring.h" #include <stdio.h> #include <stdlib.h> static void uprintf(const UChar* str) { char buf[256]; u_austrcpy(buf, str); printf("%s", buf); } void capi() { UNumberFormat *fmt; UErrorCode status = U_ZERO_ERROR; /* The string "987654321.123" as UChars */ UChar str[] = { 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2E, 0x31, 0x32, 0x33, 0 }; UChar buf[256]; int32_t needed; double a; /* Create a formatter for the US locale */ fmt = unum_open( UNUM_DECIMAL, /* style */ 0, /* pattern */ 0, /* patternLength */ "en_US", /* locale */ 0, /* parseErr */ &status); if (U_FAILURE(status)) { printf("FAIL: unum_open\n"); exit(1); } /* Use the formatter to parse a number. When using the C API, we have to specify whether we want a double or a long in advance. We pass in NULL for the position pointer in order to get the default behavior which is to parse from the start. */ a = unum_parseDouble(fmt, str, u_strlen(str), NULL, &status); if (U_FAILURE(status)) { printf("FAIL: unum_parseDouble\n"); exit(1); } /* Show the result */ printf("unum_parseDouble(\""); uprintf(str); printf("\") => %g\n", a); /* Use the formatter to format the same number back into a string in the US locale. The return value is the buffer size needed. We're pretty sure we have enough space, but in a production application one would check this value. We pass in NULL for the UFieldPosition pointer because we don't care to receive that data. */ needed = unum_formatDouble(fmt, a, buf, 256, NULL, &status); if (U_FAILURE(status)) { printf("FAIL: format_parseDouble\n"); exit(1); } /* Show the result */ printf("unum_formatDouble(%g) => \"", a); uprintf(buf); printf("\"\n"); /* Release the storage used by the formatter */ unum_close(fmt); }
mit
x13945/Android-ImageMagick
library/src/main/jni/jasper-1.900.1/src/libjasper/jpc/jpc_dec.c
149
59860
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "jasper/jas_types.h" #include "jasper/jas_math.h" #include "jasper/jas_tvp.h" #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jpc_fix.h" #include "jpc_dec.h" #include "jpc_cs.h" #include "jpc_mct.h" #include "jpc_t2dec.h" #include "jpc_t1dec.h" #include "jpc_math.h" /******************************************************************************\ * \******************************************************************************/ #define JPC_MHSOC 0x0001 /* In the main header, expecting a SOC marker segment. */ #define JPC_MHSIZ 0x0002 /* In the main header, expecting a SIZ marker segment. */ #define JPC_MH 0x0004 /* In the main header, expecting "other" marker segments. */ #define JPC_TPHSOT 0x0008 /* In a tile-part header, expecting a SOT marker segment. */ #define JPC_TPH 0x0010 /* In a tile-part header, expecting "other" marker segments. */ #define JPC_MT 0x0020 /* In the main trailer. */ typedef struct { uint_fast16_t id; /* The marker segment type. */ int validstates; /* The states in which this type of marker segment can be validly encountered. */ int (*action)(jpc_dec_t *dec, jpc_ms_t *ms); /* The action to take upon encountering this type of marker segment. */ } jpc_dec_mstabent_t; /******************************************************************************\ * \******************************************************************************/ /* COD/COC parameters have been specified. */ #define JPC_CSET 0x0001 /* QCD/QCC parameters have been specified. */ #define JPC_QSET 0x0002 /* COD/COC parameters set from a COC marker segment. */ #define JPC_COC 0x0004 /* QCD/QCC parameters set from a QCC marker segment. */ #define JPC_QCC 0x0008 /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jpc_dec_dump(jpc_dec_t *dec, FILE *out); jpc_ppxstab_t *jpc_ppxstab_create(void); void jpc_ppxstab_destroy(jpc_ppxstab_t *tab); int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents); int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent); jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab); int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab); jpc_ppxstabent_t *jpc_ppxstabent_create(void); void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent); int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist); jpc_streamlist_t *jpc_streamlist_create(void); int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream); jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno); void jpc_streamlist_destroy(jpc_streamlist_t *streamlist); jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno); static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps); static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp); static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod); static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc); static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags); static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd); static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc); static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags); static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn); static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp); static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp); static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset); static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc); static int jpc_dec_decode(jpc_dec_t *dec); static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in); static void jpc_dec_destroy(jpc_dec_t *dec); static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize); static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps); static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits); static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile); static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms); static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts); static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id); /******************************************************************************\ * Global data. \******************************************************************************/ jpc_dec_mstabent_t jpc_dec_mstab[] = { {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc}, {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot}, {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod}, {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc}, {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz}, {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod}, {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc}, {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn}, {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd}, {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc}, {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc}, {JPC_MS_TLM, JPC_MH, 0}, {JPC_MS_PLM, JPC_MH, 0}, {JPC_MS_PLT, JPC_TPH, 0}, {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm}, {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt}, {JPC_MS_SOP, 0, 0}, {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg}, {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com}, {0, JPC_MH | JPC_TPH, jpc_dec_process_unk} }; /******************************************************************************\ * The main entry point for the JPEG-2000 decoder. \******************************************************************************/ jas_image_t *jpc_decode(jas_stream_t *in, char *optstr) { jpc_dec_importopts_t opts; jpc_dec_t *dec; jas_image_t *image; dec = 0; if (jpc_dec_parseopts(optstr, &opts)) { goto error; } jpc_initluts(); if (!(dec = jpc_dec_create(&opts, in))) { goto error; } /* Do most of the work. */ if (jpc_dec_decode(dec)) { goto error; } if (jas_image_numcmpts(dec->image) >= 3) { jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(dec->image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(dec->image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(dec->image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Save the return value. */ image = dec->image; /* Stop the image from being discarded. */ dec->image = 0; /* Destroy decoder. */ jpc_dec_destroy(dec); return image; error: if (dec) { jpc_dec_destroy(dec); } return 0; } typedef enum { OPT_MAXLYRS, OPT_MAXPKTS, OPT_DEBUG } optid_t; jas_taginfo_t decopts[] = { {OPT_MAXLYRS, "maxlyrs"}, {OPT_MAXPKTS, "maxpkts"}, {OPT_DEBUG, "debug"}, {-1, 0} }; static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts) { jas_tvparser_t *tvp; opts->debug = 0; opts->maxlyrs = JPC_MAXLYRS; opts->maxpkts = -1; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { return -1; } while (!jas_tvparser_next(tvp)) { switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, jas_tvparser_gettag(tvp)))->id) { case OPT_MAXLYRS: opts->maxlyrs = atoi(jas_tvparser_getval(tvp)); break; case OPT_DEBUG: opts->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_MAXPKTS: opts->maxpkts = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); return 0; } /******************************************************************************\ * Code for table-driven code stream decoder. \******************************************************************************/ static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id) { jpc_dec_mstabent_t *mstabent; for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) { if (mstabent->id == id) { break; } } return mstabent; } static int jpc_dec_decode(jpc_dec_t *dec) { jpc_ms_t *ms; jpc_dec_mstabent_t *mstabent; int ret; jpc_cstate_t *cstate; if (!(cstate = jpc_cstate_create())) { return -1; } dec->cstate = cstate; /* Initially, we should expect to encounter a SOC marker segment. */ dec->state = JPC_MHSOC; for (;;) { /* Get the next marker segment in the code stream. */ if (!(ms = jpc_getms(dec->in, cstate))) { jas_eprintf("cannot get marker segment\n"); return -1; } mstabent = jpc_dec_mstab_lookup(ms->id); assert(mstabent); /* Ensure that this type of marker segment is permitted at this point in the code stream. */ if (!(dec->state & mstabent->validstates)) { jas_eprintf("unexpected marker segment type\n"); jpc_ms_destroy(ms); return -1; } /* Process the marker segment. */ if (mstabent->action) { ret = (*mstabent->action)(dec, ms); } else { /* No explicit action is required. */ ret = 0; } /* Destroy the marker segment. */ jpc_ms_destroy(ms); if (ret < 0) { return -1; } else if (ret > 0) { break; } } return 0; } static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms) { int cmptno; jpc_dec_cmpt_t *cmpt; jpc_crg_t *crg; crg = &ms->parms.crg; for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno, ++cmpt) { /* Ignore the information in the CRG marker segment for now. This information serves no useful purpose for decoding anyhow. Some other parts of the code need to be changed if these lines are uncommented. cmpt->hsubstep = crg->comps[cmptno].hoff; cmpt->vsubstep = crg->comps[cmptno].voff; */ } return 0; } static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate warnings about unused variables. */ ms = 0; /* We should expect to encounter a SIZ marker segment next. */ dec->state = JPC_MHSIZ; return 0; } static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; jpc_sot_t *sot = &ms->parms.sot; jas_image_cmptparm_t *compinfos; jas_image_cmptparm_t *compinfo; jpc_dec_cmpt_t *cmpt; int cmptno; if (dec->state == JPC_MH) { compinfos = jas_malloc(dec->numcomps * sizeof(jas_image_cmptparm_t)); assert(compinfos); for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos; cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) { compinfo->tlx = 0; compinfo->tly = 0; compinfo->prec = cmpt->prec; compinfo->sgnd = cmpt->sgnd; compinfo->width = cmpt->width; compinfo->height = cmpt->height; compinfo->hstep = cmpt->hstep; compinfo->vstep = cmpt->vstep; } if (!(dec->image = jas_image_create(dec->numcomps, compinfos, JAS_CLRSPC_UNKNOWN))) { return -1; } jas_free(compinfos); /* Is the packet header information stored in PPM marker segments in the main header? */ if (dec->ppmstab) { /* Convert the PPM marker segment data into a collection of streams (one stream per tile-part). */ if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) { abort(); } jpc_ppxstab_destroy(dec->ppmstab); dec->ppmstab = 0; } } if (sot->len > 0) { dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len - 4 + sot->len; } else { dec->curtileendoff = 0; } if (JAS_CAST(int, sot->tileno) > dec->numtiles) { jas_eprintf("invalid tile number in SOT marker segment\n"); return -1; } /* Set the current tile. */ dec->curtile = &dec->tiles[sot->tileno]; tile = dec->curtile; /* Ensure that this is the expected part number. */ if (sot->partno != tile->partno) { return -1; } if (tile->numparts > 0 && sot->partno >= tile->numparts) { return -1; } if (!tile->numparts && sot->numparts > 0) { tile->numparts = sot->numparts; } tile->pptstab = 0; switch (tile->state) { case JPC_TILE_INIT: /* This is the first tile-part for this tile. */ tile->state = JPC_TILE_ACTIVE; assert(!tile->cp); if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) { return -1; } jpc_dec_cp_resetflags(dec->cp); break; default: if (sot->numparts == sot->partno - 1) { tile->state = JPC_TILE_ACTIVELAST; } break; } /* Note: We do not increment the expected tile-part number until all processing for this tile-part is complete. */ /* We should expect to encounter other tile-part header marker segments next. */ dec->state = JPC_TPH; return 0; } static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; int pos; /* Eliminate compiler warnings about unused variables. */ ms = 0; if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (!jpc_dec_cp_isvalid(tile->cp)) { return -1; } jpc_dec_cp_prepare(tile->cp); if (jpc_dec_tileinit(dec, tile)) { return -1; } } /* Are packet headers stored in the main header or tile-part header? */ if (dec->pkthdrstreams) { /* Get the stream containing the packet header data for this tile-part. */ if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) { return -1; } } if (tile->pptstab) { if (!tile->pkthdrstream) { if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) { return -1; } } pos = jas_stream_tell(tile->pkthdrstream); jas_stream_seek(tile->pkthdrstream, 0, SEEK_END); if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) { return -1; } jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET); jpc_ppxstab_destroy(tile->pptstab); tile->pptstab = 0; } if (jas_getdbglevel() >= 10) { jpc_dec_dump(dec, stderr); } if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream : dec->in, dec->in)) { jas_eprintf("jpc_dec_decodepkts failed\n"); return -1; } /* Gobble any unconsumed tile data. */ if (dec->curtileendoff > 0) { long curoff; uint_fast32_t n; curoff = jas_stream_getrwcount(dec->in); if (curoff < dec->curtileendoff) { n = dec->curtileendoff - curoff; jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n", (unsigned long) n); while (n-- > 0) { if (jas_stream_getc(dec->in) == EOF) { jas_eprintf("read error\n"); return -1; } } } else if (curoff > dec->curtileendoff) { jas_eprintf("warning: not enough tile data (%lu bytes)\n", (unsigned long) curoff - dec->curtileendoff); } } if (tile->numparts > 0 && tile->partno == tile->numparts - 1) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } jpc_dec_tilefini(dec, tile); } dec->curtile = 0; /* Increment the expected tile-part number. */ ++tile->partno; /* We should expect to encounter a SOT marker segment next. */ dec->state = JPC_TPHSOT; return 0; } static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int rlvlno; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_prc_t *prc; int bndno; jpc_tsfb_band_t *bnd; int bandno; jpc_dec_ccp_t *ccp; int prccnt; jpc_dec_cblk_t *cblk; int cblkcnt; uint_fast32_t tlprcxstart; uint_fast32_t tlprcystart; uint_fast32_t brprcxend; uint_fast32_t brprcyend; uint_fast32_t tlcbgxstart; uint_fast32_t tlcbgystart; uint_fast32_t brcbgxend; uint_fast32_t brcbgyend; uint_fast32_t cbgxstart; uint_fast32_t cbgystart; uint_fast32_t cbgxend; uint_fast32_t cbgyend; uint_fast32_t tlcblkxstart; uint_fast32_t tlcblkystart; uint_fast32_t brcblkxend; uint_fast32_t brcblkyend; uint_fast32_t cblkxstart; uint_fast32_t cblkystart; uint_fast32_t cblkxend; uint_fast32_t cblkyend; uint_fast32_t tmpxstart; uint_fast32_t tmpystart; uint_fast32_t tmpxend; uint_fast32_t tmpyend; jpc_dec_cp_t *cp; jpc_tsfb_band_t bnds[64]; jpc_pchg_t *pchg; int pchgno; jpc_dec_cmpt_t *cmpt; cp = tile->cp; tile->realmode = 0; if (cp->mctid == JPC_MCT_ICT) { tile->realmode = 1; } for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { ccp = &tile->cp->ccps[compno]; if (ccp->qmfbid == JPC_COX_INS) { tile->realmode = 1; } tcomp->numrlvls = ccp->numrlvls; if (!(tcomp->rlvls = jas_malloc(tcomp->numrlvls * sizeof(jpc_dec_rlvl_t)))) { return -1; } if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, cmpt->vstep)))) { return -1; } if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, tcomp->numrlvls - 1))) { return -1; } { jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); } for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, tcomp->numrlvls - 1 - rlvlno); rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, tcomp->numrlvls - 1 - rlvlno); rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, tcomp->numrlvls - 1 - rlvlno); rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, tcomp->numrlvls - 1 - rlvlno); rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, rlvl->prcheightexpn) << rlvl->prcheightexpn; brprcxend = JPC_CEILDIVPOW2(rlvl->xend, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; brprcyend = JPC_CEILDIVPOW2(rlvl->yend, rlvl->prcheightexpn) << rlvl->prcheightexpn; rlvl->numhprcs = (brprcxend - tlprcxstart) >> rlvl->prcwidthexpn; rlvl->numvprcs = (brprcyend - tlprcystart) >> rlvl->prcheightexpn; rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { rlvl->bands = 0; rlvl->numprcs = 0; rlvl->numhprcs = 0; rlvl->numvprcs = 0; continue; } if (!rlvlno) { tlcbgxstart = tlprcxstart; tlcbgystart = tlprcystart; brcbgxend = brprcxend; brcbgyend = brprcyend; rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, rlvl->cbgheightexpn); rlvl->numbands = (!rlvlno) ? 1 : 3; if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_dec_band_t)))) { return -1; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bnd = &bnds[bndno]; band->orient = bnd->orient; band->stepsize = ccp->stepsizes[bndno]; band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, tcomp->numrlvls - 1, rlvlno, band->orient); band->absstepsize = jpc_calcabsstepsize(band->stepsize, cmpt->prec + band->analgain); band->numbps = ccp->numguardbits + JPC_QCX_GETEXPN(band->stepsize) - 1; band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? (JPC_PREC - 1 - band->numbps) : ccp->roishift; band->data = 0; band->prcs = 0; if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { continue; } if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); assert(rlvl->numprcs); if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_dec_prc_t)))) { return -1; } /************************************************/ cbgxstart = tlcbgxstart; cbgystart = tlcbgystart; for (prccnt = rlvl->numprcs, prc = band->prcs; prccnt > 0; --prccnt, ++prc) { cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); if (prc->xend > prc->xstart && prc->yend > prc->ystart) { tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; brcblkxend = JPC_CEILDIVPOW2(prc->xend, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; brcblkyend = JPC_CEILDIVPOW2(prc->yend, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; prc->numhcblks = (brcblkxend - tlcblkxstart) >> rlvl->cblkwidthexpn; prc->numvcblks = (brcblkyend - tlcblkystart) >> rlvl->cblkheightexpn; prc->numcblks = prc->numhcblks * prc->numvcblks; assert(prc->numcblks > 0); if (!(prc->incltagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->numimsbstagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_dec_cblk_t)))) { return -1; } cblkxstart = cbgxstart; cblkystart = cbgystart; for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); tmpxstart = JAS_MAX(cblkxstart, prc->xstart); tmpystart = JAS_MAX(cblkystart, prc->ystart); tmpxend = JAS_MIN(cblkxend, prc->xend); tmpyend = JAS_MIN(cblkyend, prc->yend); if (tmpxend > tmpxstart && tmpyend > tmpystart) { cblk->firstpassno = -1; cblk->mqdec = 0; cblk->nulldec = 0; cblk->flags = 0; cblk->numpasses = 0; cblk->segs.head = 0; cblk->segs.tail = 0; cblk->curseg = 0; cblk->numimsbs = 0; cblk->numlenbits = 3; cblk->flags = 0; if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); ++cblk; --cblkcnt; } cblkxstart += 1 << rlvl->cblkwidthexpn; if (cblkxstart >= cbgxend) { cblkxstart = cbgxstart; cblkystart += 1 << rlvl->cblkheightexpn; } } } else { prc->cblks = 0; prc->incltagtree = 0; prc->numimsbstagtree = 0; } cbgxstart += 1 << rlvl->cbgwidthexpn; if (cbgxstart >= brcbgxend) { cbgxstart = tlcbgxstart; cbgystart += 1 << rlvl->cbgheightexpn; } } /********************************************/ } } } if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { return -1; } for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); ++pchgno) { pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); assert(pchg); jpc_pi_addpchg(tile->pi, pchg); } jpc_pi_init(tile->pi); return 0; } static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int bandno; int rlvlno; jpc_dec_band_t *band; jpc_dec_rlvl_t *rlvl; int prcno; jpc_dec_prc_t *prc; jpc_dec_seg_t *seg; jpc_dec_cblk_t *cblk; int cblkno; if (tile->tcomps) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (band->prcs) { for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { if (!prc->cblks) { continue; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { while (cblk->segs.head) { seg = cblk->segs.head; jpc_seglist_remove(&cblk->segs, seg); jpc_seg_destroy(seg); } jas_matrix_destroy(cblk->data); if (cblk->mqdec) { jpc_mqdec_destroy(cblk->mqdec); } if (cblk->nulldec) { jpc_bitstream_close(cblk->nulldec); } if (cblk->flags) { jas_matrix_destroy(cblk->flags); } } if (prc->incltagtree) { jpc_tagtree_destroy(prc->incltagtree); } if (prc->numimsbstagtree) { jpc_tagtree_destroy(prc->numimsbstagtree); } if (prc->cblks) { jas_free(prc->cblks); } } } if (band->data) { jas_matrix_destroy(band->data); } if (band->prcs) { jas_free(band->prcs); } } if (rlvl->bands) { jas_free(rlvl->bands); } } if (tcomp->rlvls) { jas_free(tcomp->rlvls); } if (tcomp->data) { jas_matrix_destroy(tcomp->data); } if (tcomp->tsfb) { jpc_tsfb_destroy(tcomp->tsfb); } } } if (tile->cp) { jpc_dec_cp_destroy(tile->cp); tile->cp = 0; } if (tile->tcomps) { jas_free(tile->tcomps); tile->tcomps = 0; } if (tile->pi) { jpc_pi_destroy(tile->pi); tile->pi = 0; } if (tile->pkthdrstream) { jas_stream_close(tile->pkthdrstream); tile->pkthdrstream = 0; } if (tile->pptstab) { jpc_ppxstab_destroy(tile->pptstab); tile->pptstab = 0; } tile->state = JPC_TILE_DONE; return 0; } static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile) { int i; int j; jpc_dec_tcomp_t *tcomp; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; int compno; int rlvlno; int bandno; int adjust; int v; jpc_dec_ccp_t *ccp; jpc_dec_cmpt_t *cmpt; if (jpc_dec_decodecblks(dec, tile)) { jas_eprintf("jpc_dec_decodecblks failed\n"); return -1; } /* Perform dequantization. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl->bands) { continue; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band->data) { continue; } jpc_undo_roi(band->data, band->roishift, ccp->roishift - band->roishift, band->numbps); if (tile->realmode) { jas_matrix_asl(band->data, JPC_FIX_FRACBITS); jpc_dequantize(band->data, band->absstepsize); } } } } /* Apply an inverse wavelet transform if necessary. */ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { ccp = &tile->cp->ccps[compno]; jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data); } /* Apply an inverse intercomponent transform if necessary. */ switch (tile->cp->mctid) { case JPC_MCT_RCT: assert(dec->numcomps == 3); jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; case JPC_MCT_ICT: assert(dec->numcomps == 3); jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data, tile->tcomps[2].data); break; } /* Perform rounding and convert to integer values. */ if (tile->realmode) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { v = jas_matrix_get(tcomp->data, i, j); v = jpc_fix_round(v); jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v)); } } } } /* Perform level shift. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1)); for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) { for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) { *jas_matrix_getref(tcomp->data, i, j) += adjust; } } } /* Perform clipping. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { jpc_fix_t mn; jpc_fix_t mx; mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0); mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 << cmpt->prec) - 1); jas_matrix_clip(tcomp->data, mn, mx); } /* XXX need to free tsfb struct */ /* Write the data for each component of the image. */ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { if (jas_image_writecmpt(dec->image, compno, tcomp->xstart - JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart - JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols( tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) { jas_eprintf("write component failed\n"); return -4; } } return 0; } static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms) { int tileno; jpc_dec_tile_t *tile; /* Eliminate compiler warnings about unused variables. */ ms = 0; for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { if (tile->state == JPC_TILE_ACTIVE) { if (jpc_dec_tiledecode(dec, tile)) { return -1; } } jpc_dec_tilefini(dec, tile); } /* We are done processing the code stream. */ dec->state = JPC_MT; return 1; } static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_malloc(dec->numcomps * sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); dec->numtiles = dec->numhtiles * dec->numvtiles; if (!(dec->tiles = jas_malloc(dec->numtiles * sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; if (!(tile->tcomps = jas_malloc(dec->numcomps * sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; } static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_cod_t *cod = &ms->parms.cod; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcod(dec->cp, cod); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno != 0) { return -1; } jpc_dec_cp_setfromcod(tile->cp, cod); break; } return 0; } static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_coc_t *coc = &ms->parms.coc; jpc_dec_tile_t *tile; if (JAS_CAST(int, coc->compno) > dec->numcomps) { jas_eprintf("invalid component number in COC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromcoc(dec->cp, coc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromcoc(tile->cp, coc); break; } return 0; } static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_rgn_t *rgn = &ms->parms.rgn; jpc_dec_tile_t *tile; if (JAS_CAST(int, rgn->compno) > dec->numcomps) { jas_eprintf("invalid component number in RGN marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromrgn(dec->cp, rgn); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromrgn(tile->cp, rgn); break; } return 0; } static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcd_t *qcd = &ms->parms.qcd; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcd(dec->cp, qcd); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcd(tile->cp, qcd); break; } return 0; } static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_qcc_t *qcc = &ms->parms.qcc; jpc_dec_tile_t *tile; if (JAS_CAST(int, qcc->compno) > dec->numcomps) { jas_eprintf("invalid component number in QCC marker segment\n"); return -1; } switch (dec->state) { case JPC_MH: jpc_dec_cp_setfromqcc(dec->cp, qcc); break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (tile->partno > 0) { return -1; } jpc_dec_cp_setfromqcc(tile->cp, qcc); break; } return 0; } static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_poc_t *poc = &ms->parms.poc; jpc_dec_tile_t *tile; switch (dec->state) { case JPC_MH: if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) { return -1; } break; case JPC_TPH: if (!(tile = dec->curtile)) { return -1; } if (!tile->partno) { if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) { return -1; } } else { jpc_pi_addpchgfrompoc(tile->pi, poc); } break; } return 0; } static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppm_t *ppm = &ms->parms.ppm; jpc_ppxstabent_t *ppmstabent; if (!dec->ppmstab) { if (!(dec->ppmstab = jpc_ppxstab_create())) { return -1; } } if (!(ppmstabent = jpc_ppxstabent_create())) { return -1; } ppmstabent->ind = ppm->ind; ppmstabent->data = ppm->data; ppm->data = 0; ppmstabent->len = ppm->len; if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) { return -1; } return 0; } static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_ppt_t *ppt = &ms->parms.ppt; jpc_dec_tile_t *tile; jpc_ppxstabent_t *pptstabent; tile = dec->curtile; if (!tile->pptstab) { if (!(tile->pptstab = jpc_ppxstab_create())) { return -1; } } if (!(pptstabent = jpc_ppxstabent_create())) { return -1; } pptstabent->ind = ppt->ind; pptstabent->data = ppt->data; ppt->data = 0; pptstabent->len = ppt->len; if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) { return -1; } return 0; } static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; ms = 0; return 0; } static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms) { /* Eliminate compiler warnings about unused variables. */ dec = 0; jas_eprintf("warning: ignoring unknown marker segment\n"); jpc_ms_dump(ms, stderr); return 0; } /******************************************************************************\ * \******************************************************************************/ static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps) { jpc_dec_cp_t *cp; jpc_dec_ccp_t *ccp; int compno; if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) { return 0; } cp->flags = 0; cp->numcomps = numcomps; cp->prgord = 0; cp->numlyrs = 0; cp->mctid = 0; cp->csty = 0; if (!(cp->ccps = jas_malloc(cp->numcomps * sizeof(jpc_dec_ccp_t)))) { return 0; } if (!(cp->pchglist = jpc_pchglist_create())) { jas_free(cp->ccps); return 0; } for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; ccp->numrlvls = 0; ccp->cblkwidthexpn = 0; ccp->cblkheightexpn = 0; ccp->qmfbid = 0; ccp->numstepsizes = 0; ccp->numguardbits = 0; ccp->roishift = 0; ccp->cblkctx = 0; } return cp; } static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp) { jpc_dec_cp_t *newcp; jpc_dec_ccp_t *newccp; jpc_dec_ccp_t *ccp; int compno; if (!(newcp = jpc_dec_cp_create(cp->numcomps))) { return 0; } newcp->flags = cp->flags; newcp->prgord = cp->prgord; newcp->numlyrs = cp->numlyrs; newcp->mctid = cp->mctid; newcp->csty = cp->csty; jpc_pchglist_destroy(newcp->pchglist); newcp->pchglist = 0; if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) { jas_free(newcp); return 0; } for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++newccp, ++ccp) { *newccp = *ccp; } return newcp; } static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp) { int compno; jpc_dec_ccp_t *ccp; cp->flags &= (JPC_CSET | JPC_QSET); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; } } static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp) { if (cp->ccps) { jas_free(cp->ccps); } if (cp->pchglist) { jpc_pchglist_destroy(cp->pchglist); } jas_free(cp); } static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp) { uint_fast16_t compcnt; jpc_dec_ccp_t *ccp; if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) { return 0; } for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt, ++ccp) { /* Is there enough step sizes for the number of bands? */ if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 * ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT && ccp->numstepsizes != 1)) { return 0; } } return 1; } static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp) { jpc_dec_ccp_t *ccp; int compno; int i; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { if (!(ccp->csty & JPC_COX_PRT)) { for (i = 0; i < JPC_MAXRLVLS; ++i) { ccp->prcwidthexpns[i] = 15; ccp->prcheightexpns[i] = 15; } } if (ccp->qsty == JPC_QCX_SIQNT) { calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes); } } return 0; } static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod) { jpc_dec_ccp_t *ccp; int compno; cp->flags |= JPC_CSET; cp->prgord = cod->prg; if (cod->mctrans) { cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT); } else { cp->mctid = JPC_MCT_NONE; } cp->numlyrs = cod->numlyrs; cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH); for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0); } cp->flags |= JPC_CSET; return 0; } static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc) { jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC); return 0; } static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_coxcp_t *compparms, int flags) { int rlvlno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) { ccp->numrlvls = compparms->numdlvls + 1; ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkwidthval); ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN( compparms->cblkheightval); ccp->qmfbid = compparms->qmfbid; ccp->cblkctx = compparms->cblksty; ccp->csty = compparms->csty & JPC_COX_PRT; for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) { ccp->prcwidthexpns[rlvlno] = compparms->rlvls[rlvlno].parwidthval; ccp->prcheightexpns[rlvlno] = compparms->rlvls[rlvlno].parheightval; } ccp->flags |= flags | JPC_CSET; } return 0; } static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd) { int compno; jpc_dec_ccp_t *ccp; for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0); } cp->flags |= JPC_QSET; return 0; } static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc) { return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC); } static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp, jpc_qcxcp_t *compparms, int flags) { int bandno; /* Eliminate compiler warnings about unused variables. */ cp = 0; if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) { ccp->flags |= flags | JPC_QSET; for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) { ccp->stepsizes[bandno] = compparms->stepsizes[bandno]; } ccp->numstepsizes = compparms->numstepsizes; ccp->numguardbits = compparms->numguard; ccp->qsty = compparms->qntsty; } return 0; } static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn) { jpc_dec_ccp_t *ccp; ccp = &cp->ccps[rgn->compno]; ccp->roishift = rgn->roishift; return 0; } static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc) { int pchgno; jpc_pchg_t *pchg; for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) { return -1; } } return 0; } static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset) { int pchgno; jpc_pchg_t *pchg; if (reset) { while (jpc_pchglist_numpchgs(cp->pchglist) > 0) { pchg = jpc_pchglist_remove(cp->pchglist, 0); jpc_pchg_destroy(pchg); } } for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) { if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) { return -1; } if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) { return -1; } } return 0; } static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits) { jpc_fix_t absstepsize; int n; absstepsize = jpc_inttofix(1); n = JPC_FIX_FRACBITS - 11; absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) : (JPC_QCX_GETMANT(stepsize) >> (-n)); n = numbits - JPC_QCX_GETEXPN(stepsize); absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n)); return absstepsize; } static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize) { int i; int j; int t; assert(absstepsize >= 0); if (absstepsize == jpc_inttofix(1)) { return; } for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { t = jas_matrix_get(x, i, j); if (t) { t = jpc_fix_mul(t, absstepsize); } else { t = 0; } jas_matrix_set(x, i, j, t); } } } static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) { int i; int j; int thresh; jpc_fix_t val; jpc_fix_t mag; bool warn; uint_fast32_t mask; if (roishift == 0 && bgshift == 0) { return; } thresh = 1 << roishift; warn = false; for (i = 0; i < jas_matrix_numrows(x); ++i) { for (j = 0; j < jas_matrix_numcols(x); ++j) { val = jas_matrix_get(x, i, j); mag = JAS_ABS(val); if (mag >= thresh) { /* We are dealing with ROI data. */ mag >>= roishift; val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } else { /* We are dealing with non-ROI (i.e., background) data. */ mag <<= bgshift; mask = (1 << numbps) - 1; /* Perform a basic sanity check on the sample value. */ /* Some implementations write garbage in the unused most-significant bit planes introduced by ROI shifting. Here we ensure that any such bits are masked off. */ if (mag & (~mask)) { if (!warn) { jas_eprintf("warning: possibly corrupt code stream\n"); warn = true; } mag &= mask; } val = (val < 0) ? (-mag) : mag; jas_matrix_set(x, i, j, val); } } } } static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in) { jpc_dec_t *dec; if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) { return 0; } dec->image = 0; dec->xstart = 0; dec->ystart = 0; dec->xend = 0; dec->yend = 0; dec->tilewidth = 0; dec->tileheight = 0; dec->tilexoff = 0; dec->tileyoff = 0; dec->numhtiles = 0; dec->numvtiles = 0; dec->numtiles = 0; dec->tiles = 0; dec->curtile = 0; dec->numcomps = 0; dec->in = in; dec->cp = 0; dec->maxlyrs = impopts->maxlyrs; dec->maxpkts = impopts->maxpkts; dec->numpkts = 0; dec->ppmseqno = 0; dec->state = 0; dec->cmpts = 0; dec->pkthdrstreams = 0; dec->ppmstab = 0; dec->curtileendoff = 0; return dec; } static void jpc_dec_destroy(jpc_dec_t *dec) { if (dec->cstate) { jpc_cstate_destroy(dec->cstate); } if (dec->pkthdrstreams) { jpc_streamlist_destroy(dec->pkthdrstreams); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cp) { jpc_dec_cp_destroy(dec->cp); } if (dec->cmpts) { jas_free(dec->cmpts); } if (dec->tiles) { jas_free(dec->tiles); } jas_free(dec); } /******************************************************************************\ * \******************************************************************************/ void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = ins; node->prev = prev; next = prev ? (prev->next) : 0; node->prev = prev; node->next = next; if (prev) { prev->next = node; } else { list->head = node; } if (next) { next->prev = node; } else { list->tail = node; } } void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg) { jpc_dec_seg_t *prev; jpc_dec_seg_t *next; prev = seg->prev; next = seg->next; if (prev) { prev->next = next; } else { list->head = next; } if (next) { next->prev = prev; } else { list->tail = prev; } seg->prev = 0; seg->next = 0; } jpc_dec_seg_t *jpc_seg_alloc() { jpc_dec_seg_t *seg; if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) { return 0; } seg->prev = 0; seg->next = 0; seg->passno = -1; seg->numpasses = 0; seg->maxpasses = 0; seg->type = JPC_SEG_INVALID; seg->stream = 0; seg->cnt = 0; seg->complete = 0; seg->lyrno = -1; return seg; } void jpc_seg_destroy(jpc_dec_seg_t *seg) { if (seg->stream) { jas_stream_close(seg->stream); } jas_free(seg); } static int jpc_dec_dump(jpc_dec_t *dec, FILE *out) { jpc_dec_tile_t *tile; int tileno; jpc_dec_tcomp_t *tcomp; int compno; jpc_dec_rlvl_t *rlvl; int rlvlno; jpc_dec_band_t *band; int bandno; jpc_dec_prc_t *prc; int prcno; jpc_dec_cblk_t *cblk; int cblkno; for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++tcomp) { for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend, rlvl->xend - rlvl->xstart, rlvl->yend - rlvl->ystart); for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { fprintf(out, "BAND %d\n", bandno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data), jas_seq2d_xend(band->data) - jas_seq2d_xstart(band->data), jas_seq2d_yend(band->data) - jas_seq2d_ystart(band->data)); for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno, ++prc) { fprintf(out, "CODE BLOCK GROUP %d\n", prcno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", prc->xstart, prc->ystart, prc->xend, prc->yend, prc->xend - prc->xstart, prc->yend - prc->ystart); for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { fprintf(out, "CODE BLOCK %d\n", cblkno); fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data), jas_seq2d_xend(cblk->data) - jas_seq2d_xstart(cblk->data), jas_seq2d_yend(cblk->data) - jas_seq2d_ystart(cblk->data)); } } } } } } return 0; } jpc_streamlist_t *jpc_streamlist_create() { jpc_streamlist_t *streamlist; int i; if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) { return 0; } streamlist->numstreams = 0; streamlist->maxstreams = 100; if (!(streamlist->streams = jas_malloc(streamlist->maxstreams * sizeof(jas_stream_t *)))) { jas_free(streamlist); return 0; } for (i = 0; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } return streamlist; } int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno, jas_stream_t *stream) { jas_stream_t **newstreams; int newmaxstreams; int i; /* Grow the array of streams if necessary. */ if (streamlist->numstreams >= streamlist->maxstreams) { newmaxstreams = streamlist->maxstreams + 1024; if (!(newstreams = jas_realloc(streamlist->streams, (newmaxstreams + 1024) * sizeof(jas_stream_t *)))) { return -1; } for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } streamlist->maxstreams = newmaxstreams; streamlist->streams = newstreams; } if (streamno != streamlist->numstreams) { /* Can only handle insertion at start of list. */ return -1; } streamlist->streams[streamno] = stream; ++streamlist->numstreams; return 0; } jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno) { jas_stream_t *stream; int i; if (streamno >= streamlist->numstreams) { abort(); } stream = streamlist->streams[streamno]; for (i = streamno + 1; i < streamlist->numstreams; ++i) { streamlist->streams[i - 1] = streamlist->streams[i]; } --streamlist->numstreams; return stream; } void jpc_streamlist_destroy(jpc_streamlist_t *streamlist) { int streamno; if (streamlist->streams) { for (streamno = 0; streamno < streamlist->numstreams; ++streamno) { jas_stream_close(streamlist->streams[streamno]); } jas_free(streamlist->streams); } jas_free(streamlist); } jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno) { assert(streamno < streamlist->numstreams); return streamlist->streams[streamno]; } int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist) { return streamlist->numstreams; } jpc_ppxstab_t *jpc_ppxstab_create() { jpc_ppxstab_t *tab; if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) { return 0; } tab->numents = 0; tab->maxents = 0; tab->ents = 0; return tab; } void jpc_ppxstab_destroy(jpc_ppxstab_t *tab) { int i; for (i = 0; i < tab->numents; ++i) { jpc_ppxstabent_destroy(tab->ents[i]); } if (tab->ents) { jas_free(tab->ents); } jas_free(tab); } int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents) { jpc_ppxstabent_t **newents; if (tab->maxents < maxents) { newents = (tab->ents) ? jas_realloc(tab->ents, maxents * sizeof(jpc_ppxstabent_t *)) : jas_malloc(maxents * sizeof(jpc_ppxstabent_t *)); if (!newents) { return -1; } tab->ents = newents; tab->maxents = maxents; } return 0; } int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent) { int inspt; int i; for (i = 0; i < tab->numents; ++i) { if (tab->ents[i]->ind > ent->ind) { break; } } inspt = i; if (tab->numents >= tab->maxents) { if (jpc_ppxstab_grow(tab, tab->maxents + 128)) { return -1; } } for (i = tab->numents; i > inspt; --i) { tab->ents[i] = tab->ents[i - 1]; } tab->ents[i] = ent; ++tab->numents; return 0; } jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) { jpc_streamlist_t *streams; uchar *dataptr; uint_fast32_t datacnt; uint_fast32_t tpcnt; jpc_ppxstabent_t *ent; int entno; jas_stream_t *stream; int n; if (!(streams = jpc_streamlist_create())) { goto error; } if (!tab->numents) { return streams; } entno = 0; ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; for (;;) { /* Get the length of the packet header data for the current tile-part. */ if (datacnt < 4) { goto error; } if (!(stream = jas_stream_memopen(0, 0))) { goto error; } if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), stream)) { goto error; } tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) | dataptr[3]; datacnt -= 4; dataptr += 4; /* Get the packet header data for the current tile-part. */ while (tpcnt) { if (!datacnt) { if (++entno >= tab->numents) { goto error; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } n = JAS_MIN(tpcnt, datacnt); if (jas_stream_write(stream, dataptr, n) != n) { goto error; } tpcnt -= n; dataptr += n; datacnt -= n; } jas_stream_rewind(stream); if (!datacnt) { if (++entno >= tab->numents) { break; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } } return streams; error: jpc_streamlist_destroy(streams); return 0; } int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab) { int i; jpc_ppxstabent_t *ent; for (i = 0; i < tab->numents; ++i) { ent = tab->ents[i]; if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) { return -1; } } return 0; } jpc_ppxstabent_t *jpc_ppxstabent_create() { jpc_ppxstabent_t *ent; if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) { return 0; } ent->data = 0; ent->len = 0; ent->ind = 0; return ent; } void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent) { if (ent->data) { jas_free(ent->data); } jas_free(ent); }
mit
huangbop/skywalker
rt-thread-2.0.0/components/external/freetype/src/autofit/afloader.c
159
19191
/***************************************************************************/ /* */ /* afloader.c */ /* */ /* Auto-fitter glyph loading routines (body). */ /* */ /* Copyright 2003-2009, 2011-2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include "afglobal.h" #include "afloader.h" #include "afhints.h" #include "aferrors.h" #include "afmodule.h" #include "afpic.h" /* Initialize glyph loader. */ FT_LOCAL_DEF( FT_Error ) af_loader_init( AF_Module module ) { AF_Loader loader = module->loader; FT_Memory memory = module->root.library->memory; FT_ZERO( loader ); af_glyph_hints_init( &loader->hints, memory ); #ifdef FT_DEBUG_AUTOFIT _af_debug_hints = &loader->hints; #endif return FT_GlyphLoader_New( memory, &loader->gloader ); } /* Reset glyph loader and compute globals if necessary. */ FT_LOCAL_DEF( FT_Error ) af_loader_reset( AF_Module module, FT_Face face ) { FT_Error error = FT_Err_Ok; AF_Loader loader = module->loader; loader->face = face; loader->globals = (AF_FaceGlobals)face->autohint.data; FT_GlyphLoader_Rewind( loader->gloader ); if ( loader->globals == NULL ) { error = af_face_globals_new( face, &loader->globals, module ); if ( !error ) { face->autohint.data = (FT_Pointer)loader->globals; face->autohint.finalizer = (FT_Generic_Finalizer)af_face_globals_free; } } return error; } /* Finalize glyph loader. */ FT_LOCAL_DEF( void ) af_loader_done( AF_Module module ) { AF_Loader loader = module->loader; af_glyph_hints_done( &loader->hints ); loader->face = NULL; loader->globals = NULL; #ifdef FT_DEBUG_AUTOFIT _af_debug_hints = NULL; #endif FT_GlyphLoader_Done( loader->gloader ); loader->gloader = NULL; } /* Load a single glyph component. This routine calls itself */ /* recursively, if necessary, and does the main work of */ /* `af_loader_load_glyph.' */ static FT_Error af_loader_load_g( AF_Loader loader, AF_Scaler scaler, FT_UInt glyph_index, FT_Int32 load_flags, FT_UInt depth ) { FT_Error error; FT_Face face = loader->face; FT_GlyphLoader gloader = loader->gloader; AF_StyleMetrics metrics = loader->metrics; AF_GlyphHints hints = &loader->hints; FT_GlyphSlot slot = face->glyph; FT_Slot_Internal internal = slot->internal; FT_Int32 flags; flags = load_flags | FT_LOAD_LINEAR_DESIGN; error = FT_Load_Glyph( face, glyph_index, flags ); if ( error ) goto Exit; loader->transformed = internal->glyph_transformed; if ( loader->transformed ) { FT_Matrix inverse; loader->trans_matrix = internal->glyph_matrix; loader->trans_delta = internal->glyph_delta; inverse = loader->trans_matrix; if ( !FT_Matrix_Invert( &inverse ) ) FT_Vector_Transform( &loader->trans_delta, &inverse ); } switch ( slot->format ) { case FT_GLYPH_FORMAT_OUTLINE: /* translate the loaded glyph when an internal transform is needed */ if ( loader->transformed ) FT_Outline_Translate( &slot->outline, loader->trans_delta.x, loader->trans_delta.y ); /* copy the outline points in the loader's current */ /* extra points which are used to keep original glyph coordinates */ error = FT_GLYPHLOADER_CHECK_POINTS( gloader, slot->outline.n_points + 4, slot->outline.n_contours ); if ( error ) goto Exit; FT_ARRAY_COPY( gloader->current.outline.points, slot->outline.points, slot->outline.n_points ); FT_ARRAY_COPY( gloader->current.outline.contours, slot->outline.contours, slot->outline.n_contours ); FT_ARRAY_COPY( gloader->current.outline.tags, slot->outline.tags, slot->outline.n_points ); gloader->current.outline.n_points = slot->outline.n_points; gloader->current.outline.n_contours = slot->outline.n_contours; /* compute original horizontal phantom points (and ignore */ /* vertical ones) */ loader->pp1.x = hints->x_delta; loader->pp1.y = hints->y_delta; loader->pp2.x = FT_MulFix( slot->metrics.horiAdvance, hints->x_scale ) + hints->x_delta; loader->pp2.y = hints->y_delta; /* be sure to check for spacing glyphs */ if ( slot->outline.n_points == 0 ) goto Hint_Metrics; /* now load the slot image into the auto-outline and run the */ /* automatic hinting process */ { #ifdef FT_CONFIG_OPTION_PIC AF_FaceGlobals globals = loader->globals; #endif AF_StyleClass style_class = metrics->style_class; AF_WritingSystemClass writing_system_class = AF_WRITING_SYSTEM_CLASSES_GET[style_class->writing_system]; if ( writing_system_class->style_hints_apply ) writing_system_class->style_hints_apply( hints, &gloader->current.outline, metrics ); } /* we now need to adjust the metrics according to the change in */ /* width/positioning that occurred during the hinting process */ if ( scaler->render_mode != FT_RENDER_MODE_LIGHT ) { FT_Pos old_rsb, old_lsb, new_lsb; FT_Pos pp1x_uh, pp2x_uh; AF_AxisHints axis = &hints->axis[AF_DIMENSION_HORZ]; AF_Edge edge1 = axis->edges; /* leftmost edge */ AF_Edge edge2 = edge1 + axis->num_edges - 1; /* rightmost edge */ if ( axis->num_edges > 1 && AF_HINTS_DO_ADVANCE( hints ) ) { old_rsb = loader->pp2.x - edge2->opos; old_lsb = edge1->opos; new_lsb = edge1->pos; /* remember unhinted values to later account */ /* for rounding errors */ pp1x_uh = new_lsb - old_lsb; pp2x_uh = edge2->pos + old_rsb; /* prefer too much space over too little space */ /* for very small sizes */ if ( old_lsb < 24 ) pp1x_uh -= 8; if ( old_rsb < 24 ) pp2x_uh += 8; loader->pp1.x = FT_PIX_ROUND( pp1x_uh ); loader->pp2.x = FT_PIX_ROUND( pp2x_uh ); if ( loader->pp1.x >= new_lsb && old_lsb > 0 ) loader->pp1.x -= 64; if ( loader->pp2.x <= edge2->pos && old_rsb > 0 ) loader->pp2.x += 64; slot->lsb_delta = loader->pp1.x - pp1x_uh; slot->rsb_delta = loader->pp2.x - pp2x_uh; } else { FT_Pos pp1x = loader->pp1.x; FT_Pos pp2x = loader->pp2.x; loader->pp1.x = FT_PIX_ROUND( pp1x ); loader->pp2.x = FT_PIX_ROUND( pp2x ); slot->lsb_delta = loader->pp1.x - pp1x; slot->rsb_delta = loader->pp2.x - pp2x; } } else { FT_Pos pp1x = loader->pp1.x; FT_Pos pp2x = loader->pp2.x; loader->pp1.x = FT_PIX_ROUND( pp1x + hints->xmin_delta ); loader->pp2.x = FT_PIX_ROUND( pp2x + hints->xmax_delta ); slot->lsb_delta = loader->pp1.x - pp1x; slot->rsb_delta = loader->pp2.x - pp2x; } /* good, we simply add the glyph to our loader's base */ FT_GlyphLoader_Add( gloader ); break; case FT_GLYPH_FORMAT_COMPOSITE: { FT_UInt nn, num_subglyphs = slot->num_subglyphs; FT_UInt num_base_subgs, start_point; FT_SubGlyph subglyph; start_point = gloader->base.outline.n_points; /* first of all, copy the subglyph descriptors in the glyph loader */ error = FT_GlyphLoader_CheckSubGlyphs( gloader, num_subglyphs ); if ( error ) goto Exit; FT_ARRAY_COPY( gloader->current.subglyphs, slot->subglyphs, num_subglyphs ); gloader->current.num_subglyphs = num_subglyphs; num_base_subgs = gloader->base.num_subglyphs; /* now read each subglyph independently */ for ( nn = 0; nn < num_subglyphs; nn++ ) { FT_Vector pp1, pp2; FT_Pos x, y; FT_UInt num_points, num_new_points, num_base_points; /* gloader.current.subglyphs can change during glyph loading due */ /* to re-allocation -- we must recompute the current subglyph on */ /* each iteration */ subglyph = gloader->base.subglyphs + num_base_subgs + nn; pp1 = loader->pp1; pp2 = loader->pp2; num_base_points = gloader->base.outline.n_points; error = af_loader_load_g( loader, scaler, subglyph->index, load_flags, depth + 1 ); if ( error ) goto Exit; /* recompute subglyph pointer */ subglyph = gloader->base.subglyphs + num_base_subgs + nn; if ( !( subglyph->flags & FT_SUBGLYPH_FLAG_USE_MY_METRICS ) ) { loader->pp1 = pp1; loader->pp2 = pp2; } num_points = gloader->base.outline.n_points; num_new_points = num_points - num_base_points; /* now perform the transformation required for this subglyph */ if ( subglyph->flags & ( FT_SUBGLYPH_FLAG_SCALE | FT_SUBGLYPH_FLAG_XY_SCALE | FT_SUBGLYPH_FLAG_2X2 ) ) { FT_Vector* cur = gloader->base.outline.points + num_base_points; FT_Vector* limit = cur + num_new_points; for ( ; cur < limit; cur++ ) FT_Vector_Transform( cur, &subglyph->transform ); } /* apply offset */ if ( !( subglyph->flags & FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES ) ) { FT_Int k = subglyph->arg1; FT_UInt l = subglyph->arg2; FT_Vector* p1; FT_Vector* p2; if ( start_point + k >= num_base_points || l >= (FT_UInt)num_new_points ) { error = FT_THROW( Invalid_Composite ); goto Exit; } l += num_base_points; /* for now, only use the current point coordinates; */ /* we eventually may consider another approach */ p1 = gloader->base.outline.points + start_point + k; p2 = gloader->base.outline.points + start_point + l; x = p1->x - p2->x; y = p1->y - p2->y; } else { x = FT_MulFix( subglyph->arg1, hints->x_scale ) + hints->x_delta; y = FT_MulFix( subglyph->arg2, hints->y_scale ) + hints->y_delta; x = FT_PIX_ROUND( x ); y = FT_PIX_ROUND( y ); } { FT_Outline dummy = gloader->base.outline; dummy.points += num_base_points; dummy.n_points = (short)num_new_points; FT_Outline_Translate( &dummy, x, y ); } } } break; default: /* we don't support other formats (yet?) */ error = FT_THROW( Unimplemented_Feature ); } Hint_Metrics: if ( depth == 0 ) { FT_BBox bbox; FT_Vector vvector; vvector.x = slot->metrics.vertBearingX - slot->metrics.horiBearingX; vvector.y = slot->metrics.vertBearingY - slot->metrics.horiBearingY; vvector.x = FT_MulFix( vvector.x, metrics->scaler.x_scale ); vvector.y = FT_MulFix( vvector.y, metrics->scaler.y_scale ); /* transform the hinted outline if needed */ if ( loader->transformed ) { FT_Outline_Transform( &gloader->base.outline, &loader->trans_matrix ); FT_Vector_Transform( &vvector, &loader->trans_matrix ); } #if 1 /* we must translate our final outline by -pp1.x and compute */ /* the new metrics */ if ( loader->pp1.x ) FT_Outline_Translate( &gloader->base.outline, -loader->pp1.x, 0 ); #endif FT_Outline_Get_CBox( &gloader->base.outline, &bbox ); bbox.xMin = FT_PIX_FLOOR( bbox.xMin ); bbox.yMin = FT_PIX_FLOOR( bbox.yMin ); bbox.xMax = FT_PIX_CEIL( bbox.xMax ); bbox.yMax = FT_PIX_CEIL( bbox.yMax ); slot->metrics.width = bbox.xMax - bbox.xMin; slot->metrics.height = bbox.yMax - bbox.yMin; slot->metrics.horiBearingX = bbox.xMin; slot->metrics.horiBearingY = bbox.yMax; slot->metrics.vertBearingX = FT_PIX_FLOOR( bbox.xMin + vvector.x ); slot->metrics.vertBearingY = FT_PIX_FLOOR( bbox.yMax + vvector.y ); /* for mono-width fonts (like Andale, Courier, etc.) we need */ /* to keep the original rounded advance width; ditto for */ /* digits if all have the same advance width */ #if 0 if ( !FT_IS_FIXED_WIDTH( slot->face ) ) slot->metrics.horiAdvance = loader->pp2.x - loader->pp1.x; else slot->metrics.horiAdvance = FT_MulFix( slot->metrics.horiAdvance, x_scale ); #else if ( scaler->render_mode != FT_RENDER_MODE_LIGHT && ( FT_IS_FIXED_WIDTH( slot->face ) || ( af_face_globals_is_digit( loader->globals, glyph_index ) && metrics->digits_have_same_width ) ) ) { slot->metrics.horiAdvance = FT_MulFix( slot->metrics.horiAdvance, metrics->scaler.x_scale ); /* Set delta values to 0. Otherwise code that uses them is */ /* going to ruin the fixed advance width. */ slot->lsb_delta = 0; slot->rsb_delta = 0; } else { /* non-spacing glyphs must stay as-is */ if ( slot->metrics.horiAdvance ) slot->metrics.horiAdvance = loader->pp2.x - loader->pp1.x; } #endif slot->metrics.vertAdvance = FT_MulFix( slot->metrics.vertAdvance, metrics->scaler.y_scale ); slot->metrics.horiAdvance = FT_PIX_ROUND( slot->metrics.horiAdvance ); slot->metrics.vertAdvance = FT_PIX_ROUND( slot->metrics.vertAdvance ); /* now copy outline into glyph slot */ FT_GlyphLoader_Rewind( internal->loader ); error = FT_GlyphLoader_CopyPoints( internal->loader, gloader ); if ( error ) goto Exit; /* reassign all outline fields except flags to protect them */ slot->outline.n_contours = internal->loader->base.outline.n_contours; slot->outline.n_points = internal->loader->base.outline.n_points; slot->outline.points = internal->loader->base.outline.points; slot->outline.tags = internal->loader->base.outline.tags; slot->outline.contours = internal->loader->base.outline.contours; slot->format = FT_GLYPH_FORMAT_OUTLINE; } Exit: return error; } /* Load a glyph. */ FT_LOCAL_DEF( FT_Error ) af_loader_load_glyph( AF_Module module, FT_Face face, FT_UInt gindex, FT_Int32 load_flags ) { FT_Error error; FT_Size size = face->size; AF_Loader loader = module->loader; AF_ScalerRec scaler; if ( !size ) return FT_THROW( Invalid_Size_Handle ); FT_ZERO( &scaler ); scaler.face = face; scaler.x_scale = size->metrics.x_scale; scaler.x_delta = 0; /* XXX: TODO: add support for sub-pixel hinting */ scaler.y_scale = size->metrics.y_scale; scaler.y_delta = 0; /* XXX: TODO: add support for sub-pixel hinting */ scaler.render_mode = FT_LOAD_TARGET_MODE( load_flags ); scaler.flags = 0; /* XXX: fix this */ error = af_loader_reset( module, face ); if ( !error ) { AF_StyleMetrics metrics; FT_UInt options = AF_STYLE_NONE_DFLT; #ifdef FT_OPTION_AUTOFIT2 /* XXX: undocumented hook to activate the latin2 writing system */ if ( load_flags & ( 1UL << 20 ) ) options = AF_STYLE_LTN2_DFLT; #endif error = af_face_globals_get_metrics( loader->globals, gindex, options, &metrics ); if ( !error ) { #ifdef FT_CONFIG_OPTION_PIC AF_FaceGlobals globals = loader->globals; #endif AF_StyleClass style_class = metrics->style_class; AF_WritingSystemClass writing_system_class = AF_WRITING_SYSTEM_CLASSES_GET[style_class->writing_system]; loader->metrics = metrics; if ( writing_system_class->style_metrics_scale ) writing_system_class->style_metrics_scale( metrics, &scaler ); else metrics->scaler = scaler; load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_IGNORE_TRANSFORM; load_flags &= ~FT_LOAD_RENDER; if ( writing_system_class->style_hints_init ) { error = writing_system_class->style_hints_init( &loader->hints, metrics ); if ( error ) goto Exit; } error = af_loader_load_g( loader, &scaler, gindex, load_flags, 0 ); } } Exit: return error; } /* END */
mit
xdkoooo/WinObjC
deps/3rdparty/iculegacy/source/i18n/name2uni.cpp
165
8172
/* ********************************************************************** * Copyright (C) 2001-2011, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Date Name Description * 06/07/01 aliu Creation. ********************************************************************** */ #include "unicode/utypes.h" #if !UCONFIG_NO_TRANSLITERATION #include "unicode/unifilt.h" #include "unicode/uchar.h" #include "unicode/uniset.h" #include "cmemory.h" #include "name2uni.h" #include "patternprops.h" #include "uprops.h" #include "uinvchar.h" #include "util.h" U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(NameUnicodeTransliterator) static const UChar OPEN[] = {92,78,126,123,126,0}; // "\N~{~" static const UChar OPEN_DELIM = 92; // '\\' first char of OPEN static const UChar CLOSE_DELIM = 125; // '}' static const UChar SPACE = 32; // ' ' U_CDECL_BEGIN // USetAdder implementation // Does not use uset.h to reduce code dependencies static void U_CALLCONV _set_add(USet *set, UChar32 c) { uset_add(set, c); } // These functions aren't used. /*static void U_CALLCONV _set_addRange(USet *set, UChar32 start, UChar32 end) { ((UnicodeSet *)set)->add(start, end); } static void U_CALLCONV _set_addString(USet *set, const UChar *str, int32_t length) { ((UnicodeSet *)set)->add(UnicodeString((UBool)(length<0), str, length)); }*/ U_CDECL_END /** * Constructs a transliterator with the default delimiters '{' and * '}'. */ NameUnicodeTransliterator::NameUnicodeTransliterator(UnicodeFilter* adoptedFilter) : Transliterator(UNICODE_STRING("Name-Any", 8), adoptedFilter) { UnicodeSet *legalPtr = &legal; // Get the legal character set USetAdder sa = { (USet *)legalPtr, // USet* == UnicodeSet* _set_add, NULL, // Don't need _set_addRange NULL, // Don't need _set_addString NULL, // Don't need remove() NULL }; uprv_getCharNameCharacters(&sa); } /** * Destructor. */ NameUnicodeTransliterator::~NameUnicodeTransliterator() {} /** * Copy constructor. */ NameUnicodeTransliterator::NameUnicodeTransliterator(const NameUnicodeTransliterator& o) : Transliterator(o), legal(o.legal) {} /** * Assignment operator. */ /*NameUnicodeTransliterator& NameUnicodeTransliterator::operator=( const NameUnicodeTransliterator& o) { Transliterator::operator=(o); // not necessary: the legal sets should all be the same -- legal=o.legal; return *this; }*/ /** * Transliterator API. */ Transliterator* NameUnicodeTransliterator::clone(void) const { return new NameUnicodeTransliterator(*this); } /** * Implements {@link Transliterator#handleTransliterate}. */ void NameUnicodeTransliterator::handleTransliterate(Replaceable& text, UTransPosition& offsets, UBool isIncremental) const { // The failure mode, here and below, is to behave like Any-Null, // if either there is no name data (max len == 0) or there is no // memory (malloc() => NULL). int32_t maxLen = uprv_getMaxCharNameLength(); if (maxLen == 0) { offsets.start = offsets.limit; return; } // Accomodate the longest possible name ++maxLen; // allow for temporary trailing space char* cbuf = (char*) uprv_malloc(maxLen); if (cbuf == NULL) { offsets.start = offsets.limit; return; } UnicodeString openPat(TRUE, OPEN, -1); UnicodeString str, name; int32_t cursor = offsets.start; int32_t limit = offsets.limit; // Modes: // 0 - looking for open delimiter // 1 - after open delimiter int32_t mode = 0; int32_t openPos = -1; // open delim candidate pos UChar32 c; while (cursor < limit) { c = text.char32At(cursor); switch (mode) { case 0: // looking for open delimiter if (c == OPEN_DELIM) { // quick check first openPos = cursor; int32_t i = ICU_Utility::parsePattern(openPat, text, cursor, limit); if (i >= 0 && i < limit) { mode = 1; name.truncate(0); cursor = i; continue; // *** reprocess char32At(cursor) } } break; case 1: // after open delimiter // Look for legal chars. If \s+ is found, convert it // to a single space. If closeDelimiter is found, exit // the loop. If any other character is found, exit the // loop. If the limit is reached, exit the loop. // Convert \s+ => SPACE. This assumes there are no // runs of >1 space characters in names. if (PatternProps::isWhiteSpace(c)) { // Ignore leading whitespace if (name.length() > 0 && name.charAt(name.length()-1) != SPACE) { name.append(SPACE); // If we are too long then abort. maxLen includes // temporary trailing space, so use '>'. if (name.length() > maxLen) { mode = 0; } } break; } if (c == CLOSE_DELIM) { int32_t len = name.length(); // Delete trailing space, if any if (len > 0 && name.charAt(len-1) == SPACE) { --len; } if (uprv_isInvariantUString(name.getBuffer(), len)) { name.extract(0, len, cbuf, maxLen, US_INV); UErrorCode status = U_ZERO_ERROR; c = u_charFromName(U_EXTENDED_CHAR_NAME, cbuf, &status); if (U_SUCCESS(status)) { // Lookup succeeded // assert(UTF_CHAR_LENGTH(CLOSE_DELIM) == 1); cursor++; // advance over CLOSE_DELIM str.truncate(0); str.append(c); text.handleReplaceBetween(openPos, cursor, str); // Adjust indices for the change in the length of // the string. Do not assume that str.length() == // 1, in case of surrogates. int32_t delta = cursor - openPos - str.length(); cursor -= delta; limit -= delta; // assert(cursor == openPos + str.length()); } } // If the lookup failed, we leave things as-is and // still switch to mode 0 and continue. mode = 0; openPos = -1; // close off candidate continue; // *** reprocess char32At(cursor) } // Check if c is a legal char. We assume here that // legal.contains(OPEN_DELIM) is FALSE, so when we abort a // name, we don't have to go back to openPos+1. if (legal.contains(c)) { name.append(c); // If we go past the longest possible name then abort. // maxLen includes temporary trailing space, so use '>='. if (name.length() >= maxLen) { mode = 0; } } // Invalid character else { --cursor; // Backup and reprocess this character mode = 0; } break; } cursor += UTF_CHAR_LENGTH(c); } offsets.contextLimit += limit - offsets.limit; offsets.limit = limit; // In incremental mode, only advance the cursor up to the last // open delimiter candidate. offsets.start = (isIncremental && openPos >= 0) ? openPos : cursor; uprv_free(cbuf); } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_TRANSLITERATION */
mit
laura-96/GameEngine
GameEngine/Bullet/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp
439
3373
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btSoftRigidCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletCollision/CollisionShapes/btBoxShape.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "btSoftBody.h" #include "BulletSoftBody/btSoftBodySolvers.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" ///TODO: include all the shapes that the softbody can collide with ///alternatively, implement special case collision algorithms (just like for rigid collision shapes) //#include <stdio.h> btSoftRigidCollisionAlgorithm::btSoftRigidCollisionAlgorithm(btPersistentManifold* /*mf*/,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* ,const btCollisionObjectWrapper* , bool isSwapped) : btCollisionAlgorithm(ci), //m_ownManifold(false), //m_manifoldPtr(mf), m_isSwapped(isSwapped) { } btSoftRigidCollisionAlgorithm::~btSoftRigidCollisionAlgorithm() { //m_softBody->m_overlappingRigidBodies.remove(m_rigidCollisionObject); /*if (m_ownManifold) { if (m_manifoldPtr) m_dispatcher->releaseManifold(m_manifoldPtr); } */ } #include <stdio.h> void btSoftRigidCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { (void)dispatchInfo; (void)resultOut; //printf("btSoftRigidCollisionAlgorithm\n"); // const btCollisionObjectWrapper* softWrap = m_isSwapped?body1Wrap:body0Wrap; // const btCollisionObjectWrapper* rigidWrap = m_isSwapped?body0Wrap:body1Wrap; btSoftBody* softBody = m_isSwapped? (btSoftBody*)body1Wrap->getCollisionObject() : (btSoftBody*)body0Wrap->getCollisionObject(); const btCollisionObjectWrapper* rigidCollisionObjectWrap = m_isSwapped? body0Wrap : body1Wrap; if (softBody->m_collisionDisabledObjects.findLinearSearch(rigidCollisionObjectWrap->getCollisionObject())==softBody->m_collisionDisabledObjects.size()) { softBody->getSoftBodySolver()->processCollision(softBody, rigidCollisionObjectWrap); } } btScalar btSoftRigidCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { (void)resultOut; (void)dispatchInfo; (void)col0; (void)col1; //not yet return btScalar(1.); }
mit
aspectron/jsx
extern/v8/third_party/icu/source/common/ucnv_cb.c
440
8083
/* ********************************************************************** * Copyright (C) 2000-2006, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * ucnv_cb.c: * External APIs for the ICU's codeset conversion library * Helena Shih * * Modification History: * * Date Name Description * 7/28/2000 srl Implementation */ /** * @name Character Conversion C API * */ #include "unicode/utypes.h" #if !UCONFIG_NO_CONVERSION #include "unicode/ucnv_cb.h" #include "ucnv_bld.h" #include "ucnv_cnv.h" #include "cmemory.h" /* need to update the offsets when the target moves. */ /* Note: Recursion may occur in the cb functions, be sure to update the offsets correctly if you don't use ucnv_cbXXX functions. Make sure you don't use the same callback within the same call stack if the complexity arises. */ U_CAPI void U_EXPORT2 ucnv_cbFromUWriteBytes (UConverterFromUnicodeArgs *args, const char* source, int32_t length, int32_t offsetIndex, UErrorCode * err) { if(U_FAILURE(*err)) { return; } ucnv_fromUWriteBytes( args->converter, source, length, &args->target, args->targetLimit, &args->offsets, offsetIndex, err); } U_CAPI void U_EXPORT2 ucnv_cbFromUWriteUChars(UConverterFromUnicodeArgs *args, const UChar** source, const UChar* sourceLimit, int32_t offsetIndex, UErrorCode * err) { /* This is a fun one. Recursion can occur - we're basically going to just retry shoving data through the same converter. Note, if you got here through some kind of invalid sequence, you maybe should emit a reset sequence of some kind and/or call ucnv_reset(). Since this IS an actual conversion, take care that you've changed the callback or the data, or you'll get an infinite loop. Please set the err value to something reasonable before calling into this. */ char *oldTarget; if(U_FAILURE(*err)) { return; } oldTarget = args->target; ucnv_fromUnicode(args->converter, &args->target, args->targetLimit, source, sourceLimit, NULL, /* no offsets */ FALSE, /* no flush */ err); if(args->offsets) { while (args->target != oldTarget) /* if it moved at all.. */ { *(args->offsets)++ = offsetIndex; oldTarget++; } } /* Note, if you did something like used a Stop subcallback, things would get interesting. In fact, here's where we want to return the partially consumed in-source! */ if(*err == U_BUFFER_OVERFLOW_ERROR) /* && (*source < sourceLimit && args->target >= args->targetLimit) -- S. Hrcek */ { /* Overflowed the target. Now, we'll write into the charErrorBuffer. It's a fixed size. If we overflow it... Hmm */ char *newTarget; const char *newTargetLimit; UErrorCode err2 = U_ZERO_ERROR; int8_t errBuffLen; errBuffLen = args->converter->charErrorBufferLength; /* start the new target at the first free slot in the errbuff.. */ newTarget = (char *)(args->converter->charErrorBuffer + errBuffLen); newTargetLimit = (char *)(args->converter->charErrorBuffer + sizeof(args->converter->charErrorBuffer)); if(newTarget >= newTargetLimit) { *err = U_INTERNAL_PROGRAM_ERROR; return; } /* We're going to tell the converter that the errbuff len is empty. This prevents the existing errbuff from being 'flushed' out onto itself. If the errbuff is needed by the converter this time, we're hosed - we're out of space! */ args->converter->charErrorBufferLength = 0; ucnv_fromUnicode(args->converter, &newTarget, newTargetLimit, source, sourceLimit, NULL, FALSE, &err2); /* We can go ahead and overwrite the length here. We know just how to recalculate it. */ args->converter->charErrorBufferLength = (int8_t)( newTarget - (char*)args->converter->charErrorBuffer); if((newTarget >= newTargetLimit) || (err2 == U_BUFFER_OVERFLOW_ERROR)) { /* now we're REALLY in trouble. Internal program error - callback shouldn't have written this much data! */ *err = U_INTERNAL_PROGRAM_ERROR; return; } /*else {*/ /* sub errs could be invalid/truncated/illegal chars or w/e. These might want to be passed on up.. But the problem is, we already need to pass U_BUFFER_OVERFLOW_ERROR. That has to override these other errs.. */ /* if(U_FAILURE(err2)) ?? */ /*}*/ } } U_CAPI void U_EXPORT2 ucnv_cbFromUWriteSub (UConverterFromUnicodeArgs *args, int32_t offsetIndex, UErrorCode * err) { UConverter *converter; int32_t length; if(U_FAILURE(*err)) { return; } converter = args->converter; length = converter->subCharLen; if(length == 0) { return; } if(length < 0) { /* * Write/convert the substitution string. Its real length is -length. * Unlike the escape callback, we need not change the converter's * callback function because ucnv_setSubstString() verified that * the string can be converted, so we will not get a conversion error * and will not recurse. * At worst we should get a U_BUFFER_OVERFLOW_ERROR. */ const UChar *source = (const UChar *)converter->subChars; ucnv_cbFromUWriteUChars(args, &source, source - length, offsetIndex, err); return; } if(converter->sharedData->impl->writeSub!=NULL) { converter->sharedData->impl->writeSub(args, offsetIndex, err); } else if(converter->subChar1!=0 && (uint16_t)converter->invalidUCharBuffer[0]<=(uint16_t)0xffu) { /* TODO: Is this untestable because the MBCS converter has a writeSub function to call and the other converters don't use subChar1? */ ucnv_cbFromUWriteBytes(args, (const char *)&converter->subChar1, 1, offsetIndex, err); } else { ucnv_cbFromUWriteBytes(args, (const char *)converter->subChars, length, offsetIndex, err); } } U_CAPI void U_EXPORT2 ucnv_cbToUWriteUChars (UConverterToUnicodeArgs *args, const UChar* source, int32_t length, int32_t offsetIndex, UErrorCode * err) { if(U_FAILURE(*err)) { return; } ucnv_toUWriteUChars( args->converter, source, length, &args->target, args->targetLimit, &args->offsets, offsetIndex, err); } U_CAPI void U_EXPORT2 ucnv_cbToUWriteSub (UConverterToUnicodeArgs *args, int32_t offsetIndex, UErrorCode * err) { static const UChar kSubstituteChar1 = 0x1A, kSubstituteChar = 0xFFFD; /* could optimize this case, just one uchar */ if(args->converter->invalidCharLength == 1 && args->converter->subChar1 != 0) { ucnv_cbToUWriteUChars(args, &kSubstituteChar1, 1, offsetIndex, err); } else { ucnv_cbToUWriteUChars(args, &kSubstituteChar, 1, offsetIndex, err); } } #endif
mit
telecamera/opencvr
3rdparty/openssl/crypto/ecdsa/ecs_sign.c
186
4168
/* crypto/ecdsa/ecdsa_sign.c */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "ecs_locl.h" #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include <openssl/rand.h> ECDSA_SIG *ECDSA_do_sign(const unsigned char *dgst, int dlen, EC_KEY *eckey) { return ECDSA_do_sign_ex(dgst, dlen, NULL, NULL, eckey); } ECDSA_SIG *ECDSA_do_sign_ex(const unsigned char *dgst, int dlen, const BIGNUM *kinv, const BIGNUM *rp, EC_KEY *eckey) { ECDSA_DATA *ecdsa = ecdsa_check(eckey); if (ecdsa == NULL) return NULL; return ecdsa->meth->ecdsa_do_sign(dgst, dlen, kinv, rp, eckey); } int ECDSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey) { return ECDSA_sign_ex(type, dgst, dlen, sig, siglen, NULL, NULL, eckey); } int ECDSA_sign_ex(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey) { ECDSA_SIG *s; RAND_seed(dgst, dlen); s = ECDSA_do_sign_ex(dgst, dlen, kinv, r, eckey); if (s == NULL) { *siglen = 0; return 0; } *siglen = i2d_ECDSA_SIG(s, &sig); ECDSA_SIG_free(s); return 1; } int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { ECDSA_DATA *ecdsa = ecdsa_check(eckey); if (ecdsa == NULL) return 0; return ecdsa->meth->ecdsa_sign_setup(eckey, ctx_in, kinvp, rp); }
mit
seem-sky/WinObjC
deps/3rdparty/cairolegacy/src/cairo-font-face-twin-data.c
196
24640
/* See cairo-font-face-twin.c for copyright info */ #include "cairoint.h" const int8_t _cairo_twin_outlines[] = { /* 0x0 '\0' offset 0 */ 0, 24, 42, 0, 2, 2, 0, 24, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 24, -42, 'l', 24, 0, 'l', 0, 0, 'e', 'X', 'X', /* 0x20 ' ' offset 28 */ 0, 4, 0, 0, 0, 0, /* snap_x */ /* snap_y */ 'e', 'X', 'X', 'X', 'X', 'X', /* 0x21 '!' offset 40 */ 0, 0, 42, 0, 1, 3, 0, /* snap_x */ -42, -14, 0, /* snap_y */ 'm', 0, -42, 'l', 0, -14, 'm', 0, 0, 'l', 0, 0, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x22 '"' offset 90 */ 0, 16, 42, -28, 2, 2, 0, 16, /* snap_x */ -42, -28, /* snap_y */ 'm', 0, -42, 'l', 0, -28, 'm', 16, -42, 'l', 16, -28, 'e', 'X', /* 0x23 '#' offset 114 */ 0, 30, 50, 14, 2, 5, 0, 30, /* snap_x */ -24, -21, -15, -12, 0, /* snap_y */ 'm', 16, -50, 'l', 2, 14, 'm', 28, -50, 'l', 14, 14, 'm', 2, -24, 'l', 30, -24, 'm', 0, -12, 'l', 28, -12, 'e', /* 0x24 '$' offset 152 */ 0, 28, 50, 8, 4, 4, 0, 10, 18, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 10, -50, 'l', 10, 8, 'm', 18, -50, 'l', 18, 8, 'm', 28, -36, 'c', 24, -42, 18, -42, 14, -42, 'c', 10, -42, 0, -42, 0, -34, 'c', 0, -25, 8, -24, 14, -22, 'c', 20, -20, 28, -19, 28, -9, 'c', 28, 0, 18, 0, 14, 0, 'c', 10, 0, 4, 0, 0, -6, 'e', /* 0x25 '%' offset 224 */ 0, 36, 42, 0, 4, 7, 0, 14, 22, 36, /* snap_x */ -42, -38, -28, -21, -15, -14, 0, /* snap_y */ 'm', 10, -42, 'c', 12, -41, 14, -40, 14, -36, 'c', 14, -30, 11, -28, 6, -28, 'c', 2, -28, 0, -30, 0, -34, 'c', 0, -39, 3, -42, 8, -42, 'l', 10, -42, 'c', 18, -37, 28, -37, 36, -42, 'l', 0, 0, 'm', 28, -14, 'c', 24, -14, 22, -11, 22, -6, 'c', 22, -2, 24, 0, 28, 0, 'c', 33, 0, 36, -2, 36, -8, 'c', 36, -12, 34, -14, 30, -14, 'l', 28, -14, 'e', 'X', 'X', 'X', /* 0x26 '&' offset 323 */ 0, 40, 42, 0, 4, 4, 0, 10, 22, 40, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 40, -24, 'c', 40, -27, 39, -28, 37, -28, 'c', 29, -28, 32, 0, 12, 0, 'c', 0, 0, 0, -8, 0, -10, 'c', 0, -24, 22, -20, 22, -34, 'c', 22, -45, 10, -45, 10, -34, 'c', 10, -27, 25, 0, 36, 0, 'c', 39, 0, 40, -1, 40, -4, 'e', /* 0x27 ''' offset 390 */ 0, 4, 42, -30, 2, 2, 0, 4, /* snap_x */ -42, -28, /* snap_y */ 'm', 2, -38, 'c', -1, -38, -1, -42, 2, -42, 'c', 6, -42, 5, -33, 0, -30, 'e', 'X', /* 0x28 '(' offset 419 */ 0, 14, 50, 14, 2, 2, 0, 14, /* snap_x */ -50, 14, /* snap_y */ 'm', 14, -50, 'c', -5, -32, -5, -5, 14, 14, 'e', 'X', /* 0x29 ')' offset 441 */ 0, 14, 50, 14, 2, 2, 0, 14, /* snap_x */ -15, 14, /* snap_y */ 'm', 0, -50, 'c', 19, -34, 19, -2, 0, 14, 'e', 'X', /* 0x2a '*' offset 463 */ 0, 20, 30, -6, 3, 3, 0, 10, 20, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 10, -30, 'l', 10, -6, 'm', 0, -24, 'l', 20, -12, 'm', 20, -24, 'l', 0, -12, 'e', /* 0x2b '+' offset 494 */ 0, 36, 36, 0, 3, 4, 0, 18, 36, /* snap_x */ -21, -18, -15, 0, /* snap_y */ 'm', 18, -36, 'l', 18, 0, 'm', 0, -18, 'l', 36, -18, 'e', /* 0x2c ',' offset 520 */ 0, 4, 4, 8, 2, 3, 0, 4, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 4, -2, 'c', 4, 1, 0, 1, 0, -2, 'c', 0, -5, 4, -5, 4, -2, 'c', 4, 4, 2, 6, 0, 8, 'e', /* 0x2d '-' offset 556 */ 0, 36, 18, -18, 2, 4, 0, 36, /* snap_x */ -21, -18, -15, 0, /* snap_y */ 'm', 0, -18, 'l', 36, -18, 'e', /* 0x2e '.' offset 575 */ 0, 4, 4, 0, 2, 3, 0, 4, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 2, -4, 'c', -1, -4, -1, 0, 2, 0, 'c', 5, 0, 5, -4, 2, -4, 'e', /* 0x2f '/' offset 604 */ 0, 36, 50, 14, 2, 3, 0, 36, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 36, -50, 'l', 0, 14, 'e', /* 0x30 '0' offset 622 */ 0, 28, 42, 0, 2, 4, 0, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 14, -42, 'c', 9, -42, 0, -42, 0, -21, 'c', 0, 0, 9, 0, 14, 0, 'c', 19, 0, 28, 0, 28, -21, 'c', 28, -42, 19, -42, 14, -42, 'E', /* 0x31 '1' offset 666 */ 0, 28, 42, 0, 2, 3, 0, 17, 28 /* snap_x */ -42, -34, 0, /* snap_y */ 'm', 7, -34, 'c', 11, -35, 15, -38, 17, -42, 'l', 17, 0, 'e', /* 0x32 '2' offset 691 */ 0, 28, 42, 0, 4, 4, 0, 2, 26, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 2, -32, 'c', 2, -34, 2, -42, 14, -42, 'c', 26, -42, 26, -34, 26, -32, 'c', 26, -30, 25, -25, 10, -10, 'l', 0, 0, 'l', 28, 0, 'e', /* 0x33 '3' offset 736 */ 0, 28, 42, 0, 2, 5, 0, 28, /* snap_x */ -42, -26, -21, -15, 0, /* snap_y */ 'm', 4, -42, 'l', 26, -42, 'l', 14, -26, 'c', 21, -26, 28, -26, 28, -14, 'c', 28, 0, 17, 0, 13, 0, 'c', 8, 0, 3, -1, 0, -8, 'e', /* 0x34 '4' offset 780 */ 0, 28, 42, 0, 3, 3, 0, 20, 30, /* snap_x */ -42, -14, 0, /* snap_y */ 'm', 20, 0, 'l', 20, -42, 'l', 0, -14, 'l', 30, -14, 'e', 'X', 'X', 'X', 'X', /* 0x35 '5' offset 809 */ 0, 28, 42, 0, 2, 5, 0, 28, /* snap_x */ -42, -28, -21, -15, 0, /* snap_y */ 'm', 24, -42, 'l', 4, -42, 'l', 2, -24, 'c', 5, -27, 10, -28, 13, -28, 'c', 16, -28, 28, -28, 28, -14, 'c', 28, 0, 16, 0, 13, 0, 'c', 10, 0, 3, 0, 0, -8, 'e', /* 0x36 '6' offset 860 */ 0, 28, 42, 0, 2, 5, 0, 26, /* snap_x */ -42, -26, -21, -15, 0, /* snap_y */ 'm', 24, -36, 'c', 22, -41, 19, -42, 14, -42, 'c', 9, -42, 0, -41, 0, -19, 'c', 0, -1, 9, 0, 13, 0, 'c', 18, 0, 26, -3, 26, -13, 'c', 26, -18, 23, -26, 13, -26, 'c', 10, -26, 1, -24, 0, -14, 'e', /* 0x37 '7' offset 919 */ 0, 28, 42, 0, 2, 4, 0, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 0, -42, 'l', 28, -42, 'l', 8, 0, 'e', 'X', 'X', 'X', /* 0x38 '8' offset 944 */ 0, 28, 42, 0, 4, 4, 0, 2, 26, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 14, -42, 'c', 5, -42, 2, -40, 2, -34, 'c', 2, -18, 28, -32, 28, -11, 'c', 28, 0, 18, 0, 14, 0, 'c', 10, 0, 0, 0, 0, -11, 'c', 0, -32, 26, -18, 26, -34, 'c', 26, -40, 23, -42, 14, -42, 'E', /* 0x39 '9' offset 1004 */ 0, 28, 42, 0, 2, 5, 0, 26, /* snap_x */ -42, -21, -16, -15, 0, /* snap_y */ 'm', 26, -28, 'c', 25, -16, 13, -16, 13, -16, 'c', 8, -16, 0, -19, 0, -29, 'c', 0, -34, 3, -42, 13, -42, 'c', 24, -42, 26, -32, 26, -23, 'c', 26, -14, 24, 0, 12, 0, 'c', 7, 0, 4, -2, 2, -6, 'e', /* 0x3a ':' offset 1063 */ 0, 4, 28, 0, 2, 3, 0, 4, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 2, -28, 'c', -1, -28, -1, -24, 2, -24, 'c', 5, -24, 5, -28, 2, -28, 'm', 2, -4, 'c', -1, -4, -1, 0, 2, 0, 'c', 5, 0, 5, -4, 2, -4, 'e', /* 0x3b ';' offset 1109 */ 0, 4, 28, 8, 2, 3, 0, 4, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 2, -28, 'c', -1, -28, -1, -24, 2, -24, 'c', 5, -24, 5, -28, 2, -28, 'm', 4, -2, 'c', 4, 1, 0, 1, 0, -2, 'c', 0, -5, 4, -5, 4, -2, 'c', 4, 3, 2, 6, 0, 8, 'e', /* 0x3c '<' offset 1162 */ 0, 32, 36, 0, 2, 3, 0, 32, /* snap_x */ -36, -18, 0, /* snap_y */ 'm', 32, -36, 'l', 0, -18, 'l', 32, 0, 'e', /* 0x3d '=' offset 1183 */ 0, 36, 24, -12, 2, 2, 0, 36, /* snap_x */ -24, -15, /* snap_y */ 'm', 0, -24, 'l', 36, -24, 'm', 0, -12, 'l', 36, -12, 'e', 'X', 'X', 'X', /* 0x3e '>' offset 1209 */ 0, 32, 36, 0, 2, 3, 0, 32, /* snap_x */ -36, -18, 0, /* snap_y */ 'm', 0, -36, 'l', 32, -18, 'l', 0, 0, 'e', /* 0x3f '?' offset 1230 */ 0, 24, 42, 0, 3, 4, 0, 12, 24, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 0, -32, 'c', 0, -34, 0, -42, 12, -42, 'c', 24, -42, 24, -34, 24, -32, 'c', 24, -29, 24, -24, 12, -20, 'l', 12, -14, 'm', 12, 0, 'l', 12, 0, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x40 '@' offset 1288 */ 0, 42, 42, 0, 1, 6, 30, /* snap_x */ -42, -32, -21, -15, -10, 0, /* snap_y */ 'm', 30, -26, 'c', 28, -31, 24, -32, 21, -32, 'c', 10, -32, 10, -23, 10, -19, 'c', 10, -13, 11, -10, 19, -10, 'c', 30, -10, 28, -21, 30, -32, 'c', 27, -10, 30, -10, 34, -10, 'c', 41, -10, 42, -19, 42, -22, 'c', 42, -34, 34, -42, 21, -42, 'c', 9, -42, 0, -34, 0, -21, 'c', 0, -9, 8, 0, 21, 0, 'c', 30, 0, 34, -3, 36, -6, 'e', /* 0x41 'A' offset 1375 */ 0, 32, 42, 0, 2, 3, 0, 32, /* snap_x */ -42, -14, 0, /* snap_y */ 'm', 0, 0, 'l', 16, -42, 'l', 32, 0, 'm', 6, -14, 'l', 26, -14, 'e', 'X', 'X', 'X', 'X', /* 0x42 'B' offset 1406 */ 0, 28, 42, 0, 2, 3, 0, 28, /* snap_x */ -42, -22, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 18, -42, 'c', 32, -42, 32, -22, 18, -22, 'l', 0, -22, 'l', 18, -22, 'c', 32, -22, 32, 0, 18, 0, 'E', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x43 'C' offset 1455 */ 0, 30, 42, 0, 2, 4, 0, 30, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 30, -32, 'c', 26, -42, 21, -42, 16, -42, 'c', 2, -42, 0, -29, 0, -21, 'c', 0, -13, 2, 0, 16, 0, 'c', 21, 0, 26, 0, 30, -10, 'e', /* 0x44 'D' offset 1499 */ 0, 28, 42, 0, 2, 2, 0, 28, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 14, -42, 'c', 33, -42, 33, 0, 14, 0, 'E', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x45 'E' offset 1534 */ 0, 26, 42, 0, 2, 3, 0, 26, /* snap_x */ -42, -22, 0, /* snap_y */ 'm', 26, -42, 'l', 0, -42, 'l', 0, 0, 'l', 26, 0, 'm', 0, -22, 'l', 16, -22, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x46 'F' offset 1572 */ 0, 26, 42, 0, 2, 3, 0, 26, /* snap_x */ -42, -22, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 26, -42, 'm', 0, -22, 'l', 16, -22, 'e', 'X', 'X', 'X', 'X', 'X', /* 0x47 'G' offset 1604 */ 0, 30, 42, 0, 2, 5, 0, 30, /* snap_x */ -42, -21, -16, -15, 0, /* snap_y */ 'm', 30, -32, 'c', 26, -42, 21, -42, 16, -42, 'c', 2, -42, 0, -29, 0, -21, 'c', 0, -13, 2, 0, 16, 0, 'c', 28, 0, 30, -7, 30, -16, 'l', 20, -16, 'e', 'X', 'X', 'X', /* 0x48 'H' offset 1655 */ 0, 28, 42, 0, 2, 3, 0, 28, /* snap_x */ -42, -22, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'm', 28, -42, 'l', 28, 0, 'm', 0, -22, 'l', 28, -22, 'e', 'X', /* 0x49 'I' offset 1686 */ 0, 0, 42, 0, 1, 2, 0, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'e', 'X', /* 0x4a 'J' offset 1703 */ 0, 20, 42, 0, 2, 3, 0, 20, /* snap_x */ -42, -15, 0, /* snap_y */ 'm', 20, -42, 'l', 20, -10, 'c', 20, 3, 0, 3, 0, -10, 'l', 0, -14, 'e', /* 0x4b 'K' offset 1731 */ 0, 28, 42, 0, 2, 3, 0, 28, /* snap_x */ -42, -15, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'm', 28, -42, 'l', 0, -14, 'm', 10, -24, 'l', 28, 0, 'e', /* 0x4c 'L' offset 1761 */ 0, 24, 42, 0, 2, 2, 0, 24, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'l', 24, 0, 'e', 'X', 'X', 'X', 'X', /* 0x4d 'M' offset 1785 */ 0, 32, 42, 0, 2, 2, 0, 32, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 16, 0, 'l', 32, -42, 'l', 32, 0, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x4e 'N' offset 1821 */ 0, 28, 42, 0, 2, 2, 0, 28, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 28, 0, 'l', 28, -42, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x4f 'O' offset 1851 */ 0, 32, 42, 0, 2, 4, 0, 32, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 16, -42, 'c', 2, -42, 0, -29, 0, -21, 'c', 0, -13, 2, 0, 16, 0, 'c', 30, 0, 32, -13, 32, -21, 'c', 32, -29, 30, -42, 16, -42, 'E', /* 0x50 'P' offset 1895 */ 0, 28, 42, 0, 2, 5, 0, 28, /* snap_x */ -42, -21, -20, -15, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 18, -42, 'c', 32, -42, 32, -20, 18, -20, 'l', 0, -20, 'e', 'X', 'X', 'X', /* 0x51 'Q' offset 1931 */ 0, 32, 42, 4, 2, 4, 0, 32, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 16, -42, 'c', 2, -42, 0, -29, 0, -21, 'c', 0, -13, 2, 0, 16, 0, 'c', 30, 0, 32, -13, 32, -21, 'c', 32, -29, 30, -42, 16, -42, 'M', 18, -8, 'l', 30, 4, 'e', /* 0x52 'R' offset 1981 */ 0, 28, 42, 0, 2, 5, 0, 28, /* snap_x */ -42, -22, -21, -15, 0, /* snap_y */ 'm', 0, 0, 'l', 0, -42, 'l', 18, -42, 'c', 32, -42, 31, -22, 18, -22, 'l', 0, -22, 'm', 14, -22, 'l', 28, 0, 'e', 'X', 'X', 'X', /* 0x53 'S' offset 2023 */ 0, 28, 42, 0, 2, 4, 0, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 28, -36, 'c', 25, -41, 21, -42, 14, -42, 'c', 10, -42, 0, -42, 0, -34, 'c', 0, -17, 28, -28, 28, -9, 'c', 28, 0, 19, 0, 14, 0, 'c', 7, 0, 3, -1, 0, -6, 'e', /* 0x54 'T' offset 2074 */ 0, 28, 42, 0, 3, 4, 0, 14, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 14, -42, 'l', 14, 0, 'm', 0, -42, 'l', 28, -42, 'e', /* 0x55 'U' offset 2100 */ 0, 28, 42, 0, 2, 2, 0, 28, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 0, -12, 'c', 0, 4, 28, 4, 28, -12, 'l', 28, -42, 'e', 'X', /* 0x56 'V' offset 2128 */ 0, 32, 42, 0, 2, 2, 0, 32, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 16, 0, 'l', 32, -42, 'e', 'X', 'X', 'X', 'X', /* 0x57 'W' offset 2152 */ 0, 40, 42, 0, 2, 2, 0, 40, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 10, 0, 'l', 20, -42, 'l', 30, 0, 'l', 40, -42, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x58 'X' offset 2188 */ 0, 28, 42, 0, 2, 2, 0, 28, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 28, 0, 'm', 28, -42, 'l', 0, 0, 'e', 'X', /* 0x59 'Y' offset 2212 */ 0, 32, 42, 0, 3, 3, 0, 16, 32, /* snap_x */ -42, -21, 0, /* snap_y */ 'm', 0, -42, 'l', 16, -22, 'l', 16, 0, 'm', 32, -42, 'l', 16, -22, 'e', /* 0x5a 'Z' offset 2240 */ 0, 28, 42, 0, 2, 4, 0, 28, /* snap_x */ -42, -21, -15, 0, /* snap_y */ 'm', 28, 0, 'l', 0, 0, 'l', 28, -42, 'l', 0, -42, 'e', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x5b '[' offset 2271 */ 0, 14, 44, 0, 2, 4, 0, 14, /* snap_x */ -44, -21, -15, 0, /* snap_y */ 'm', 14, -44, 'l', 0, -44, 'l', 0, 0, 'l', 14, 0, 'e', /* 0x5c '\' offset 2296 */ 0, 36, 50, 14, 2, 3, 0, 36, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 0, -50, 'l', 36, 14, 'e', /* 0x5d ']' offset 2314 */ 0, 14, 44, 0, 2, 4, 0, 14, /* snap_x */ -44, -21, -15, 0, /* snap_y */ 'm', 0, -44, 'l', 14, -44, 'l', 14, 0, 'l', 0, 0, 'e', /* 0x5e '^' offset 2339 */ 0, 32, 46, -18, 2, 3, 0, 32, /* snap_x */ -21, -15, 0, /* snap_y */ 'm', 0, -18, 'l', 16, -46, 'l', 32, -18, 'e', 'X', 'X', 'X', /* 0x5f '_' offset 2363 */ 0, 36, 0, 0, 2, 1, 0, 36, /* snap_x */ 0, /* snap_y */ 'm', 0, 0, 'l', 36, 0, 'e', 'X', 'X', /* 0x60 '`' offset 2381 */ 0, 4, 42, -30, 2, 2, 0, 4, /* snap_x */ -42, 0, /* snap_y */ 'm', 4, -42, 'c', 2, -40, 0, -39, 0, -32, 'c', 0, -31, 1, -30, 2, -30, 'c', 5, -30, 5, -34, 2, -34, 'e', 'X', /* 0x61 'a' offset 2417 */ 0, 24, 28, 0, 2, 4, 0, 24, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 24, -28, 'l', 24, 0, 'm', 24, -22, 'c', 21, -27, 18, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -1, 24, -6, 'e', /* 0x62 'b' offset 2467 */ 0, 24, 42, 0, 2, 4, 0, 24, /* snap_x */ -42, -28, -15, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'm', 0, -22, 'c', 3, -26, 6, -28, 11, -28, 'c', 22, -28, 24, -19, 24, -14, 'c', 24, -9, 22, 0, 11, 0, 'c', 6, 0, 3, -2, 0, -6, 'e', /* 0x63 'c' offset 2517 */ 0, 24, 28, 0, 2, 4, 0, 24, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 24, -22, 'c', 21, -26, 18, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -2, 24, -6, 'e', /* 0x64 'd' offset 2561 */ 0, 24, 42, 0, 2, 4, 0, 24, /* snap_x */ -42, -28, -15, 0, /* snap_y */ 'm', 24, -42, 'l', 24, 0, 'm', 24, -22, 'c', 21, -26, 18, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -2, 24, -6, 'e', /* 0x65 'e' offset 2611 */ 0, 24, 28, 0, 2, 5, 0, 24, /* snap_x */ -28, -21, -16, -15, 0, /* snap_y */ 'm', 0, -16, 'l', 24, -16, 'c', 24, -20, 24, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -2, 24, -6, 'e', /* 0x66 'f' offset 2659 */ 0, 16, 42, 0, 3, 5, 0, 6, 16, /* snap_x */ -42, -28, -21, -15, 0, /* snap_y */ 'm', 16, -42, 'c', 8, -42, 6, -40, 6, -34, 'l', 6, 0, 'm', 0, -28, 'l', 14, -28, 'e', /* 0x67 'g' offset 2693 */ 0, 24, 28, 14, 2, 5, 0, 24, /* snap_x */ -28, -21, -15, 0, 14, /* snap_y */ 'm', 24, -28, 'l', 24, 4, 'c', 23, 14, 16, 14, 13, 14, 'c', 10, 14, 8, 14, 6, 12, 'm', 24, -22, 'c', 21, -26, 18, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -2, 24, -6, 'e', /* 0x68 'h' offset 2758 */ 0, 22, 42, 0, 2, 4, 0, 22, /* snap_x */ -42, -28, -15, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'm', 0, -20, 'c', 8, -32, 22, -31, 22, -20, 'l', 22, 0, 'e', /* 0x69 'i' offset 2790 */ 0, 0, 44, 0, 1, 3, 0, /* snap_x */ -42, -28, 0, /* snap_y */ 'm', 0, -42, 'l', 0, -42, 'm', 0, -28, 'l', 0, 0, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x6a 'j' offset 2826 */ -8, 4, 44, 14, 3, 5, -8, 2, 4, /* snap_x */ -42, -21, -15, 0, 14, /* snap_y */ 'm', 2, -42, 'l', 2, -42, 'm', 2, -28, 'l', 2, 6, 'c', 2, 13, -1, 14, -8, 14, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x6b 'k' offset 2870 */ 0, 22, 42, 0, 2, 3, 0, 22, /* snap_x */ -42, -28, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'm', 20, -28, 'l', 0, -8, 'm', 8, -16, 'l', 22, 0, 'e', /* 0x6c 'l' offset 2900 */ 0, 0, 42, 0, 1, 2, 0, /* snap_x */ -42, 0, /* snap_y */ 'm', 0, -42, 'l', 0, 0, 'e', 'X', /* 0x6d 'm' offset 2917 */ 0, 44, 28, 0, 3, 3, 0, 22, 44, /* snap_x */ -28, -21, 0, /* snap_y */ 'm', 0, -28, 'l', 0, 0, 'm', 0, -20, 'c', 5, -29, 22, -33, 22, -20, 'l', 22, 0, 'm', 22, -20, 'c', 27, -29, 44, -33, 44, -20, 'l', 44, 0, 'e', 'X', /* 0x6e 'n' offset 2963 */ 0, 22, 28, 0, 2, 3, 0, 22, /* snap_x */ -28, -21, 0, /* snap_y */ 'm', 0, -28, 'l', 0, 0, 'm', 0, -20, 'c', 4, -28, 22, -34, 22, -20, 'l', 22, 0, 'e', 'X', /* 0x6f 'o' offset 2995 */ 0, 26, 28, 0, 2, 4, 0, 26, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 24, 0, 26, -9, 26, -14, 'c', 26, -19, 24, -28, 13, -28, 'E', /* 0x70 'p' offset 3039 */ 0, 24, 28, 14, 2, 4, 0, 24, /* snap_x */ -28, -21, 0, 14, /* snap_y */ 'm', 0, -28, 'l', 0, 14, 'm', 0, -22, 'c', 3, -26, 6, -28, 11, -28, 'c', 22, -28, 24, -19, 24, -14, 'c', 24, -9, 22, 0, 11, 0, 'c', 6, 0, 3, -2, 0, -6, 'e', /* 0x71 'q' offset 3089 */ 0, 24, 28, 14, 2, 4, 0, 24, /* snap_x */ -28, -21, 0, 14, /* snap_y */ 'm', 24, -28, 'l', 24, 14, 'm', 24, -22, 'c', 21, -26, 18, -28, 13, -28, 'c', 2, -28, 0, -19, 0, -14, 'c', 0, -9, 2, 0, 13, 0, 'c', 18, 0, 21, -2, 24, -6, 'e', /* 0x72 'r' offset 3139 */ 0, 16, 28, 0, 2, 4, 0, 16, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 0, -28, 'l', 0, 0, 'm', 0, -16, 'c', 2, -27, 7, -28, 16, -28, 'e', /* 0x73 's' offset 3168 */ 0, 22, 28, 0, 2, 4, 0, 22, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 22, -22, 'c', 22, -27, 16, -28, 11, -28, 'c', 4, -28, 0, -26, 0, -22, 'c', 0, -11, 22, -20, 22, -7, 'c', 22, 0, 17, 0, 11, 0, 'c', 6, 0, 0, -1, 0, -6, 'e', /* 0x74 't' offset 3219 */ 0, 16, 42, 0, 3, 4, 0, 6, 16, /* snap_x */ -42, -28, -21, 0, /* snap_y */ 'm', 6, -42, 'l', 6, -8, 'c', 6, -2, 8, 0, 16, 0, 'm', 0, -28, 'l', 14, -28, 'e', /* 0x75 'u' offset 3252 */ 0, 22, 28, 0, 2, 3, 0, 22, /* snap_x */ -28, -15, 0, /* snap_y */ 'm', 0, -28, 'l', 0, -8, 'c', 0, 6, 18, 0, 22, -8, 'm', 22, -28, 'l', 22, 0, 'e', /* 0x76 'v' offset 3283 */ 0, 24, 28, 0, 2, 3, 0, 24, /* snap_x */ -28, -15, 0, /* snap_y */ 'm', 0, -28, 'l', 12, 0, 'l', 24, -28, 'e', 'X', 'X', 'X', /* 0x77 'w' offset 3307 */ 0, 32, 28, 0, 2, 3, 0, 32, /* snap_x */ -28, -15, 0, /* snap_y */ 'm', 0, -28, 'l', 8, 0, 'l', 16, -28, 'l', 24, 0, 'l', 32, -28, 'e', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x78 'x' offset 3343 */ 0, 22, 28, 0, 2, 2, 0, 22, /* snap_x */ -28, 0, /* snap_y */ 'm', 0, -28, 'l', 22, 0, 'm', 22, -28, 'l', 0, 0, 'e', 'X', /* 0x79 'y' offset 3367 */ -2, 24, 28, 14, 2, 4, 0, 24, /* snap_x */ -28, -15, 0, 14, /* snap_y */ 'm', 0, -28, 'l', 12, 0, 'm', 24, -28, 'l', 12, 0, 'c', 6, 13, 0, 14, -2, 14, 'e', /* 0x7a 'z' offset 3399 */ 0, 22, 28, 0, 2, 4, 0, 22, /* snap_x */ -28, -21, -15, 0, /* snap_y */ 'm', 22, 0, 'l', 0, 0, 'l', 22, -28, 'l', 0, -28, 'e', 'X', 'X', 'X', 'X', 'X', 'X', /* 0x7b '{' offset 3430 */ 0, 16, 44, 0, 3, 5, 0, 6, 16, /* snap_x */ -44, -24, -21, -15, 0, /* snap_y */ 'm', 16, -44, 'c', 10, -44, 6, -42, 6, -36, 'l', 6, -24, 'l', 0, -24, 'l', 6, -24, 'l', 6, -8, 'c', 6, -2, 10, 0, 16, 0, 'e', /* 0x7c '|' offset 3474 */ 0, 0, 50, 14, 1, 2, 0, /* snap_x */ -50, 14, /* snap_y */ 'm', 0, -50, 'l', 0, 14, 'e', 'X', /* 0x7d '}' offset 3491 */ 0, 16, 44, 0, 3, 5, 0, 10, 16, /* snap_x */ -44, -24, -21, -15, 0, /* snap_y */ 'm', 0, -44, 'c', 6, -44, 10, -42, 10, -36, 'l', 10, -24, 'l', 16, -24, 'l', 10, -24, 'l', 10, -8, 'c', 10, -2, 6, 0, 0, 0, 'e', /* 0x7e '~' offset 3535 */ 0, 36, 24, -12, 2, 5, 0, 36, /* snap_x */ -24, -21, -15, -12, 0, /* snap_y */ 'm', 0, -14, 'c', 1, -21, 4, -24, 8, -24, 'c', 18, -24, 18, -12, 28, -12, 'c', 32, -12, 35, -15, 36, -22, 'e', }; const uint16_t _cairo_twin_charmap[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 40, 90, 114, 152, 224, 323, 390, 419, 441, 463, 494, 520, 556, 575, 604, 622, 666, 691, 736, 780, 809, 860, 919, 944, 1004, 1063, 1109, 1162, 1183, 1209, 1230, 1288, 1375, 1406, 1455, 1499, 1534, 1572, 1604, 1655, 1686, 1703, 1731, 1761, 1785, 1821, 1851, 1895, 1931, 1981, 2023, 2074, 2100, 2128, 2152, 2188, 2212, 2240, 2271, 2296, 2314, 2339, 2363, 2381, 2417, 2467, 2517, 2561, 2611, 2659, 2693, 2758, 2790, 2826, 2870, 2900, 2917, 2963, 2995, 3039, 3089, 3139, 3168, 3219, 3252, 3283, 3307, 3343, 3367, 3399, 3430, 3474, 3491, 3535, 0, };
mit
tony--/WinObjC
deps/3rdparty/iculegacy/source/test/letest/cfonts.cpp
198
1641
/* * * (C) Copyright IBM Corp. 1998-2008 - All Rights Reserved * */ #include "LETypes.h" #include "loengine.h" #include "PortableFontInstance.h" #include "SimpleFontInstance.h" U_CDECL_BEGIN le_font *le_portableFontOpen(const char *fileName, float pointSize, LEErrorCode *status) { return (le_font *) new PortableFontInstance(fileName, pointSize, *status); } le_font *le_simpleFontOpen(float pointSize, LEErrorCode *status) { return (le_font *) new SimpleFontInstance(pointSize, *status); } void le_fontClose(le_font *font) { LEFontInstance *fontInstance = (LEFontInstance *) font; delete fontInstance; } const char *le_getNameString(le_font *font, le_uint16 nameID, le_uint16 platform, le_uint16 encoding, le_uint16 language) { PortableFontInstance *pfi = (PortableFontInstance *) font; return pfi->getNameString(nameID, platform, encoding, language); } const LEUnicode16 *le_getUnicodeNameString(le_font *font, le_uint16 nameID, le_uint16 platform, le_uint16 encoding, le_uint16 language) { PortableFontInstance *pfi = (PortableFontInstance *) font; return pfi->getUnicodeNameString(nameID, platform, encoding, language); } void le_deleteNameString(le_font *font, const char *name) { PortableFontInstance *pfi = (PortableFontInstance *) font; pfi->deleteNameString(name); } void le_deleteUnicodeNameString(le_font *font, const LEUnicode16 *name) { PortableFontInstance *pfi = (PortableFontInstance *) font; pfi->deleteNameString(name); } le_uint32 le_getFontChecksum(le_font *font) { PortableFontInstance *pfi = (PortableFontInstance *) font; return pfi->getFontChecksum(); } U_CDECL_END
mit
b-man/WinObjC
deps/3rdparty/icu/icu/source/common/ucnv.c
203
95035
/* ****************************************************************************** * * Copyright (C) 1998-2013, International Business Machines * Corporation and others. All Rights Reserved. * ****************************************************************************** * * ucnv.c: * Implements APIs for the ICU's codeset conversion library; * mostly calls through internal functions; * created by Bertrand A. Damiba * * Modification History: * * Date Name Description * 04/04/99 helena Fixed internal header inclusion. * 05/09/00 helena Added implementation to handle fallback mappings. * 06/20/2000 helena OS/400 port changes; mostly typecast. */ #include "unicode/utypes.h" #if !UCONFIG_NO_CONVERSION #include "unicode/ustring.h" #include "unicode/ucnv.h" #include "unicode/ucnv_err.h" #include "unicode/uset.h" #include "unicode/utf.h" #include "unicode/utf16.h" #include "putilimp.h" #include "cmemory.h" #include "cstring.h" #include "uassert.h" #include "utracimp.h" #include "ustr_imp.h" #include "ucnv_imp.h" #include "ucnv_cnv.h" #include "ucnv_bld.h" /* size of intermediate and preflighting buffers in ucnv_convert() */ #define CHUNK_SIZE 1024 typedef struct UAmbiguousConverter { const char *name; const UChar variant5c; } UAmbiguousConverter; static const UAmbiguousConverter ambiguousConverters[]={ { "ibm-897_P100-1995", 0xa5 }, { "ibm-942_P120-1999", 0xa5 }, { "ibm-943_P130-1999", 0xa5 }, { "ibm-946_P100-1995", 0xa5 }, { "ibm-33722_P120-1999", 0xa5 }, { "ibm-1041_P100-1995", 0xa5 }, /*{ "ibm-54191_P100-2006", 0xa5 },*/ /*{ "ibm-62383_P100-2007", 0xa5 },*/ /*{ "ibm-891_P100-1995", 0x20a9 },*/ { "ibm-944_P100-1995", 0x20a9 }, { "ibm-949_P110-1999", 0x20a9 }, { "ibm-1363_P110-1997", 0x20a9 }, { "ISO_2022,locale=ko,version=0", 0x20a9 }, { "ibm-1088_P100-1995", 0x20a9 } }; /*Calls through createConverter */ U_CAPI UConverter* U_EXPORT2 ucnv_open (const char *name, UErrorCode * err) { UConverter *r; if (err == NULL || U_FAILURE (*err)) { return NULL; } r = ucnv_createConverter(NULL, name, err); return r; } U_CAPI UConverter* U_EXPORT2 ucnv_openPackage (const char *packageName, const char *converterName, UErrorCode * err) { return ucnv_createConverterFromPackage(packageName, converterName, err); } /*Extracts the UChar* to a char* and calls through createConverter */ U_CAPI UConverter* U_EXPORT2 ucnv_openU (const UChar * name, UErrorCode * err) { char asciiName[UCNV_MAX_CONVERTER_NAME_LENGTH]; if (err == NULL || U_FAILURE(*err)) return NULL; if (name == NULL) return ucnv_open (NULL, err); if (u_strlen(name) >= UCNV_MAX_CONVERTER_NAME_LENGTH) { *err = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } return ucnv_open(u_austrcpy(asciiName, name), err); } /* Copy the string that is represented by the UConverterPlatform enum * @param platformString An output buffer * @param platform An enum representing a platform * @return the length of the copied string. */ static int32_t ucnv_copyPlatformString(char *platformString, UConverterPlatform pltfrm) { switch (pltfrm) { case UCNV_IBM: uprv_strcpy(platformString, "ibm-"); return 4; case UCNV_UNKNOWN: break; } /* default to empty string */ *platformString = 0; return 0; } /*Assumes a $platform-#codepage.$CONVERTER_FILE_EXTENSION scheme and calls *through createConverter*/ U_CAPI UConverter* U_EXPORT2 ucnv_openCCSID (int32_t codepage, UConverterPlatform platform, UErrorCode * err) { char myName[UCNV_MAX_CONVERTER_NAME_LENGTH]; int32_t myNameLen; if (err == NULL || U_FAILURE (*err)) return NULL; /* ucnv_copyPlatformString could return "ibm-" or "cp" */ myNameLen = ucnv_copyPlatformString(myName, platform); T_CString_integerToString(myName + myNameLen, codepage, 10); return ucnv_createConverter(NULL, myName, err); } /* Creating a temporary stack-based object that can be used in one thread, and created from a converter that is shared across threads. */ U_CAPI UConverter* U_EXPORT2 ucnv_safeClone(const UConverter* cnv, void *stackBuffer, int32_t *pBufferSize, UErrorCode *status) { UConverter *localConverter, *allocatedConverter; int32_t stackBufferSize; int32_t bufferSizeNeeded; char *stackBufferChars = (char *)stackBuffer; UErrorCode cbErr; UConverterToUnicodeArgs toUArgs = { sizeof(UConverterToUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; UConverterFromUnicodeArgs fromUArgs = { sizeof(UConverterFromUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; UTRACE_ENTRY_OC(UTRACE_UCNV_CLONE); if (status == NULL || U_FAILURE(*status)){ UTRACE_EXIT_STATUS(status? *status: U_ILLEGAL_ARGUMENT_ERROR); return NULL; } if (cnv == NULL) { *status = U_ILLEGAL_ARGUMENT_ERROR; UTRACE_EXIT_STATUS(*status); return NULL; } UTRACE_DATA3(UTRACE_OPEN_CLOSE, "clone converter %s at %p into stackBuffer %p", ucnv_getName(cnv, status), cnv, stackBuffer); if (cnv->sharedData->impl->safeClone != NULL) { /* call the custom safeClone function for sizing */ bufferSizeNeeded = 0; cnv->sharedData->impl->safeClone(cnv, NULL, &bufferSizeNeeded, status); if (U_FAILURE(*status)) { UTRACE_EXIT_STATUS(*status); return NULL; } } else { /* inherent sizing */ bufferSizeNeeded = sizeof(UConverter); } if (pBufferSize == NULL) { stackBufferSize = 1; pBufferSize = &stackBufferSize; } else { stackBufferSize = *pBufferSize; if (stackBufferSize <= 0){ /* 'preflighting' request - set needed size into *pBufferSize */ *pBufferSize = bufferSizeNeeded; UTRACE_EXIT_VALUE(bufferSizeNeeded); return NULL; } } /* Pointers on 64-bit platforms need to be aligned * on a 64-bit boundary in memory. */ if (U_ALIGNMENT_OFFSET(stackBuffer) != 0) { int32_t offsetUp = (int32_t)U_ALIGNMENT_OFFSET_UP(stackBufferChars); if(stackBufferSize > offsetUp) { stackBufferSize -= offsetUp; stackBufferChars += offsetUp; } else { /* prevent using the stack buffer but keep the size > 0 so that we do not just preflight */ stackBufferSize = 1; } } stackBuffer = (void *)stackBufferChars; /* Now, see if we must allocate any memory */ if (stackBufferSize < bufferSizeNeeded || stackBuffer == NULL) { /* allocate one here...*/ localConverter = allocatedConverter = (UConverter *) uprv_malloc (bufferSizeNeeded); if(localConverter == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; UTRACE_EXIT_STATUS(*status); return NULL; } *status = U_SAFECLONE_ALLOCATED_WARNING; /* record the fact that memory was allocated */ *pBufferSize = bufferSizeNeeded; } else { /* just use the stack buffer */ localConverter = (UConverter*) stackBuffer; allocatedConverter = NULL; } uprv_memset(localConverter, 0, bufferSizeNeeded); /* Copy initial state */ uprv_memcpy(localConverter, cnv, sizeof(UConverter)); localConverter->isCopyLocal = localConverter->isExtraLocal = FALSE; /* copy the substitution string */ if (cnv->subChars == (uint8_t *)cnv->subUChars) { localConverter->subChars = (uint8_t *)localConverter->subUChars; } else { localConverter->subChars = (uint8_t *)uprv_malloc(UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR); if (localConverter->subChars == NULL) { uprv_free(allocatedConverter); UTRACE_EXIT_STATUS(*status); return NULL; } uprv_memcpy(localConverter->subChars, cnv->subChars, UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR); } /* now either call the safeclone fcn or not */ if (cnv->sharedData->impl->safeClone != NULL) { /* call the custom safeClone function */ localConverter = cnv->sharedData->impl->safeClone(cnv, localConverter, pBufferSize, status); } if(localConverter==NULL || U_FAILURE(*status)) { if (allocatedConverter != NULL && allocatedConverter->subChars != (uint8_t *)allocatedConverter->subUChars) { uprv_free(allocatedConverter->subChars); } uprv_free(allocatedConverter); UTRACE_EXIT_STATUS(*status); return NULL; } /* increment refcount of shared data if needed */ /* Checking whether it's an algorithic converter is okay in multithreaded applications because the value never changes. Don't check referenceCounter for any other value. */ if (cnv->sharedData->referenceCounter != ~0) { ucnv_incrementRefCount(cnv->sharedData); } if(localConverter == (UConverter*)stackBuffer) { /* we're using user provided data - set to not destroy */ localConverter->isCopyLocal = TRUE; } /* allow callback functions to handle any memory allocation */ toUArgs.converter = fromUArgs.converter = localConverter; cbErr = U_ZERO_ERROR; cnv->fromCharErrorBehaviour(cnv->toUContext, &toUArgs, NULL, 0, UCNV_CLONE, &cbErr); cbErr = U_ZERO_ERROR; cnv->fromUCharErrorBehaviour(cnv->fromUContext, &fromUArgs, NULL, 0, 0, UCNV_CLONE, &cbErr); UTRACE_EXIT_PTR_STATUS(localConverter, *status); return localConverter; } /*Decreases the reference counter in the shared immutable section of the object *and frees the mutable part*/ U_CAPI void U_EXPORT2 ucnv_close (UConverter * converter) { UErrorCode errorCode = U_ZERO_ERROR; UTRACE_ENTRY_OC(UTRACE_UCNV_CLOSE); if (converter == NULL) { UTRACE_EXIT(); return; } UTRACE_DATA3(UTRACE_OPEN_CLOSE, "close converter %s at %p, isCopyLocal=%b", ucnv_getName(converter, &errorCode), converter, converter->isCopyLocal); /* In order to speed up the close, only call the callbacks when they have been changed. This performance check will only work when the callbacks are set within a shared library or from user code that statically links this code. */ /* first, notify the callback functions that the converter is closed */ if (converter->fromCharErrorBehaviour != UCNV_TO_U_DEFAULT_CALLBACK) { UConverterToUnicodeArgs toUArgs = { sizeof(UConverterToUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; toUArgs.converter = converter; errorCode = U_ZERO_ERROR; converter->fromCharErrorBehaviour(converter->toUContext, &toUArgs, NULL, 0, UCNV_CLOSE, &errorCode); } if (converter->fromUCharErrorBehaviour != UCNV_FROM_U_DEFAULT_CALLBACK) { UConverterFromUnicodeArgs fromUArgs = { sizeof(UConverterFromUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; fromUArgs.converter = converter; errorCode = U_ZERO_ERROR; converter->fromUCharErrorBehaviour(converter->fromUContext, &fromUArgs, NULL, 0, 0, UCNV_CLOSE, &errorCode); } if (converter->sharedData->impl->close != NULL) { converter->sharedData->impl->close(converter); } if (converter->subChars != (uint8_t *)converter->subUChars) { uprv_free(converter->subChars); } /* Checking whether it's an algorithic converter is okay in multithreaded applications because the value never changes. Don't check referenceCounter for any other value. */ if (converter->sharedData->referenceCounter != ~0) { ucnv_unloadSharedDataIfReady(converter->sharedData); } if(!converter->isCopyLocal){ uprv_free(converter); } UTRACE_EXIT(); } /*returns a single Name from the list, will return NULL if out of bounds */ U_CAPI const char* U_EXPORT2 ucnv_getAvailableName (int32_t n) { if (0 <= n && n <= 0xffff) { UErrorCode err = U_ZERO_ERROR; const char *name = ucnv_bld_getAvailableConverter((uint16_t)n, &err); if (U_SUCCESS(err)) { return name; } } return NULL; } U_CAPI int32_t U_EXPORT2 ucnv_countAvailable () { UErrorCode err = U_ZERO_ERROR; return ucnv_bld_countAvailableConverters(&err); } U_CAPI void U_EXPORT2 ucnv_getSubstChars (const UConverter * converter, char *mySubChar, int8_t * len, UErrorCode * err) { if (U_FAILURE (*err)) return; if (converter->subCharLen <= 0) { /* Unicode string or empty string from ucnv_setSubstString(). */ *len = 0; return; } if (*len < converter->subCharLen) /*not enough space in subChars */ { *err = U_INDEX_OUTOFBOUNDS_ERROR; return; } uprv_memcpy (mySubChar, converter->subChars, converter->subCharLen); /*fills in the subchars */ *len = converter->subCharLen; /*store # of bytes copied to buffer */ } U_CAPI void U_EXPORT2 ucnv_setSubstChars (UConverter * converter, const char *mySubChar, int8_t len, UErrorCode * err) { if (U_FAILURE (*err)) return; /*Makes sure that the subChar is within the codepages char length boundaries */ if ((len > converter->sharedData->staticData->maxBytesPerChar) || (len < converter->sharedData->staticData->minBytesPerChar)) { *err = U_ILLEGAL_ARGUMENT_ERROR; return; } uprv_memcpy (converter->subChars, mySubChar, len); /*copies the subchars */ converter->subCharLen = len; /*sets the new len */ /* * There is currently (2001Feb) no separate API to set/get subChar1. * In order to always have subChar written after it is explicitly set, * we set subChar1 to 0. */ converter->subChar1 = 0; return; } U_CAPI void U_EXPORT2 ucnv_setSubstString(UConverter *cnv, const UChar *s, int32_t length, UErrorCode *err) { UAlignedMemory cloneBuffer[U_CNV_SAFECLONE_BUFFERSIZE / sizeof(UAlignedMemory) + 1]; char chars[UCNV_ERROR_BUFFER_LENGTH]; UConverter *clone; uint8_t *subChars; int32_t cloneSize, length8; /* Let the following functions check all arguments. */ cloneSize = sizeof(cloneBuffer); clone = ucnv_safeClone(cnv, cloneBuffer, &cloneSize, err); ucnv_setFromUCallBack(clone, UCNV_FROM_U_CALLBACK_STOP, NULL, NULL, NULL, err); length8 = ucnv_fromUChars(clone, chars, (int32_t)sizeof(chars), s, length, err); ucnv_close(clone); if (U_FAILURE(*err)) { return; } if (cnv->sharedData->impl->writeSub == NULL #if !UCONFIG_NO_LEGACY_CONVERSION || (cnv->sharedData->staticData->conversionType == UCNV_MBCS && ucnv_MBCSGetType(cnv) != UCNV_EBCDIC_STATEFUL) #endif ) { /* The converter is not stateful. Store the charset bytes as a fixed string. */ subChars = (uint8_t *)chars; } else { /* * The converter has a non-default writeSub() function, indicating * that it is stateful. * Store the Unicode string for on-the-fly conversion for correct * state handling. */ if (length > UCNV_ERROR_BUFFER_LENGTH) { /* * Should not occur. The converter should output at least one byte * per UChar, which means that ucnv_fromUChars() should catch all * overflows. */ *err = U_BUFFER_OVERFLOW_ERROR; return; } subChars = (uint8_t *)s; if (length < 0) { length = u_strlen(s); } length8 = length * U_SIZEOF_UCHAR; } /* * For storing the substitution string, select either the small buffer inside * UConverter or allocate a subChars buffer. */ if (length8 > UCNV_MAX_SUBCHAR_LEN) { /* Use a separate buffer for the string. Outside UConverter to not make it too large. */ if (cnv->subChars == (uint8_t *)cnv->subUChars) { /* Allocate a new buffer for the string. */ cnv->subChars = (uint8_t *)uprv_malloc(UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR); if (cnv->subChars == NULL) { cnv->subChars = (uint8_t *)cnv->subUChars; *err = U_MEMORY_ALLOCATION_ERROR; return; } uprv_memset(cnv->subChars, 0, UCNV_ERROR_BUFFER_LENGTH * U_SIZEOF_UCHAR); } } /* Copy the substitution string into the UConverter or its subChars buffer. */ if (length8 == 0) { cnv->subCharLen = 0; } else { uprv_memcpy(cnv->subChars, subChars, length8); if (subChars == (uint8_t *)chars) { cnv->subCharLen = (int8_t)length8; } else /* subChars == s */ { cnv->subCharLen = (int8_t)-length; } } /* See comment in ucnv_setSubstChars(). */ cnv->subChar1 = 0; } /*resets the internal states of a converter *goal : have the same behaviour than a freshly created converter */ static void _reset(UConverter *converter, UConverterResetChoice choice, UBool callCallback) { if(converter == NULL) { return; } if(callCallback) { /* first, notify the callback functions that the converter is reset */ UErrorCode errorCode; if(choice<=UCNV_RESET_TO_UNICODE && converter->fromCharErrorBehaviour != UCNV_TO_U_DEFAULT_CALLBACK) { UConverterToUnicodeArgs toUArgs = { sizeof(UConverterToUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; toUArgs.converter = converter; errorCode = U_ZERO_ERROR; converter->fromCharErrorBehaviour(converter->toUContext, &toUArgs, NULL, 0, UCNV_RESET, &errorCode); } if(choice!=UCNV_RESET_TO_UNICODE && converter->fromUCharErrorBehaviour != UCNV_FROM_U_DEFAULT_CALLBACK) { UConverterFromUnicodeArgs fromUArgs = { sizeof(UConverterFromUnicodeArgs), TRUE, NULL, NULL, NULL, NULL, NULL, NULL }; fromUArgs.converter = converter; errorCode = U_ZERO_ERROR; converter->fromUCharErrorBehaviour(converter->fromUContext, &fromUArgs, NULL, 0, 0, UCNV_RESET, &errorCode); } } /* now reset the converter itself */ if(choice<=UCNV_RESET_TO_UNICODE) { converter->toUnicodeStatus = converter->sharedData->toUnicodeStatus; converter->mode = 0; converter->toULength = 0; converter->invalidCharLength = converter->UCharErrorBufferLength = 0; converter->preToULength = 0; } if(choice!=UCNV_RESET_TO_UNICODE) { converter->fromUnicodeStatus = 0; converter->fromUChar32 = 0; converter->invalidUCharLength = converter->charErrorBufferLength = 0; converter->preFromUFirstCP = U_SENTINEL; converter->preFromULength = 0; } if (converter->sharedData->impl->reset != NULL) { /* call the custom reset function */ converter->sharedData->impl->reset(converter, choice); } } U_CAPI void U_EXPORT2 ucnv_reset(UConverter *converter) { _reset(converter, UCNV_RESET_BOTH, TRUE); } U_CAPI void U_EXPORT2 ucnv_resetToUnicode(UConverter *converter) { _reset(converter, UCNV_RESET_TO_UNICODE, TRUE); } U_CAPI void U_EXPORT2 ucnv_resetFromUnicode(UConverter *converter) { _reset(converter, UCNV_RESET_FROM_UNICODE, TRUE); } U_CAPI int8_t U_EXPORT2 ucnv_getMaxCharSize (const UConverter * converter) { return converter->maxBytesPerUChar; } U_CAPI int8_t U_EXPORT2 ucnv_getMinCharSize (const UConverter * converter) { return converter->sharedData->staticData->minBytesPerChar; } U_CAPI const char* U_EXPORT2 ucnv_getName (const UConverter * converter, UErrorCode * err) { if (U_FAILURE (*err)) return NULL; if(converter->sharedData->impl->getName){ const char* temp= converter->sharedData->impl->getName(converter); if(temp) return temp; } return converter->sharedData->staticData->name; } U_CAPI int32_t U_EXPORT2 ucnv_getCCSID(const UConverter * converter, UErrorCode * err) { int32_t ccsid; if (U_FAILURE (*err)) return -1; ccsid = converter->sharedData->staticData->codepage; if (ccsid == 0) { /* Rare case. This is for cases like gb18030, which doesn't have an IBM canonical name, but does have an IBM alias. */ const char *standardName = ucnv_getStandardName(ucnv_getName(converter, err), "IBM", err); if (U_SUCCESS(*err) && standardName) { const char *ccsidStr = uprv_strchr(standardName, '-'); if (ccsidStr) { ccsid = (int32_t)atol(ccsidStr+1); /* +1 to skip '-' */ } } } return ccsid; } U_CAPI UConverterPlatform U_EXPORT2 ucnv_getPlatform (const UConverter * converter, UErrorCode * err) { if (U_FAILURE (*err)) return UCNV_UNKNOWN; return (UConverterPlatform)converter->sharedData->staticData->platform; } U_CAPI void U_EXPORT2 ucnv_getToUCallBack (const UConverter * converter, UConverterToUCallback *action, const void **context) { *action = converter->fromCharErrorBehaviour; *context = converter->toUContext; } U_CAPI void U_EXPORT2 ucnv_getFromUCallBack (const UConverter * converter, UConverterFromUCallback *action, const void **context) { *action = converter->fromUCharErrorBehaviour; *context = converter->fromUContext; } U_CAPI void U_EXPORT2 ucnv_setToUCallBack (UConverter * converter, UConverterToUCallback newAction, const void* newContext, UConverterToUCallback *oldAction, const void** oldContext, UErrorCode * err) { if (U_FAILURE (*err)) return; if (oldAction) *oldAction = converter->fromCharErrorBehaviour; converter->fromCharErrorBehaviour = newAction; if (oldContext) *oldContext = converter->toUContext; converter->toUContext = newContext; } U_CAPI void U_EXPORT2 ucnv_setFromUCallBack (UConverter * converter, UConverterFromUCallback newAction, const void* newContext, UConverterFromUCallback *oldAction, const void** oldContext, UErrorCode * err) { if (U_FAILURE (*err)) return; if (oldAction) *oldAction = converter->fromUCharErrorBehaviour; converter->fromUCharErrorBehaviour = newAction; if (oldContext) *oldContext = converter->fromUContext; converter->fromUContext = newContext; } static void _updateOffsets(int32_t *offsets, int32_t length, int32_t sourceIndex, int32_t errorInputLength) { int32_t *limit; int32_t delta, offset; if(sourceIndex>=0) { /* * adjust each offset by adding the previous sourceIndex * minus the length of the input sequence that caused an * error, if any */ delta=sourceIndex-errorInputLength; } else { /* * set each offset to -1 because this conversion function * does not handle offsets */ delta=-1; } limit=offsets+length; if(delta==0) { /* most common case, nothing to do */ } else if(delta>0) { /* add the delta to each offset (but not if the offset is <0) */ while(offsets<limit) { offset=*offsets; if(offset>=0) { *offsets=offset+delta; } ++offsets; } } else /* delta<0 */ { /* * set each offset to -1 because this conversion function * does not handle offsets * or the error input sequence started in a previous buffer */ while(offsets<limit) { *offsets++=-1; } } } /* ucnv_fromUnicode --------------------------------------------------------- */ /* * Implementation note for m:n conversions * * While collecting source units to find the longest match for m:n conversion, * some source units may need to be stored for a partial match. * When a second buffer does not yield a match on all of the previously stored * source units, then they must be "replayed", i.e., fed back into the converter. * * The code relies on the fact that replaying will not nest - * converting a replay buffer will not result in a replay. * This is because a replay is necessary only after the _continuation_ of a * partial match failed, but a replay buffer is converted as a whole. * It may result in some of its units being stored again for a partial match, * but there will not be a continuation _during_ the replay which could fail. * * It is conceivable that a callback function could call the converter * recursively in a way that causes another replay to be stored, but that * would be an error in the callback function. * Such violations will cause assertion failures in a debug build, * and wrong output, but they will not cause a crash. */ static void _fromUnicodeWithCallback(UConverterFromUnicodeArgs *pArgs, UErrorCode *err) { UConverterFromUnicode fromUnicode; UConverter *cnv; const UChar *s; char *t; int32_t *offsets; int32_t sourceIndex; int32_t errorInputLength; UBool converterSawEndOfInput, calledCallback; /* variables for m:n conversion */ UChar replay[UCNV_EXT_MAX_UCHARS]; const UChar *realSource, *realSourceLimit; int32_t realSourceIndex; UBool realFlush; cnv=pArgs->converter; s=pArgs->source; t=pArgs->target; offsets=pArgs->offsets; /* get the converter implementation function */ sourceIndex=0; if(offsets==NULL) { fromUnicode=cnv->sharedData->impl->fromUnicode; } else { fromUnicode=cnv->sharedData->impl->fromUnicodeWithOffsets; if(fromUnicode==NULL) { /* there is no WithOffsets implementation */ fromUnicode=cnv->sharedData->impl->fromUnicode; /* we will write -1 for each offset */ sourceIndex=-1; } } if(cnv->preFromULength>=0) { /* normal mode */ realSource=NULL; /* avoid compiler warnings - not otherwise necessary, and the values do not matter */ realSourceLimit=NULL; realFlush=FALSE; realSourceIndex=0; } else { /* * Previous m:n conversion stored source units from a partial match * and failed to consume all of them. * We need to "replay" them from a temporary buffer and convert them first. */ realSource=pArgs->source; realSourceLimit=pArgs->sourceLimit; realFlush=pArgs->flush; realSourceIndex=sourceIndex; uprv_memcpy(replay, cnv->preFromU, -cnv->preFromULength*U_SIZEOF_UCHAR); pArgs->source=replay; pArgs->sourceLimit=replay-cnv->preFromULength; pArgs->flush=FALSE; sourceIndex=-1; cnv->preFromULength=0; } /* * loop for conversion and error handling * * loop { * convert * loop { * update offsets * handle end of input * handle errors/call callback * } * } */ for(;;) { if(U_SUCCESS(*err)) { /* convert */ fromUnicode(pArgs, err); /* * set a flag for whether the converter * successfully processed the end of the input * * need not check cnv->preFromULength==0 because a replay (<0) will cause * s<sourceLimit before converterSawEndOfInput is checked */ converterSawEndOfInput= (UBool)(U_SUCCESS(*err) && pArgs->flush && pArgs->source==pArgs->sourceLimit && cnv->fromUChar32==0); } else { /* handle error from ucnv_convertEx() */ converterSawEndOfInput=FALSE; } /* no callback called yet for this iteration */ calledCallback=FALSE; /* no sourceIndex adjustment for conversion, only for callback output */ errorInputLength=0; /* * loop for offsets and error handling * * iterates at most 3 times: * 1. to clean up after the conversion function * 2. after the callback * 3. after the callback again if there was truncated input */ for(;;) { /* update offsets if we write any */ if(offsets!=NULL) { int32_t length=(int32_t)(pArgs->target-t); if(length>0) { _updateOffsets(offsets, length, sourceIndex, errorInputLength); /* * if a converter handles offsets and updates the offsets * pointer at the end, then pArgs->offset should not change * here; * however, some converters do not handle offsets at all * (sourceIndex<0) or may not update the offsets pointer */ pArgs->offsets=offsets+=length; } if(sourceIndex>=0) { sourceIndex+=(int32_t)(pArgs->source-s); } } if(cnv->preFromULength<0) { /* * switch the source to new replay units (cannot occur while replaying) * after offset handling and before end-of-input and callback handling */ if(realSource==NULL) { realSource=pArgs->source; realSourceLimit=pArgs->sourceLimit; realFlush=pArgs->flush; realSourceIndex=sourceIndex; uprv_memcpy(replay, cnv->preFromU, -cnv->preFromULength*U_SIZEOF_UCHAR); pArgs->source=replay; pArgs->sourceLimit=replay-cnv->preFromULength; pArgs->flush=FALSE; if((sourceIndex+=cnv->preFromULength)<0) { sourceIndex=-1; } cnv->preFromULength=0; } else { /* see implementation note before _fromUnicodeWithCallback() */ U_ASSERT(realSource==NULL); *err=U_INTERNAL_PROGRAM_ERROR; } } /* update pointers */ s=pArgs->source; t=pArgs->target; if(U_SUCCESS(*err)) { if(s<pArgs->sourceLimit) { /* * continue with the conversion loop while there is still input left * (continue converting by breaking out of only the inner loop) */ break; } else if(realSource!=NULL) { /* switch back from replaying to the real source and continue */ pArgs->source=realSource; pArgs->sourceLimit=realSourceLimit; pArgs->flush=realFlush; sourceIndex=realSourceIndex; realSource=NULL; break; } else if(pArgs->flush && cnv->fromUChar32!=0) { /* * the entire input stream is consumed * and there is a partial, truncated input sequence left */ /* inject an error and continue with callback handling */ *err=U_TRUNCATED_CHAR_FOUND; calledCallback=FALSE; /* new error condition */ } else { /* input consumed */ if(pArgs->flush) { /* * return to the conversion loop once more if the flush * flag is set and the conversion function has not * successfully processed the end of the input yet * * (continue converting by breaking out of only the inner loop) */ if(!converterSawEndOfInput) { break; } /* reset the converter without calling the callback function */ _reset(cnv, UCNV_RESET_FROM_UNICODE, FALSE); } /* done successfully */ return; } } /* U_FAILURE(*err) */ { UErrorCode e; if( calledCallback || (e=*err)==U_BUFFER_OVERFLOW_ERROR || (e!=U_INVALID_CHAR_FOUND && e!=U_ILLEGAL_CHAR_FOUND && e!=U_TRUNCATED_CHAR_FOUND) ) { /* * the callback did not or cannot resolve the error: * set output pointers and return * * the check for buffer overflow is redundant but it is * a high-runner case and hopefully documents the intent * well * * if we were replaying, then the replay buffer must be * copied back into the UConverter * and the real arguments must be restored */ if(realSource!=NULL) { int32_t length; U_ASSERT(cnv->preFromULength==0); length=(int32_t)(pArgs->sourceLimit-pArgs->source); if(length>0) { uprv_memcpy(cnv->preFromU, pArgs->source, length*U_SIZEOF_UCHAR); cnv->preFromULength=(int8_t)-length; } pArgs->source=realSource; pArgs->sourceLimit=realSourceLimit; pArgs->flush=realFlush; } return; } } /* callback handling */ { UChar32 codePoint; /* get and write the code point */ codePoint=cnv->fromUChar32; errorInputLength=0; U16_APPEND_UNSAFE(cnv->invalidUCharBuffer, errorInputLength, codePoint); cnv->invalidUCharLength=(int8_t)errorInputLength; /* set the converter state to deal with the next character */ cnv->fromUChar32=0; /* call the callback function */ cnv->fromUCharErrorBehaviour(cnv->fromUContext, pArgs, cnv->invalidUCharBuffer, errorInputLength, codePoint, *err==U_INVALID_CHAR_FOUND ? UCNV_UNASSIGNED : UCNV_ILLEGAL, err); } /* * loop back to the offset handling * * this flag will indicate after offset handling * that a callback was called; * if the callback did not resolve the error, then we return */ calledCallback=TRUE; } } } /* * Output the fromUnicode overflow buffer. * Call this function if(cnv->charErrorBufferLength>0). * @return TRUE if overflow */ static UBool ucnv_outputOverflowFromUnicode(UConverter *cnv, char **target, const char *targetLimit, int32_t **pOffsets, UErrorCode *err) { int32_t *offsets; char *overflow, *t; int32_t i, length; t=*target; if(pOffsets!=NULL) { offsets=*pOffsets; } else { offsets=NULL; } overflow=(char *)cnv->charErrorBuffer; length=cnv->charErrorBufferLength; i=0; while(i<length) { if(t==targetLimit) { /* the overflow buffer contains too much, keep the rest */ int32_t j=0; do { overflow[j++]=overflow[i++]; } while(i<length); cnv->charErrorBufferLength=(int8_t)j; *target=t; if(offsets!=NULL) { *pOffsets=offsets; } *err=U_BUFFER_OVERFLOW_ERROR; return TRUE; } /* copy the overflow contents to the target */ *t++=overflow[i++]; if(offsets!=NULL) { *offsets++=-1; /* no source index available for old output */ } } /* the overflow buffer is completely copied to the target */ cnv->charErrorBufferLength=0; *target=t; if(offsets!=NULL) { *pOffsets=offsets; } return FALSE; } U_CAPI void U_EXPORT2 ucnv_fromUnicode(UConverter *cnv, char **target, const char *targetLimit, const UChar **source, const UChar *sourceLimit, int32_t *offsets, UBool flush, UErrorCode *err) { UConverterFromUnicodeArgs args; const UChar *s; char *t; /* check parameters */ if(err==NULL || U_FAILURE(*err)) { return; } if(cnv==NULL || target==NULL || source==NULL) { *err=U_ILLEGAL_ARGUMENT_ERROR; return; } s=*source; t=*target; if ((const void *)U_MAX_PTR(sourceLimit) == (const void *)sourceLimit) { /* Prevent code from going into an infinite loop in case we do hit this limit. The limit pointer is expected to be on a UChar * boundary. This also prevents the next argument check from failing. */ sourceLimit = (const UChar *)(((const char *)sourceLimit) - 1); } /* * All these conditions should never happen. * * 1) Make sure that the limits are >= to the address source or target * * 2) Make sure that the buffer sizes do not exceed the number range for * int32_t because some functions use the size (in units or bytes) * rather than comparing pointers, and because offsets are int32_t values. * * size_t is guaranteed to be unsigned and large enough for the job. * * Return with an error instead of adjusting the limits because we would * not be able to maintain the semantics that either the source must be * consumed or the target filled (unless an error occurs). * An adjustment would be targetLimit=t+0x7fffffff; for example. * * 3) Make sure that the user didn't incorrectly cast a UChar * pointer * to a char * pointer and provide an incomplete UChar code unit. */ if (sourceLimit<s || targetLimit<t || ((size_t)(sourceLimit-s)>(size_t)0x3fffffff && sourceLimit>s) || ((size_t)(targetLimit-t)>(size_t)0x7fffffff && targetLimit>t) || (((const char *)sourceLimit-(const char *)s) & 1) != 0) { *err=U_ILLEGAL_ARGUMENT_ERROR; return; } /* output the target overflow buffer */ if( cnv->charErrorBufferLength>0 && ucnv_outputOverflowFromUnicode(cnv, target, targetLimit, &offsets, err) ) { /* U_BUFFER_OVERFLOW_ERROR */ return; } /* *target may have moved, therefore stop using t */ if(!flush && s==sourceLimit && cnv->preFromULength>=0) { /* the overflow buffer is emptied and there is no new input: we are done */ return; } /* * Do not simply return with a buffer overflow error if * !flush && t==targetLimit * because it is possible that the source will not generate any output. * For example, the skip callback may be called; * it does not output anything. */ /* prepare the converter arguments */ args.converter=cnv; args.flush=flush; args.offsets=offsets; args.source=s; args.sourceLimit=sourceLimit; args.target=*target; args.targetLimit=targetLimit; args.size=sizeof(args); _fromUnicodeWithCallback(&args, err); *source=args.source; *target=args.target; } /* ucnv_toUnicode() --------------------------------------------------------- */ static void _toUnicodeWithCallback(UConverterToUnicodeArgs *pArgs, UErrorCode *err) { UConverterToUnicode toUnicode; UConverter *cnv; const char *s; UChar *t; int32_t *offsets; int32_t sourceIndex; int32_t errorInputLength; UBool converterSawEndOfInput, calledCallback; /* variables for m:n conversion */ char replay[UCNV_EXT_MAX_BYTES]; const char *realSource, *realSourceLimit; int32_t realSourceIndex; UBool realFlush; cnv=pArgs->converter; s=pArgs->source; t=pArgs->target; offsets=pArgs->offsets; /* get the converter implementation function */ sourceIndex=0; if(offsets==NULL) { toUnicode=cnv->sharedData->impl->toUnicode; } else { toUnicode=cnv->sharedData->impl->toUnicodeWithOffsets; if(toUnicode==NULL) { /* there is no WithOffsets implementation */ toUnicode=cnv->sharedData->impl->toUnicode; /* we will write -1 for each offset */ sourceIndex=-1; } } if(cnv->preToULength>=0) { /* normal mode */ realSource=NULL; /* avoid compiler warnings - not otherwise necessary, and the values do not matter */ realSourceLimit=NULL; realFlush=FALSE; realSourceIndex=0; } else { /* * Previous m:n conversion stored source units from a partial match * and failed to consume all of them. * We need to "replay" them from a temporary buffer and convert them first. */ realSource=pArgs->source; realSourceLimit=pArgs->sourceLimit; realFlush=pArgs->flush; realSourceIndex=sourceIndex; uprv_memcpy(replay, cnv->preToU, -cnv->preToULength); pArgs->source=replay; pArgs->sourceLimit=replay-cnv->preToULength; pArgs->flush=FALSE; sourceIndex=-1; cnv->preToULength=0; } /* * loop for conversion and error handling * * loop { * convert * loop { * update offsets * handle end of input * handle errors/call callback * } * } */ for(;;) { if(U_SUCCESS(*err)) { /* convert */ toUnicode(pArgs, err); /* * set a flag for whether the converter * successfully processed the end of the input * * need not check cnv->preToULength==0 because a replay (<0) will cause * s<sourceLimit before converterSawEndOfInput is checked */ converterSawEndOfInput= (UBool)(U_SUCCESS(*err) && pArgs->flush && pArgs->source==pArgs->sourceLimit && cnv->toULength==0); } else { /* handle error from getNextUChar() or ucnv_convertEx() */ converterSawEndOfInput=FALSE; } /* no callback called yet for this iteration */ calledCallback=FALSE; /* no sourceIndex adjustment for conversion, only for callback output */ errorInputLength=0; /* * loop for offsets and error handling * * iterates at most 3 times: * 1. to clean up after the conversion function * 2. after the callback * 3. after the callback again if there was truncated input */ for(;;) { /* update offsets if we write any */ if(offsets!=NULL) { int32_t length=(int32_t)(pArgs->target-t); if(length>0) { _updateOffsets(offsets, length, sourceIndex, errorInputLength); /* * if a converter handles offsets and updates the offsets * pointer at the end, then pArgs->offset should not change * here; * however, some converters do not handle offsets at all * (sourceIndex<0) or may not update the offsets pointer */ pArgs->offsets=offsets+=length; } if(sourceIndex>=0) { sourceIndex+=(int32_t)(pArgs->source-s); } } if(cnv->preToULength<0) { /* * switch the source to new replay units (cannot occur while replaying) * after offset handling and before end-of-input and callback handling */ if(realSource==NULL) { realSource=pArgs->source; realSourceLimit=pArgs->sourceLimit; realFlush=pArgs->flush; realSourceIndex=sourceIndex; uprv_memcpy(replay, cnv->preToU, -cnv->preToULength); pArgs->source=replay; pArgs->sourceLimit=replay-cnv->preToULength; pArgs->flush=FALSE; if((sourceIndex+=cnv->preToULength)<0) { sourceIndex=-1; } cnv->preToULength=0; } else { /* see implementation note before _fromUnicodeWithCallback() */ U_ASSERT(realSource==NULL); *err=U_INTERNAL_PROGRAM_ERROR; } } /* update pointers */ s=pArgs->source; t=pArgs->target; if(U_SUCCESS(*err)) { if(s<pArgs->sourceLimit) { /* * continue with the conversion loop while there is still input left * (continue converting by breaking out of only the inner loop) */ break; } else if(realSource!=NULL) { /* switch back from replaying to the real source and continue */ pArgs->source=realSource; pArgs->sourceLimit=realSourceLimit; pArgs->flush=realFlush; sourceIndex=realSourceIndex; realSource=NULL; break; } else if(pArgs->flush && cnv->toULength>0) { /* * the entire input stream is consumed * and there is a partial, truncated input sequence left */ /* inject an error and continue with callback handling */ *err=U_TRUNCATED_CHAR_FOUND; calledCallback=FALSE; /* new error condition */ } else { /* input consumed */ if(pArgs->flush) { /* * return to the conversion loop once more if the flush * flag is set and the conversion function has not * successfully processed the end of the input yet * * (continue converting by breaking out of only the inner loop) */ if(!converterSawEndOfInput) { break; } /* reset the converter without calling the callback function */ _reset(cnv, UCNV_RESET_TO_UNICODE, FALSE); } /* done successfully */ return; } } /* U_FAILURE(*err) */ { UErrorCode e; if( calledCallback || (e=*err)==U_BUFFER_OVERFLOW_ERROR || (e!=U_INVALID_CHAR_FOUND && e!=U_ILLEGAL_CHAR_FOUND && e!=U_TRUNCATED_CHAR_FOUND && e!=U_ILLEGAL_ESCAPE_SEQUENCE && e!=U_UNSUPPORTED_ESCAPE_SEQUENCE) ) { /* * the callback did not or cannot resolve the error: * set output pointers and return * * the check for buffer overflow is redundant but it is * a high-runner case and hopefully documents the intent * well * * if we were replaying, then the replay buffer must be * copied back into the UConverter * and the real arguments must be restored */ if(realSource!=NULL) { int32_t length; U_ASSERT(cnv->preToULength==0); length=(int32_t)(pArgs->sourceLimit-pArgs->source); if(length>0) { uprv_memcpy(cnv->preToU, pArgs->source, length); cnv->preToULength=(int8_t)-length; } pArgs->source=realSource; pArgs->sourceLimit=realSourceLimit; pArgs->flush=realFlush; } return; } } /* copy toUBytes[] to invalidCharBuffer[] */ errorInputLength=cnv->invalidCharLength=cnv->toULength; if(errorInputLength>0) { uprv_memcpy(cnv->invalidCharBuffer, cnv->toUBytes, errorInputLength); } /* set the converter state to deal with the next character */ cnv->toULength=0; /* call the callback function */ if(cnv->toUCallbackReason==UCNV_ILLEGAL && *err==U_INVALID_CHAR_FOUND) { cnv->toUCallbackReason = UCNV_UNASSIGNED; } cnv->fromCharErrorBehaviour(cnv->toUContext, pArgs, cnv->invalidCharBuffer, errorInputLength, cnv->toUCallbackReason, err); cnv->toUCallbackReason = UCNV_ILLEGAL; /* reset to default value */ /* * loop back to the offset handling * * this flag will indicate after offset handling * that a callback was called; * if the callback did not resolve the error, then we return */ calledCallback=TRUE; } } } /* * Output the toUnicode overflow buffer. * Call this function if(cnv->UCharErrorBufferLength>0). * @return TRUE if overflow */ static UBool ucnv_outputOverflowToUnicode(UConverter *cnv, UChar **target, const UChar *targetLimit, int32_t **pOffsets, UErrorCode *err) { int32_t *offsets; UChar *overflow, *t; int32_t i, length; t=*target; if(pOffsets!=NULL) { offsets=*pOffsets; } else { offsets=NULL; } overflow=cnv->UCharErrorBuffer; length=cnv->UCharErrorBufferLength; i=0; while(i<length) { if(t==targetLimit) { /* the overflow buffer contains too much, keep the rest */ int32_t j=0; do { overflow[j++]=overflow[i++]; } while(i<length); cnv->UCharErrorBufferLength=(int8_t)j; *target=t; if(offsets!=NULL) { *pOffsets=offsets; } *err=U_BUFFER_OVERFLOW_ERROR; return TRUE; } /* copy the overflow contents to the target */ *t++=overflow[i++]; if(offsets!=NULL) { *offsets++=-1; /* no source index available for old output */ } } /* the overflow buffer is completely copied to the target */ cnv->UCharErrorBufferLength=0; *target=t; if(offsets!=NULL) { *pOffsets=offsets; } return FALSE; } U_CAPI void U_EXPORT2 ucnv_toUnicode(UConverter *cnv, UChar **target, const UChar *targetLimit, const char **source, const char *sourceLimit, int32_t *offsets, UBool flush, UErrorCode *err) { UConverterToUnicodeArgs args; const char *s; UChar *t; /* check parameters */ if(err==NULL || U_FAILURE(*err)) { return; } if(cnv==NULL || target==NULL || source==NULL) { *err=U_ILLEGAL_ARGUMENT_ERROR; return; } s=*source; t=*target; if ((const void *)U_MAX_PTR(targetLimit) == (const void *)targetLimit) { /* Prevent code from going into an infinite loop in case we do hit this limit. The limit pointer is expected to be on a UChar * boundary. This also prevents the next argument check from failing. */ targetLimit = (const UChar *)(((const char *)targetLimit) - 1); } /* * All these conditions should never happen. * * 1) Make sure that the limits are >= to the address source or target * * 2) Make sure that the buffer sizes do not exceed the number range for * int32_t because some functions use the size (in units or bytes) * rather than comparing pointers, and because offsets are int32_t values. * * size_t is guaranteed to be unsigned and large enough for the job. * * Return with an error instead of adjusting the limits because we would * not be able to maintain the semantics that either the source must be * consumed or the target filled (unless an error occurs). * An adjustment would be sourceLimit=t+0x7fffffff; for example. * * 3) Make sure that the user didn't incorrectly cast a UChar * pointer * to a char * pointer and provide an incomplete UChar code unit. */ if (sourceLimit<s || targetLimit<t || ((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s) || ((size_t)(targetLimit-t)>(size_t)0x3fffffff && targetLimit>t) || (((const char *)targetLimit-(const char *)t) & 1) != 0 ) { *err=U_ILLEGAL_ARGUMENT_ERROR; return; } /* output the target overflow buffer */ if( cnv->UCharErrorBufferLength>0 && ucnv_outputOverflowToUnicode(cnv, target, targetLimit, &offsets, err) ) { /* U_BUFFER_OVERFLOW_ERROR */ return; } /* *target may have moved, therefore stop using t */ if(!flush && s==sourceLimit && cnv->preToULength>=0) { /* the overflow buffer is emptied and there is no new input: we are done */ return; } /* * Do not simply return with a buffer overflow error if * !flush && t==targetLimit * because it is possible that the source will not generate any output. * For example, the skip callback may be called; * it does not output anything. */ /* prepare the converter arguments */ args.converter=cnv; args.flush=flush; args.offsets=offsets; args.source=s; args.sourceLimit=sourceLimit; args.target=*target; args.targetLimit=targetLimit; args.size=sizeof(args); _toUnicodeWithCallback(&args, err); *source=args.source; *target=args.target; } /* ucnv_to/fromUChars() ----------------------------------------------------- */ U_CAPI int32_t U_EXPORT2 ucnv_fromUChars(UConverter *cnv, char *dest, int32_t destCapacity, const UChar *src, int32_t srcLength, UErrorCode *pErrorCode) { const UChar *srcLimit; char *originalDest, *destLimit; int32_t destLength; /* check arguments */ if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return 0; } if( cnv==NULL || destCapacity<0 || (destCapacity>0 && dest==NULL) || srcLength<-1 || (srcLength!=0 && src==NULL) ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return 0; } /* initialize */ ucnv_resetFromUnicode(cnv); originalDest=dest; if(srcLength==-1) { srcLength=u_strlen(src); } if(srcLength>0) { srcLimit=src+srcLength; destLimit=dest+destCapacity; /* pin the destination limit to U_MAX_PTR; NULL check is for OS/400 */ if(destLimit<dest || (destLimit==NULL && dest!=NULL)) { destLimit=(char *)U_MAX_PTR(dest); } /* perform the conversion */ ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, TRUE, pErrorCode); destLength=(int32_t)(dest-originalDest); /* if an overflow occurs, then get the preflighting length */ if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) { char buffer[1024]; destLimit=buffer+sizeof(buffer); do { dest=buffer; *pErrorCode=U_ZERO_ERROR; ucnv_fromUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, TRUE, pErrorCode); destLength+=(int32_t)(dest-buffer); } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR); } } else { destLength=0; } return u_terminateChars(originalDest, destCapacity, destLength, pErrorCode); } U_CAPI int32_t U_EXPORT2 ucnv_toUChars(UConverter *cnv, UChar *dest, int32_t destCapacity, const char *src, int32_t srcLength, UErrorCode *pErrorCode) { const char *srcLimit; UChar *originalDest, *destLimit; int32_t destLength; /* check arguments */ if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return 0; } if( cnv==NULL || destCapacity<0 || (destCapacity>0 && dest==NULL) || srcLength<-1 || (srcLength!=0 && src==NULL)) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return 0; } /* initialize */ ucnv_resetToUnicode(cnv); originalDest=dest; if(srcLength==-1) { srcLength=(int32_t)uprv_strlen(src); } if(srcLength>0) { srcLimit=src+srcLength; destLimit=dest+destCapacity; /* pin the destination limit to U_MAX_PTR; NULL check is for OS/400 */ if(destLimit<dest || (destLimit==NULL && dest!=NULL)) { destLimit=(UChar *)U_MAX_PTR(dest); } /* perform the conversion */ ucnv_toUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, TRUE, pErrorCode); destLength=(int32_t)(dest-originalDest); /* if an overflow occurs, then get the preflighting length */ if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) { UChar buffer[1024]; destLimit=buffer+sizeof(buffer)/U_SIZEOF_UCHAR; do { dest=buffer; *pErrorCode=U_ZERO_ERROR; ucnv_toUnicode(cnv, &dest, destLimit, &src, srcLimit, 0, TRUE, pErrorCode); destLength+=(int32_t)(dest-buffer); } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR); } } else { destLength=0; } return u_terminateUChars(originalDest, destCapacity, destLength, pErrorCode); } /* ucnv_getNextUChar() ------------------------------------------------------ */ U_CAPI UChar32 U_EXPORT2 ucnv_getNextUChar(UConverter *cnv, const char **source, const char *sourceLimit, UErrorCode *err) { UConverterToUnicodeArgs args; UChar buffer[U16_MAX_LENGTH]; const char *s; UChar32 c; int32_t i, length; /* check parameters */ if(err==NULL || U_FAILURE(*err)) { return 0xffff; } if(cnv==NULL || source==NULL) { *err=U_ILLEGAL_ARGUMENT_ERROR; return 0xffff; } s=*source; if(sourceLimit<s) { *err=U_ILLEGAL_ARGUMENT_ERROR; return 0xffff; } /* * Make sure that the buffer sizes do not exceed the number range for * int32_t because some functions use the size (in units or bytes) * rather than comparing pointers, and because offsets are int32_t values. * * size_t is guaranteed to be unsigned and large enough for the job. * * Return with an error instead of adjusting the limits because we would * not be able to maintain the semantics that either the source must be * consumed or the target filled (unless an error occurs). * An adjustment would be sourceLimit=t+0x7fffffff; for example. */ if(((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s)) { *err=U_ILLEGAL_ARGUMENT_ERROR; return 0xffff; } c=U_SENTINEL; /* flush the target overflow buffer */ if(cnv->UCharErrorBufferLength>0) { UChar *overflow; overflow=cnv->UCharErrorBuffer; i=0; length=cnv->UCharErrorBufferLength; U16_NEXT(overflow, i, length, c); /* move the remaining overflow contents up to the beginning */ if((cnv->UCharErrorBufferLength=(int8_t)(length-i))>0) { uprv_memmove(cnv->UCharErrorBuffer, cnv->UCharErrorBuffer+i, cnv->UCharErrorBufferLength*U_SIZEOF_UCHAR); } if(!U16_IS_LEAD(c) || i<length) { return c; } /* * Continue if the overflow buffer contained only a lead surrogate, * in case the converter outputs single surrogates from complete * input sequences. */ } /* * flush==TRUE is implied for ucnv_getNextUChar() * * do not simply return even if s==sourceLimit because the converter may * not have seen flush==TRUE before */ /* prepare the converter arguments */ args.converter=cnv; args.flush=TRUE; args.offsets=NULL; args.source=s; args.sourceLimit=sourceLimit; args.target=buffer; args.targetLimit=buffer+1; args.size=sizeof(args); if(c<0) { /* * call the native getNextUChar() implementation if we are * at a character boundary (toULength==0) * * unlike with _toUnicode(), getNextUChar() implementations must set * U_TRUNCATED_CHAR_FOUND for truncated input, * in addition to setting toULength/toUBytes[] */ if(cnv->toULength==0 && cnv->sharedData->impl->getNextUChar!=NULL) { c=cnv->sharedData->impl->getNextUChar(&args, err); *source=s=args.source; if(*err==U_INDEX_OUTOFBOUNDS_ERROR) { /* reset the converter without calling the callback function */ _reset(cnv, UCNV_RESET_TO_UNICODE, FALSE); return 0xffff; /* no output */ } else if(U_SUCCESS(*err) && c>=0) { return c; /* * else fall through to use _toUnicode() because * UCNV_GET_NEXT_UCHAR_USE_TO_U: the native function did not want to handle it after all * U_FAILURE: call _toUnicode() for callback handling (do not output c) */ } } /* convert to one UChar in buffer[0], or handle getNextUChar() errors */ _toUnicodeWithCallback(&args, err); if(*err==U_BUFFER_OVERFLOW_ERROR) { *err=U_ZERO_ERROR; } i=0; length=(int32_t)(args.target-buffer); } else { /* write the lead surrogate from the overflow buffer */ buffer[0]=(UChar)c; args.target=buffer+1; i=0; length=1; } /* buffer contents starts at i and ends before length */ if(U_FAILURE(*err)) { c=0xffff; /* no output */ } else if(length==0) { /* no input or only state changes */ *err=U_INDEX_OUTOFBOUNDS_ERROR; /* no need to reset explicitly because _toUnicodeWithCallback() did it */ c=0xffff; /* no output */ } else { c=buffer[0]; i=1; if(!U16_IS_LEAD(c)) { /* consume c=buffer[0], done */ } else { /* got a lead surrogate, see if a trail surrogate follows */ UChar c2; if(cnv->UCharErrorBufferLength>0) { /* got overflow output from the conversion */ if(U16_IS_TRAIL(c2=cnv->UCharErrorBuffer[0])) { /* got a trail surrogate, too */ c=U16_GET_SUPPLEMENTARY(c, c2); /* move the remaining overflow contents up to the beginning */ if((--cnv->UCharErrorBufferLength)>0) { uprv_memmove(cnv->UCharErrorBuffer, cnv->UCharErrorBuffer+1, cnv->UCharErrorBufferLength*U_SIZEOF_UCHAR); } } else { /* c is an unpaired lead surrogate, just return it */ } } else if(args.source<sourceLimit) { /* convert once more, to buffer[1] */ args.targetLimit=buffer+2; _toUnicodeWithCallback(&args, err); if(*err==U_BUFFER_OVERFLOW_ERROR) { *err=U_ZERO_ERROR; } length=(int32_t)(args.target-buffer); if(U_SUCCESS(*err) && length==2 && U16_IS_TRAIL(c2=buffer[1])) { /* got a trail surrogate, too */ c=U16_GET_SUPPLEMENTARY(c, c2); i=2; } } } } /* * move leftover output from buffer[i..length[ * into the beginning of the overflow buffer */ if(i<length) { /* move further overflow back */ int32_t delta=length-i; if((length=cnv->UCharErrorBufferLength)>0) { uprv_memmove(cnv->UCharErrorBuffer+delta, cnv->UCharErrorBuffer, length*U_SIZEOF_UCHAR); } cnv->UCharErrorBufferLength=(int8_t)(length+delta); cnv->UCharErrorBuffer[0]=buffer[i++]; if(delta>1) { cnv->UCharErrorBuffer[1]=buffer[i]; } } *source=args.source; return c; } /* ucnv_convert() and siblings ---------------------------------------------- */ U_CAPI void U_EXPORT2 ucnv_convertEx(UConverter *targetCnv, UConverter *sourceCnv, char **target, const char *targetLimit, const char **source, const char *sourceLimit, UChar *pivotStart, UChar **pivotSource, UChar **pivotTarget, const UChar *pivotLimit, UBool reset, UBool flush, UErrorCode *pErrorCode) { UChar pivotBuffer[CHUNK_SIZE]; const UChar *myPivotSource; UChar *myPivotTarget; const char *s; char *t; UConverterToUnicodeArgs toUArgs; UConverterFromUnicodeArgs fromUArgs; UConverterConvert convert; /* error checking */ if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return; } if( targetCnv==NULL || sourceCnv==NULL || source==NULL || *source==NULL || target==NULL || *target==NULL || targetLimit==NULL ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } s=*source; t=*target; if((sourceLimit!=NULL && sourceLimit<s) || targetLimit<t) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } /* * Make sure that the buffer sizes do not exceed the number range for * int32_t. See ucnv_toUnicode() for a more detailed comment. */ if( (sourceLimit!=NULL && ((size_t)(sourceLimit-s)>(size_t)0x7fffffff && sourceLimit>s)) || ((size_t)(targetLimit-t)>(size_t)0x7fffffff && targetLimit>t) ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } if(pivotStart==NULL) { if(!flush) { /* streaming conversion requires an explicit pivot buffer */ *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } /* use the stack pivot buffer */ myPivotSource=myPivotTarget=pivotStart=pivotBuffer; pivotSource=(UChar **)&myPivotSource; pivotTarget=&myPivotTarget; pivotLimit=pivotBuffer+CHUNK_SIZE; } else if( pivotStart>=pivotLimit || pivotSource==NULL || *pivotSource==NULL || pivotTarget==NULL || *pivotTarget==NULL || pivotLimit==NULL ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } if(sourceLimit==NULL) { /* get limit of single-byte-NUL-terminated source string */ sourceLimit=uprv_strchr(*source, 0); } if(reset) { ucnv_resetToUnicode(sourceCnv); ucnv_resetFromUnicode(targetCnv); *pivotSource=*pivotTarget=pivotStart; } else if(targetCnv->charErrorBufferLength>0) { /* output the targetCnv overflow buffer */ if(ucnv_outputOverflowFromUnicode(targetCnv, target, targetLimit, NULL, pErrorCode)) { /* U_BUFFER_OVERFLOW_ERROR */ return; } /* *target has moved, therefore stop using t */ if( !flush && targetCnv->preFromULength>=0 && *pivotSource==*pivotTarget && sourceCnv->UCharErrorBufferLength==0 && sourceCnv->preToULength>=0 && s==sourceLimit ) { /* the fromUnicode overflow buffer is emptied and there is no new input: we are done */ return; } } /* Is direct-UTF-8 conversion available? */ if( sourceCnv->sharedData->staticData->conversionType==UCNV_UTF8 && targetCnv->sharedData->impl->fromUTF8!=NULL ) { convert=targetCnv->sharedData->impl->fromUTF8; } else if( targetCnv->sharedData->staticData->conversionType==UCNV_UTF8 && sourceCnv->sharedData->impl->toUTF8!=NULL ) { convert=sourceCnv->sharedData->impl->toUTF8; } else { convert=NULL; } /* * If direct-UTF-8 conversion is available, then we use a smaller * pivot buffer for error handling and partial matches * so that we quickly return to direct conversion. * * 32 is large enough for UCNV_EXT_MAX_UCHARS and UCNV_ERROR_BUFFER_LENGTH. * * We could reduce the pivot buffer size further, at the cost of * buffer overflows from callbacks. * The pivot buffer should not be smaller than the maximum number of * fromUnicode extension table input UChars * (for m:n conversion, see * targetCnv->sharedData->mbcs.extIndexes[UCNV_EXT_COUNT_UCHARS]) * or 2 for surrogate pairs. * * Too small a buffer can cause thrashing between pivoting and direct * conversion, with function call overhead outweighing the benefits * of direct conversion. */ if(convert!=NULL && (pivotLimit-pivotStart)>32) { pivotLimit=pivotStart+32; } /* prepare the converter arguments */ fromUArgs.converter=targetCnv; fromUArgs.flush=FALSE; fromUArgs.offsets=NULL; fromUArgs.target=*target; fromUArgs.targetLimit=targetLimit; fromUArgs.size=sizeof(fromUArgs); toUArgs.converter=sourceCnv; toUArgs.flush=flush; toUArgs.offsets=NULL; toUArgs.source=s; toUArgs.sourceLimit=sourceLimit; toUArgs.targetLimit=pivotLimit; toUArgs.size=sizeof(toUArgs); /* * TODO: Consider separating this function into two functions, * extracting exactly the conversion loop, * for readability and to reduce the set of visible variables. * * Otherwise stop using s and t from here on. */ s=t=NULL; /* * conversion loop * * The sequence of steps in the loop may appear backward, * but the principle is simple: * In the chain of * source - sourceCnv overflow - pivot - targetCnv overflow - target * empty out later buffers before refilling them from earlier ones. * * The targetCnv overflow buffer is flushed out only once before the loop. */ for(;;) { /* * if(pivot not empty or error or replay or flush fromUnicode) { * fromUnicode(pivot -> target); * } * * For pivoting conversion; and for direct conversion for * error callback handling and flushing the replay buffer. */ if( *pivotSource<*pivotTarget || U_FAILURE(*pErrorCode) || targetCnv->preFromULength<0 || fromUArgs.flush ) { fromUArgs.source=*pivotSource; fromUArgs.sourceLimit=*pivotTarget; _fromUnicodeWithCallback(&fromUArgs, pErrorCode); if(U_FAILURE(*pErrorCode)) { /* target overflow, or conversion error */ *pivotSource=(UChar *)fromUArgs.source; break; } /* * _fromUnicodeWithCallback() must have consumed the pivot contents * (*pivotSource==*pivotTarget) since it returned with U_SUCCESS() */ } /* The pivot buffer is empty; reset it so we start at pivotStart. */ *pivotSource=*pivotTarget=pivotStart; /* * if(sourceCnv overflow buffer not empty) { * move(sourceCnv overflow buffer -> pivot); * continue; * } */ /* output the sourceCnv overflow buffer */ if(sourceCnv->UCharErrorBufferLength>0) { if(ucnv_outputOverflowToUnicode(sourceCnv, pivotTarget, pivotLimit, NULL, pErrorCode)) { /* U_BUFFER_OVERFLOW_ERROR */ *pErrorCode=U_ZERO_ERROR; } continue; } /* * check for end of input and break if done * * Checking both flush and fromUArgs.flush ensures that the converters * have been called with the flush flag set if the ucnv_convertEx() * caller set it. */ if( toUArgs.source==sourceLimit && sourceCnv->preToULength>=0 && sourceCnv->toULength==0 && (!flush || fromUArgs.flush) ) { /* done successfully */ break; } /* * use direct conversion if available * but not if continuing a partial match * or flushing the toUnicode replay buffer */ if(convert!=NULL && targetCnv->preFromUFirstCP<0 && sourceCnv->preToULength==0) { if(*pErrorCode==U_USING_DEFAULT_WARNING) { /* remove a warning that may be set by this function */ *pErrorCode=U_ZERO_ERROR; } convert(&fromUArgs, &toUArgs, pErrorCode); if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) { break; } else if(U_FAILURE(*pErrorCode)) { if(sourceCnv->toULength>0) { /* * Fall through to calling _toUnicodeWithCallback() * for callback handling. * * The pivot buffer will be reset with * *pivotSource=*pivotTarget=pivotStart; * which indicates a toUnicode error to the caller * (*pivotSource==pivotStart shows no pivot UChars consumed). */ } else { /* * Indicate a fromUnicode error to the caller * (*pivotSource>pivotStart shows some pivot UChars consumed). */ *pivotSource=*pivotTarget=pivotStart+1; /* * Loop around to calling _fromUnicodeWithCallbacks() * for callback handling. */ continue; } } else if(*pErrorCode==U_USING_DEFAULT_WARNING) { /* * No error, but the implementation requested to temporarily * fall back to pivoting. */ *pErrorCode=U_ZERO_ERROR; /* * The following else branches are almost identical to the end-of-input * handling in _toUnicodeWithCallback(). * Avoid calling it just for the end of input. */ } else if(flush && sourceCnv->toULength>0) { /* flush==toUArgs.flush */ /* * the entire input stream is consumed * and there is a partial, truncated input sequence left */ /* inject an error and continue with callback handling */ *pErrorCode=U_TRUNCATED_CHAR_FOUND; } else { /* input consumed */ if(flush) { /* reset the converters without calling the callback functions */ _reset(sourceCnv, UCNV_RESET_TO_UNICODE, FALSE); _reset(targetCnv, UCNV_RESET_FROM_UNICODE, FALSE); } /* done successfully */ break; } } /* * toUnicode(source -> pivot); * * For pivoting conversion; and for direct conversion for * error callback handling, continuing partial matches * and flushing the replay buffer. * * The pivot buffer is empty and reset. */ toUArgs.target=pivotStart; /* ==*pivotTarget */ /* toUArgs.targetLimit=pivotLimit; already set before the loop */ _toUnicodeWithCallback(&toUArgs, pErrorCode); *pivotTarget=toUArgs.target; if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) { /* pivot overflow: continue with the conversion loop */ *pErrorCode=U_ZERO_ERROR; } else if(U_FAILURE(*pErrorCode) || (!flush && *pivotTarget==pivotStart)) { /* conversion error, or there was nothing left to convert */ break; } /* * else: * _toUnicodeWithCallback() wrote into the pivot buffer, * continue with fromUnicode conversion. * * Set the fromUnicode flush flag if we flush and if toUnicode has * processed the end of the input. */ if( flush && toUArgs.source==sourceLimit && sourceCnv->preToULength>=0 && sourceCnv->UCharErrorBufferLength==0 ) { fromUArgs.flush=TRUE; } } /* * The conversion loop is exited when one of the following is true: * - the entire source text has been converted successfully to the target buffer * - a target buffer overflow occurred * - a conversion error occurred */ *source=toUArgs.source; *target=fromUArgs.target; /* terminate the target buffer if possible */ if(flush && U_SUCCESS(*pErrorCode)) { if(*target!=targetLimit) { **target=0; if(*pErrorCode==U_STRING_NOT_TERMINATED_WARNING) { *pErrorCode=U_ZERO_ERROR; } } else { *pErrorCode=U_STRING_NOT_TERMINATED_WARNING; } } } /* internal implementation of ucnv_convert() etc. with preflighting */ static int32_t ucnv_internalConvert(UConverter *outConverter, UConverter *inConverter, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode) { UChar pivotBuffer[CHUNK_SIZE]; UChar *pivot, *pivot2; char *myTarget; const char *sourceLimit; const char *targetLimit; int32_t targetLength=0; /* set up */ if(sourceLength<0) { sourceLimit=uprv_strchr(source, 0); } else { sourceLimit=source+sourceLength; } /* if there is no input data, we're done */ if(source==sourceLimit) { return u_terminateChars(target, targetCapacity, 0, pErrorCode); } pivot=pivot2=pivotBuffer; myTarget=target; targetLength=0; if(targetCapacity>0) { /* perform real conversion */ targetLimit=target+targetCapacity; ucnv_convertEx(outConverter, inConverter, &myTarget, targetLimit, &source, sourceLimit, pivotBuffer, &pivot, &pivot2, pivotBuffer+CHUNK_SIZE, FALSE, TRUE, pErrorCode); targetLength=(int32_t)(myTarget-target); } /* * If the output buffer is exhausted (or we are only "preflighting"), we need to stop writing * to it but continue the conversion in order to store in targetCapacity * the number of bytes that was required. */ if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR || targetCapacity==0) { char targetBuffer[CHUNK_SIZE]; targetLimit=targetBuffer+CHUNK_SIZE; do { *pErrorCode=U_ZERO_ERROR; myTarget=targetBuffer; ucnv_convertEx(outConverter, inConverter, &myTarget, targetLimit, &source, sourceLimit, pivotBuffer, &pivot, &pivot2, pivotBuffer+CHUNK_SIZE, FALSE, TRUE, pErrorCode); targetLength+=(int32_t)(myTarget-targetBuffer); } while(*pErrorCode==U_BUFFER_OVERFLOW_ERROR); /* done with preflighting, set warnings and errors as appropriate */ return u_terminateChars(target, targetCapacity, targetLength, pErrorCode); } /* no need to call u_terminateChars() because ucnv_convertEx() took care of that */ return targetLength; } U_CAPI int32_t U_EXPORT2 ucnv_convert(const char *toConverterName, const char *fromConverterName, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode) { UConverter in, out; /* stack-allocated */ UConverter *inConverter, *outConverter; int32_t targetLength; if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return 0; } if( source==NULL || sourceLength<-1 || targetCapacity<0 || (targetCapacity>0 && target==NULL) ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return 0; } /* if there is no input data, we're done */ if(sourceLength==0 || (sourceLength<0 && *source==0)) { return u_terminateChars(target, targetCapacity, 0, pErrorCode); } /* create the converters */ inConverter=ucnv_createConverter(&in, fromConverterName, pErrorCode); if(U_FAILURE(*pErrorCode)) { return 0; } outConverter=ucnv_createConverter(&out, toConverterName, pErrorCode); if(U_FAILURE(*pErrorCode)) { ucnv_close(inConverter); return 0; } targetLength=ucnv_internalConvert(outConverter, inConverter, target, targetCapacity, source, sourceLength, pErrorCode); ucnv_close(inConverter); ucnv_close(outConverter); return targetLength; } /* @internal */ static int32_t ucnv_convertAlgorithmic(UBool convertToAlgorithmic, UConverterType algorithmicType, UConverter *cnv, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode) { UConverter algoConverterStatic; /* stack-allocated */ UConverter *algoConverter, *to, *from; int32_t targetLength; if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) { return 0; } if( cnv==NULL || source==NULL || sourceLength<-1 || targetCapacity<0 || (targetCapacity>0 && target==NULL) ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return 0; } /* if there is no input data, we're done */ if(sourceLength==0 || (sourceLength<0 && *source==0)) { return u_terminateChars(target, targetCapacity, 0, pErrorCode); } /* create the algorithmic converter */ algoConverter=ucnv_createAlgorithmicConverter(&algoConverterStatic, algorithmicType, "", 0, pErrorCode); if(U_FAILURE(*pErrorCode)) { return 0; } /* reset the other converter */ if(convertToAlgorithmic) { /* cnv->Unicode->algo */ ucnv_resetToUnicode(cnv); to=algoConverter; from=cnv; } else { /* algo->Unicode->cnv */ ucnv_resetFromUnicode(cnv); from=algoConverter; to=cnv; } targetLength=ucnv_internalConvert(to, from, target, targetCapacity, source, sourceLength, pErrorCode); ucnv_close(algoConverter); return targetLength; } U_CAPI int32_t U_EXPORT2 ucnv_toAlgorithmic(UConverterType algorithmicType, UConverter *cnv, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode) { return ucnv_convertAlgorithmic(TRUE, algorithmicType, cnv, target, targetCapacity, source, sourceLength, pErrorCode); } U_CAPI int32_t U_EXPORT2 ucnv_fromAlgorithmic(UConverter *cnv, UConverterType algorithmicType, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode) { return ucnv_convertAlgorithmic(FALSE, algorithmicType, cnv, target, targetCapacity, source, sourceLength, pErrorCode); } U_CAPI UConverterType U_EXPORT2 ucnv_getType(const UConverter* converter) { int8_t type = converter->sharedData->staticData->conversionType; #if !UCONFIG_NO_LEGACY_CONVERSION if(type == UCNV_MBCS) { return ucnv_MBCSGetType(converter); } #endif return (UConverterType)type; } U_CAPI void U_EXPORT2 ucnv_getStarters(const UConverter* converter, UBool starters[256], UErrorCode* err) { if (err == NULL || U_FAILURE(*err)) { return; } if(converter->sharedData->impl->getStarters != NULL) { converter->sharedData->impl->getStarters(converter, starters, err); } else { *err = U_ILLEGAL_ARGUMENT_ERROR; } } static const UAmbiguousConverter *ucnv_getAmbiguous(const UConverter *cnv) { UErrorCode errorCode; const char *name; int32_t i; if(cnv==NULL) { return NULL; } errorCode=U_ZERO_ERROR; name=ucnv_getName(cnv, &errorCode); if(U_FAILURE(errorCode)) { return NULL; } for(i=0; i<(int32_t)(sizeof(ambiguousConverters)/sizeof(UAmbiguousConverter)); ++i) { if(0==uprv_strcmp(name, ambiguousConverters[i].name)) { return ambiguousConverters+i; } } return NULL; } U_CAPI void U_EXPORT2 ucnv_fixFileSeparator(const UConverter *cnv, UChar* source, int32_t sourceLength) { const UAmbiguousConverter *a; int32_t i; UChar variant5c; if(cnv==NULL || source==NULL || sourceLength<=0 || (a=ucnv_getAmbiguous(cnv))==NULL) { return; } variant5c=a->variant5c; for(i=0; i<sourceLength; ++i) { if(source[i]==variant5c) { source[i]=0x5c; } } } U_CAPI UBool U_EXPORT2 ucnv_isAmbiguous(const UConverter *cnv) { return (UBool)(ucnv_getAmbiguous(cnv)!=NULL); } U_CAPI void U_EXPORT2 ucnv_setFallback(UConverter *cnv, UBool usesFallback) { cnv->useFallback = usesFallback; } U_CAPI UBool U_EXPORT2 ucnv_usesFallback(const UConverter *cnv) { return cnv->useFallback; } U_CAPI void U_EXPORT2 ucnv_getInvalidChars (const UConverter * converter, char *errBytes, int8_t * len, UErrorCode * err) { if (err == NULL || U_FAILURE(*err)) { return; } if (len == NULL || errBytes == NULL || converter == NULL) { *err = U_ILLEGAL_ARGUMENT_ERROR; return; } if (*len < converter->invalidCharLength) { *err = U_INDEX_OUTOFBOUNDS_ERROR; return; } if ((*len = converter->invalidCharLength) > 0) { uprv_memcpy (errBytes, converter->invalidCharBuffer, *len); } } U_CAPI void U_EXPORT2 ucnv_getInvalidUChars (const UConverter * converter, UChar *errChars, int8_t * len, UErrorCode * err) { if (err == NULL || U_FAILURE(*err)) { return; } if (len == NULL || errChars == NULL || converter == NULL) { *err = U_ILLEGAL_ARGUMENT_ERROR; return; } if (*len < converter->invalidUCharLength) { *err = U_INDEX_OUTOFBOUNDS_ERROR; return; } if ((*len = converter->invalidUCharLength) > 0) { uprv_memcpy (errChars, converter->invalidUCharBuffer, sizeof(UChar) * (*len)); } } #define SIG_MAX_LEN 5 U_CAPI const char* U_EXPORT2 ucnv_detectUnicodeSignature( const char* source, int32_t sourceLength, int32_t* signatureLength, UErrorCode* pErrorCode) { int32_t dummy; /* initial 0xa5 bytes: make sure that if we read <SIG_MAX_LEN * bytes we don't misdetect something */ char start[SIG_MAX_LEN]={ '\xa5', '\xa5', '\xa5', '\xa5', '\xa5' }; int i = 0; if((pErrorCode==NULL) || U_FAILURE(*pErrorCode)){ return NULL; } if(source == NULL || sourceLength < -1){ *pErrorCode = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } if(signatureLength == NULL) { signatureLength = &dummy; } if(sourceLength==-1){ sourceLength=(int32_t)uprv_strlen(source); } while(i<sourceLength&& i<SIG_MAX_LEN){ start[i]=source[i]; i++; } if(start[0] == '\xFE' && start[1] == '\xFF') { *signatureLength=2; return "UTF-16BE"; } else if(start[0] == '\xFF' && start[1] == '\xFE') { if(start[2] == '\x00' && start[3] =='\x00') { *signatureLength=4; return "UTF-32LE"; } else { *signatureLength=2; return "UTF-16LE"; } } else if(start[0] == '\xEF' && start[1] == '\xBB' && start[2] == '\xBF') { *signatureLength=3; return "UTF-8"; } else if(start[0] == '\x00' && start[1] == '\x00' && start[2] == '\xFE' && start[3]=='\xFF') { *signatureLength=4; return "UTF-32BE"; } else if(start[0] == '\x0E' && start[1] == '\xFE' && start[2] == '\xFF') { *signatureLength=3; return "SCSU"; } else if(start[0] == '\xFB' && start[1] == '\xEE' && start[2] == '\x28') { *signatureLength=3; return "BOCU-1"; } else if(start[0] == '\x2B' && start[1] == '\x2F' && start[2] == '\x76') { /* * UTF-7: Initial U+FEFF is encoded as +/v8 or +/v9 or +/v+ or +/v/ * depending on the second UTF-16 code unit. * Detect the entire, closed Unicode mode sequence +/v8- for only U+FEFF * if it occurs. * * So far we have +/v */ if(start[3] == '\x38' && start[4] == '\x2D') { /* 5 bytes +/v8- */ *signatureLength=5; return "UTF-7"; } else if(start[3] == '\x38' || start[3] == '\x39' || start[3] == '\x2B' || start[3] == '\x2F') { /* 4 bytes +/v8 or +/v9 or +/v+ or +/v/ */ *signatureLength=4; return "UTF-7"; } }else if(start[0]=='\xDD' && start[1]== '\x73'&& start[2]=='\x66' && start[3]=='\x73'){ *signatureLength=4; return "UTF-EBCDIC"; } /* no known Unicode signature byte sequence recognized */ *signatureLength=0; return NULL; } U_CAPI int32_t U_EXPORT2 ucnv_fromUCountPending(const UConverter* cnv, UErrorCode* status) { if(status == NULL || U_FAILURE(*status)){ return -1; } if(cnv == NULL){ *status = U_ILLEGAL_ARGUMENT_ERROR; return -1; } if(cnv->preFromUFirstCP >= 0){ return U16_LENGTH(cnv->preFromUFirstCP)+cnv->preFromULength ; }else if(cnv->preFromULength < 0){ return -cnv->preFromULength ; }else if(cnv->fromUChar32 > 0){ return 1; } return 0; } U_CAPI int32_t U_EXPORT2 ucnv_toUCountPending(const UConverter* cnv, UErrorCode* status){ if(status == NULL || U_FAILURE(*status)){ return -1; } if(cnv == NULL){ *status = U_ILLEGAL_ARGUMENT_ERROR; return -1; } if(cnv->preToULength > 0){ return cnv->preToULength ; }else if(cnv->preToULength < 0){ return -cnv->preToULength; }else if(cnv->toULength > 0){ return cnv->toULength; } return 0; } U_CAPI UBool U_EXPORT2 ucnv_isFixedWidth(UConverter *cnv, UErrorCode *status){ if (U_FAILURE(*status)) { return FALSE; } if (cnv == NULL) { *status = U_ILLEGAL_ARGUMENT_ERROR; return FALSE; } switch (ucnv_getType(cnv)) { case UCNV_SBCS: case UCNV_DBCS: case UCNV_UTF32_BigEndian: case UCNV_UTF32_LittleEndian: case UCNV_UTF32: case UCNV_US_ASCII: return TRUE; default: return FALSE; } } #endif /* * Hey, Emacs, please set the following: * * Local Variables: * indent-tabs-mode: nil * End: * */
mit
mediapiglet/piglet
node_modules/exec-sync/node_modules/ffi/deps/pthreads-win32/tests/sizes.c
206
1694
#define _WIN32_WINNT 0x400 #include "test.h" #include "../implement.h" int main() { printf("Sizes of pthreads-win32 structs\n"); printf("-------------------------------\n"); printf("%30s %4d\n", "pthread_t", (int)sizeof(pthread_t)); printf("%30s %4d\n", "ptw32_thread_t", (int)sizeof(ptw32_thread_t)); printf("%30s %4d\n", "pthread_attr_t_", (int)sizeof(struct pthread_attr_t_)); printf("%30s %4d\n", "sem_t_", (int)sizeof(struct sem_t_)); printf("%30s %4d\n", "pthread_mutex_t_", (int)sizeof(struct pthread_mutex_t_)); printf("%30s %4d\n", "pthread_mutexattr_t_", (int)sizeof(struct pthread_mutexattr_t_)); printf("%30s %4d\n", "pthread_spinlock_t_", (int)sizeof(struct pthread_spinlock_t_)); printf("%30s %4d\n", "pthread_barrier_t_", (int)sizeof(struct pthread_barrier_t_)); printf("%30s %4d\n", "pthread_barrierattr_t_", (int)sizeof(struct pthread_barrierattr_t_)); printf("%30s %4d\n", "pthread_key_t_", (int)sizeof(struct pthread_key_t_)); printf("%30s %4d\n", "pthread_cond_t_", (int)sizeof(struct pthread_cond_t_)); printf("%30s %4d\n", "pthread_condattr_t_", (int)sizeof(struct pthread_condattr_t_)); printf("%30s %4d\n", "pthread_rwlock_t_", (int)sizeof(struct pthread_rwlock_t_)); printf("%30s %4d\n", "pthread_rwlockattr_t_", (int)sizeof(struct pthread_rwlockattr_t_)); printf("%30s %4d\n", "pthread_once_t_", (int)sizeof(struct pthread_once_t_)); printf("%30s %4d\n", "ptw32_cleanup_t", (int)sizeof(struct ptw32_cleanup_t)); printf("%30s %4d\n", "ptw32_mcs_node_t_", (int)sizeof(struct ptw32_mcs_node_t_)); printf("%30s %4d\n", "sched_param", (int)sizeof(struct sched_param)); printf("-------------------------------\n"); return 0; }
mit
clonecoin/clonecoin
src/qt/addresstablemodel.cpp
1234
12857
#include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "wallet.h" #include "base58.h" #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *wallet, AddressTableModel *parent): wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& item, wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; const std::string& strName = item.second; bool fMine = IsMine(*wallet, address.Get()); cachedAddressTable.append(AddressTableEntry(fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending; switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: AddressTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); editStatus = OK; if(role == Qt::EditRole) { switch(index.column()) { case Label: // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBookName(CBitcoinAddress(rec->address.toStdString()).Get(), value.toString().toStdString()); break; case Address: // Do nothing, if old address == new address if(CBitcoinAddress(rec->address.toStdString()) == CBitcoinAddress(value.toString().toStdString())) { editStatus = NO_CHANGES; return false; } // Refuse to set invalid address, set error status and return false else if(!walletModel->validateAddress(value.toString())) { editStatus = INVALID_ADDRESS; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(CBitcoinAddress(value.toString().toStdString()).Get())) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { { LOCK(wallet->cs_wallet); // Remove old entry wallet->DelAddressBookName(CBitcoinAddress(rec->address.toStdString()).Get()); // Add new entry with new address wallet->SetAddressBookName(CBitcoinAddress(value.toString().toStdString()).Get(), rec->label.toStdString()); } } break; } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, int status) { // Update address book model from Bitcoin core priv->updateEntry(address, label, isMine, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } CPubKey newKey; if(!wallet->GetKeyFromPool(newKey, true)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBookName(CBitcoinAddress(strAddress).Get(), strLabel); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBookName(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); }
mit