repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
QuuxZebula/python-twitter | simplejson/_speedups.c | 136 | 75169 | #include "Python.h"
#include "structmember.h"
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PyInt_FromSsize_t PyInt_FromLong
#define PyInt_AsSsize_t PyInt_AsLong
#endif
#ifndef Py_IS_FINITE
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
#endif
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#define DEFAULT_ENCODING "utf-8"
#define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
#define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
#define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
#define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
static PyTypeObject PyScannerType;
static PyTypeObject PyEncoderType;
typedef struct _PyScannerObject {
PyObject_HEAD
PyObject *encoding;
PyObject *strict;
PyObject *object_hook;
PyObject *parse_float;
PyObject *parse_int;
PyObject *parse_constant;
} PyScannerObject;
static PyMemberDef scanner_members[] = {
{"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
{"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
{"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
{"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
{"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
{"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
{NULL}
};
typedef struct _PyEncoderObject {
PyObject_HEAD
PyObject *markers;
PyObject *defaultfn;
PyObject *encoder;
PyObject *indent;
PyObject *key_separator;
PyObject *item_separator;
PyObject *sort_keys;
PyObject *skipkeys;
int fast_encode;
int allow_nan;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
{"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
{"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
{"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
{"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
{"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
{"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
{"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
{"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
{NULL}
};
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
static PyObject *
ascii_escape_unicode(PyObject *pystr);
static PyObject *
ascii_escape_str(PyObject *pystr);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
void init_speedups(void);
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
scanner_dealloc(PyObject *self);
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
encoder_dealloc(PyObject *self);
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
static PyObject *
_encoded_const(PyObject *const);
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj);
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj);
#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
#define MIN_EXPANSION 6
#ifdef Py_UNICODE_WIDE
#define MAX_EXPANSION (2 * MIN_EXPANSION)
#else
#define MAX_EXPANSION MIN_EXPANSION
#endif
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
{
/* PyObject to Py_ssize_t converter */
*size_ptr = PyInt_AsSsize_t(o);
if (*size_ptr == -1 && PyErr_Occurred());
return 1;
return 0;
}
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
{
/* Py_ssize_t to PyObject converter */
return PyInt_FromSsize_t(*size_ptr);
}
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
{
/* Escape unicode code point c to ASCII escape sequences
in char *output. output must have at least 12 bytes unused to
accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
output[chars++] = '\\';
switch (c) {
case '\\': output[chars++] = (char)c; break;
case '"': output[chars++] = (char)c; break;
case '\b': output[chars++] = 'b'; break;
case '\f': output[chars++] = 'f'; break;
case '\n': output[chars++] = 'n'; break;
case '\r': output[chars++] = 'r'; break;
case '\t': output[chars++] = 't'; break;
default:
#ifdef Py_UNICODE_WIDE
if (c >= 0x10000) {
/* UTF-16 surrogate pair */
Py_UNICODE v = c - 0x10000;
c = 0xd800 | ((v >> 10) & 0x3ff);
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
c = 0xdc00 | (v & 0x3ff);
output[chars++] = '\\';
}
#endif
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
}
return chars;
}
static PyObject *
ascii_escape_unicode(PyObject *pystr)
{
/* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t max_output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
Py_UNICODE *input_unicode;
input_chars = PyUnicode_GET_SIZE(pystr);
input_unicode = PyUnicode_AS_UNICODE(pystr);
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
max_output_size = 2 + (input_chars * MAX_EXPANSION);
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
chars = 0;
output[chars++] = '"';
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = input_unicode[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
if (output_size - chars < (1 + MAX_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
Py_ssize_t new_output_size = output_size * 2;
/* This is an upper bound */
if (new_output_size > max_output_size) {
new_output_size = max_output_size;
}
/* Make sure that the output size changed before resizing */
if (new_output_size != output_size) {
output_size = new_output_size;
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static PyObject *
ascii_escape_str(PyObject *pystr)
{
/* Take a PyString pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
char *input_str;
input_chars = PyString_GET_SIZE(pystr);
input_str = PyString_AS_STRING(pystr);
/* Fast path for a string that's already ASCII */
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (!S_CHAR(c)) {
/* If we have to escape something, scan the string for unicode */
Py_ssize_t j;
for (j = i; j < input_chars; j++) {
c = (Py_UNICODE)(unsigned char)input_str[j];
if (c > 0x7f) {
/* We hit a non-ASCII character, bail to unicode mode */
PyObject *uni;
uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
if (uni == NULL) {
return NULL;
}
rval = ascii_escape_unicode(uni);
Py_DECREF(uni);
return rval;
}
}
break;
}
}
if (i == input_chars) {
/* Input is already ASCII */
output_size = 2 + input_chars;
}
else {
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
}
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
output[0] = '"';
/* We know that everything up to i is ASCII already */
chars = i + 1;
memcpy(&output[1], input_str, i);
for (; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
/* An ASCII char can't possibly expand to a surrogate! */
if (output_size - chars < (1 + MIN_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
output_size *= 2;
if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
output_size = 2 + (input_chars * MIN_EXPANSION);
}
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
{
/* Use the Python function simplejson.decoder.errmsg to raise a nice
looking ValueError exception */
static PyObject *errmsg_fn = NULL;
PyObject *pymsg;
if (errmsg_fn == NULL) {
PyObject *decoder = PyImport_ImportModule("simplejson.decoder");
if (decoder == NULL)
return;
errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
Py_DECREF(decoder);
if (errmsg_fn == NULL)
return;
}
pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
if (pymsg) {
PyErr_SetObject(PyExc_ValueError, pymsg);
Py_DECREF(pymsg);
}
}
static PyObject *
join_list_unicode(PyObject *lst)
{
/* return u''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
join_list_string(PyObject *lst)
{
/* return ''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
PyObject *pyidx;
/*
steal a reference to rval, returns (rval, idx)
*/
if (rval == NULL) {
return NULL;
}
pyidx = PyInt_FromSsize_t(idx);
if (pyidx == NULL) {
Py_DECREF(rval);
return NULL;
}
tpl = PyTuple_New(2);
if (tpl == NULL) {
Py_DECREF(pyidx);
Py_DECREF(rval);
return NULL;
}
PyTuple_SET_ITEM(tpl, 0, rval);
PyTuple_SET_ITEM(tpl, 1, pyidx);
return tpl;
}
static PyObject *
scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyString pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyString (if ASCII-only) or PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyString_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
int has_unicode = 0;
char *buf = PyString_AS_STRING(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = (unsigned char)buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
else if (c > 0x7f) {
has_unicode = 1;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end);
if (strchunk == NULL) {
goto bail;
}
if (has_unicode) {
chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
Py_DECREF(strchunk);
if (chunk == NULL) {
goto bail;
}
}
else {
chunk = strchunk;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
if (c > 0x7f) {
has_unicode = 1;
}
if (has_unicode) {
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
}
else {
char c_char = Py_CHARMASK(c);
chunk = PyString_FromStringAndSize(&c_char, 1);
if (chunk == NULL) {
goto bail;
}
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_string(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
static PyObject *
scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyUnicode pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
chunk = PyUnicode_FromUnicode(&buf[end], next - end);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_DECREF(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
PyDoc_STRVAR(pydoc_scanstring,
"scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
"\n"
"Scan the string s for a JSON string. End is the index of the\n"
"character in s after the quote that started the JSON string.\n"
"Unescapes all valid JSON string escape sequences and raises ValueError\n"
"on attempt to decode an invalid string. If strict is False then literal\n"
"control characters are allowed in the string.\n"
"\n"
"Returns a tuple of the decoded string and the index of the character in s\n"
"after the end quote."
);
static PyObject *
py_scanstring(PyObject* self UNUSED, PyObject *args)
{
PyObject *pystr;
PyObject *rval;
Py_ssize_t end;
Py_ssize_t next_end = -1;
char *encoding = NULL;
int strict = 1;
if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
return NULL;
}
if (encoding == NULL) {
encoding = DEFAULT_ENCODING;
}
if (PyString_Check(pystr)) {
rval = scanstring_str(pystr, end, encoding, strict, &next_end);
}
else if (PyUnicode_Check(pystr)) {
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_end);
}
PyDoc_STRVAR(pydoc_encode_basestring_ascii,
"encode_basestring_ascii(basestring) -> str\n"
"\n"
"Return an ASCII-only JSON representation of a Python string"
);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
{
/* Return an ASCII-only JSON representation of a Python string */
/* METH_O */
if (PyString_Check(pystr)) {
return ascii_escape_str(pystr);
}
else if (PyUnicode_Check(pystr)) {
return ascii_escape_unicode(pystr);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
}
static void
scanner_dealloc(PyObject *self)
{
/* Deallocate scanner object */
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
self->ob_type->tp_free(self);
}
static PyObject *
_parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyString pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
PyObject *val = NULL;
char *encoding = PyString_AS_STRING(s->encoding);
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON data type */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyUnicode pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term and de-tuplefy the (rval, idx) */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON constant from PyString pystr.
constant is the constant string that was found
("NaN", "Infinity", "-Infinity").
idx is the index of the first character of the constant
*next_idx_ptr is a return-by-reference index to the first character after
the constant.
Returns the result of parse_constant
*/
PyObject *cstr;
PyObject *rval;
/* constant is "NaN", "Infinity", or "-Infinity" */
cstr = PyString_InternFromString(constant);
if (cstr == NULL)
return NULL;
/* rval = parse_constant(constant) */
rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
idx += PyString_GET_SIZE(cstr);
Py_DECREF(cstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyString pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
/* save the index of the 'e' or 'E' just in case we need to backtrack */
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyString_FromStringAndSize(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr)));
}
}
else {
/* parse as an int using a fast path if available, otherwise call user defined method */
if (s->parse_int != (PyObject *)&PyInt_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
else {
rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
}
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyUnicode pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyUnicode_FromUnicode(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromString(numstr, NULL);
}
}
else {
/* no fast path for unicode -> int, just call */
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyString pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_str(pystr, idx + 1,
PyString_AS_STRING(s->encoding),
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_str(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyUnicode pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_unicode(pystr, idx + 1,
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_unicode(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to scan_once_{str,unicode} */
PyObject *pystr;
PyObject *rval;
Py_ssize_t idx;
Py_ssize_t next_idx = -1;
static char *kwlist[] = {"string", "idx", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
return NULL;
if (PyString_Check(pystr)) {
rval = scan_once_str(s, pystr, idx, &next_idx);
}
else if (PyUnicode_Check(pystr)) {
rval = scan_once_unicode(s, pystr, idx, &next_idx);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_idx);
}
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Initialize Scanner object */
PyObject *ctx;
static char *kwlist[] = {"context", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
return -1;
s->encoding = NULL;
s->strict = NULL;
s->object_hook = NULL;
s->parse_float = NULL;
s->parse_int = NULL;
s->parse_constant = NULL;
/* PyString_AS_STRING is used on encoding */
s->encoding = PyObject_GetAttrString(ctx, "encoding");
if (s->encoding == Py_None) {
Py_DECREF(Py_None);
s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
}
else if (PyUnicode_Check(s->encoding)) {
PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
Py_DECREF(s->encoding);
s->encoding = tmp;
}
if (s->encoding == NULL || !PyString_Check(s->encoding))
goto bail;
/* All of these will fail "gracefully" so we don't need to verify them */
s->strict = PyObject_GetAttrString(ctx, "strict");
if (s->strict == NULL)
goto bail;
s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
if (s->object_hook == NULL)
goto bail;
s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
if (s->parse_float == NULL)
goto bail;
s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
if (s->parse_int == NULL)
goto bail;
s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
if (s->parse_constant == NULL)
goto bail;
return 0;
bail:
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return -1;
}
PyDoc_STRVAR(scanner_doc, "JSON scanner object");
static
PyTypeObject PyScannerType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Scanner", /* tp_name */
sizeof(PyScannerObject), /* tp_basicsize */
0, /* tp_itemsize */
scanner_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
scanner_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
scanner_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
scanner_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
scanner_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
PyEncoderObject *s;
PyObject *allow_nan;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
s->markers = NULL;
s->defaultfn = NULL;
s->encoder = NULL;
s->indent = NULL;
s->key_separator = NULL;
s->item_separator = NULL;
s->sort_keys = NULL;
s->skipkeys = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
&s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan))
return -1;
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
Py_INCREF(s->encoder);
Py_INCREF(s->indent);
Py_INCREF(s->key_separator);
Py_INCREF(s->item_separator);
Py_INCREF(s->sort_keys);
Py_INCREF(s->skipkeys);
s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
s->allow_nan = PyObject_IsTrue(allow_nan);
return 0;
}
static PyObject *
encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to encode_listencode_obj */
static char *kwlist[] = {"obj", "_current_indent_level", NULL};
PyObject *obj;
PyObject *rval;
Py_ssize_t indent_level;
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
&obj, _convertPyInt_AsSsize_t, &indent_level))
return NULL;
rval = PyList_New(0);
if (rval == NULL)
return NULL;
if (encoder_listencode_obj(s, rval, obj, indent_level)) {
Py_DECREF(rval);
return NULL;
}
return rval;
}
static PyObject *
_encoded_const(PyObject *obj)
{
/* Return the JSON string representation of None, True, False */
if (obj == Py_None) {
static PyObject *s_null = NULL;
if (s_null == NULL) {
s_null = PyString_InternFromString("null");
}
Py_INCREF(s_null);
return s_null;
}
else if (obj == Py_True) {
static PyObject *s_true = NULL;
if (s_true == NULL) {
s_true = PyString_InternFromString("true");
}
Py_INCREF(s_true);
return s_true;
}
else if (obj == Py_False) {
static PyObject *s_false = NULL;
if (s_false == NULL) {
s_false = PyString_InternFromString("false");
}
Py_INCREF(s_false);
return s_false;
}
else {
PyErr_SetString(PyExc_ValueError, "not a const");
return NULL;
}
}
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyString_FromString("Infinity");
}
else if (i < 0) {
return PyString_FromString("-Infinity");
}
else {
return PyString_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a string */
if (s->fast_encode)
return py_encode_basestring_ascii(NULL, obj);
else
return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
}
static int
_steal_list_append(PyObject *lst, PyObject *stolen)
{
/* Append stolen and then decrement its reference count */
int rval = PyList_Append(lst, stolen);
Py_DECREF(stolen);
return rval;
}
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
{
/* Encode Python object obj to a JSON term, rval is a PyList */
PyObject *newobj;
int rv;
if (obj == Py_None || obj == Py_True || obj == Py_False) {
PyObject *cstr = _encoded_const(obj);
if (cstr == NULL)
return -1;
return _steal_list_append(rval, cstr);
}
else if (PyString_Check(obj) || PyUnicode_Check(obj))
{
PyObject *encoded = encoder_encode_string(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyList_Check(obj) || PyTuple_Check(obj)) {
return encoder_listencode_list(s, rval, obj, indent_level);
}
else if (PyDict_Check(obj)) {
return encoder_listencode_dict(s, rval, obj, indent_level);
}
else {
PyObject *ident = NULL;
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(obj);
if (ident == NULL)
return -1;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
Py_DECREF(ident);
return -1;
}
if (PyDict_SetItem(s->markers, ident, obj)) {
Py_DECREF(ident);
return -1;
}
}
newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
if (newobj == NULL) {
Py_XDECREF(ident);
return -1;
}
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
return -1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident)) {
Py_XDECREF(ident);
return -1;
}
Py_XDECREF(ident);
}
return rv;
}
}
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
{
/* Encode Python dict dct a JSON term, rval is a PyList */
static PyObject *open_dict = NULL;
static PyObject *close_dict = NULL;
static PyObject *empty_dict = NULL;
PyObject *kstr = NULL;
PyObject *ident = NULL;
PyObject *key, *value;
Py_ssize_t pos;
int skipkeys;
Py_ssize_t idx;
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
open_dict = PyString_InternFromString("{");
close_dict = PyString_InternFromString("}");
empty_dict = PyString_InternFromString("{}");
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
return -1;
}
if (PyDict_Size(dct) == 0)
return PyList_Append(rval, empty_dict);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(dct);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, dct)) {
goto bail;
}
}
if (PyList_Append(rval, open_dict))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
/* TODO: C speedup not implemented for sort_keys */
pos = 0;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
while (PyDict_Next(dct, &pos, &key, &value)) {
PyObject *encoded;
if (PyString_Check(key) || PyUnicode_Check(key)) {
Py_INCREF(key);
kstr = key;
}
else if (PyFloat_Check(key)) {
kstr = encoder_encode_float(s, key);
if (kstr == NULL)
goto bail;
}
else if (PyInt_Check(key) || PyLong_Check(key)) {
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
}
else if (skipkeys) {
continue;
}
else {
/* TODO: include repr of key */
PyErr_SetString(PyExc_ValueError, "keys must be a string");
goto bail;
}
if (idx) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
encoded = encoder_encode_string(s, kstr);
Py_CLEAR(kstr);
if (encoded == NULL)
goto bail;
if (PyList_Append(rval, encoded)) {
Py_DECREF(encoded);
goto bail;
}
Py_DECREF(encoded);
if (PyList_Append(rval, s->key_separator))
goto bail;
if (encoder_listencode_obj(s, rval, value, indent_level))
goto bail;
idx += 1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_dict))
goto bail;
return 0;
bail:
Py_XDECREF(kstr);
Py_XDECREF(ident);
return -1;
}
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
{
/* Encode Python list seq to a JSON term, rval is a PyList */
static PyObject *open_array = NULL;
static PyObject *close_array = NULL;
static PyObject *empty_array = NULL;
PyObject *ident = NULL;
PyObject *s_fast = NULL;
Py_ssize_t num_items;
PyObject **seq_items;
Py_ssize_t i;
if (open_array == NULL || close_array == NULL || empty_array == NULL) {
open_array = PyString_InternFromString("[");
close_array = PyString_InternFromString("]");
empty_array = PyString_InternFromString("[]");
if (open_array == NULL || close_array == NULL || empty_array == NULL)
return -1;
}
ident = NULL;
s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
if (s_fast == NULL)
return -1;
num_items = PySequence_Fast_GET_SIZE(s_fast);
if (num_items == 0) {
Py_DECREF(s_fast);
return PyList_Append(rval, empty_array);
}
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(seq);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, seq)) {
goto bail;
}
}
seq_items = PySequence_Fast_ITEMS(s_fast);
if (PyList_Append(rval, open_array))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
for (i = 0; i < num_items; i++) {
PyObject *obj = seq_items[i];
if (i) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoder_listencode_obj(s, rval, obj, indent_level))
goto bail;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_array))
goto bail;
Py_DECREF(s_fast);
return 0;
bail:
Py_XDECREF(ident);
Py_DECREF(s_fast);
return -1;
}
static void
encoder_dealloc(PyObject *self)
{
/* Deallocate Encoder */
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_CLEAR(s->markers);
Py_CLEAR(s->defaultfn);
Py_CLEAR(s->encoder);
Py_CLEAR(s->indent);
Py_CLEAR(s->key_separator);
Py_CLEAR(s->item_separator);
Py_CLEAR(s->sort_keys);
Py_CLEAR(s->skipkeys);
self->ob_type->tp_free(self);
}
PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
static
PyTypeObject PyEncoderType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Encoder", /* tp_name */
sizeof(PyEncoderObject), /* tp_basicsize */
0, /* tp_itemsize */
encoder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
encoder_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
encoder_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
encoder_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
encoder_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static PyMethodDef speedups_methods[] = {
{"encode_basestring_ascii",
(PyCFunction)py_encode_basestring_ascii,
METH_O,
pydoc_encode_basestring_ascii},
{"scanstring",
(PyCFunction)py_scanstring,
METH_VARARGS,
pydoc_scanstring},
{NULL, NULL, 0, NULL}
};
PyDoc_STRVAR(module_doc,
"simplejson speedups\n");
void
init_speedups(void)
{
PyObject *m;
PyScannerType.tp_getattro = PyObject_GenericGetAttr;
PyScannerType.tp_setattro = PyObject_GenericSetAttr;
PyScannerType.tp_alloc = PyType_GenericAlloc;
PyScannerType.tp_new = PyType_GenericNew;
PyScannerType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyScannerType) < 0)
return;
PyEncoderType.tp_getattro = PyObject_GenericGetAttr;
PyEncoderType.tp_setattro = PyObject_GenericSetAttr;
PyEncoderType.tp_alloc = PyType_GenericAlloc;
PyEncoderType.tp_new = PyType_GenericNew;
PyEncoderType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyEncoderType) < 0)
return;
m = Py_InitModule3("_speedups", speedups_methods, module_doc);
Py_INCREF((PyObject*)&PyScannerType);
PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
Py_INCREF((PyObject*)&PyEncoderType);
PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
}
| apache-2.0 |
algohary/SlicerExtension_ColiageFilter | CLIModule_ColiageFilter/Eigen/test/array_replicate.cpp | 156 | 2010 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
template<typename MatrixType> void replicate(const MatrixType& m)
{
/* this test covers the following files:
Replicate.cpp
*/
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, Dynamic, Dynamic> MatrixX;
typedef Matrix<Scalar, Dynamic, 1> VectorX;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols);
VectorType v1 = VectorType::Random(rows);
MatrixX x1, x2;
VectorX vx1;
int f1 = internal::random<int>(1,10),
f2 = internal::random<int>(1,10);
x1.resize(rows*f1,cols*f2);
for(int j=0; j<f2; j++)
for(int i=0; i<f1; i++)
x1.block(i*rows,j*cols,rows,cols) = m1;
VERIFY_IS_APPROX(x1, m1.replicate(f1,f2));
x2.resize(2*rows,3*cols);
x2 << m2, m2, m2,
m2, m2, m2;
VERIFY_IS_APPROX(x2, (m2.template replicate<2,3>()));
x2.resize(rows,f1);
for (int j=0; j<f1; ++j)
x2.col(j) = v1;
VERIFY_IS_APPROX(x2, v1.rowwise().replicate(f1));
vx1.resize(rows*f2);
for (int j=0; j<f2; ++j)
vx1.segment(j*rows,rows) = v1;
VERIFY_IS_APPROX(vx1, v1.colwise().replicate(f2));
}
void test_array_replicate()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( replicate(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( replicate(Vector2f()) );
CALL_SUBTEST_3( replicate(Vector3d()) );
CALL_SUBTEST_4( replicate(Vector4f()) );
CALL_SUBTEST_5( replicate(VectorXf(16)) );
CALL_SUBTEST_6( replicate(VectorXcd(10)) );
}
}
| apache-2.0 |
tinchoss/Python_Android | python-build/openssl/crypto/mdc2/mdc2test.c | 950 | 5131 | /* crypto/mdc2/mdc2test.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 <stdlib.h>
#include <string.h>
#include "../e_os.h"
#if defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_MDC2)
#define OPENSSL_NO_MDC2
#endif
#ifdef OPENSSL_NO_MDC2
int main(int argc, char *argv[])
{
printf("No MDC2 support\n");
return(0);
}
#else
#include <openssl/evp.h>
#include <openssl/mdc2.h>
#ifdef CHARSET_EBCDIC
#include <openssl/ebcdic.h>
#endif
static unsigned char pad1[16]={
0x42,0xE5,0x0C,0xD2,0x24,0xBA,0xCE,0xBA,
0x76,0x0B,0xDD,0x2B,0xD4,0x09,0x28,0x1A
};
static unsigned char pad2[16]={
0x2E,0x46,0x79,0xB5,0xAD,0xD9,0xCA,0x75,
0x35,0xD8,0x7A,0xFE,0xAB,0x33,0xBE,0xE2
};
int main(int argc, char *argv[])
{
int ret=0;
unsigned char md[MDC2_DIGEST_LENGTH];
int i;
EVP_MD_CTX c;
static char *text="Now is the time for all ";
#ifdef CHARSET_EBCDIC
ebcdic2ascii(text,text,strlen(text));
#endif
EVP_MD_CTX_init(&c);
EVP_DigestInit_ex(&c,EVP_mdc2(), NULL);
EVP_DigestUpdate(&c,(unsigned char *)text,strlen(text));
EVP_DigestFinal_ex(&c,&(md[0]),NULL);
if (memcmp(md,pad1,MDC2_DIGEST_LENGTH) != 0)
{
for (i=0; i<MDC2_DIGEST_LENGTH; i++)
printf("%02X",md[i]);
printf(" <- generated\n");
for (i=0; i<MDC2_DIGEST_LENGTH; i++)
printf("%02X",pad1[i]);
printf(" <- correct\n");
ret=1;
}
else
printf("pad1 - ok\n");
EVP_DigestInit_ex(&c,EVP_mdc2(), NULL);
/* FIXME: use a ctl function? */
((MDC2_CTX *)c.md_data)->pad_type=2;
EVP_DigestUpdate(&c,(unsigned char *)text,strlen(text));
EVP_DigestFinal_ex(&c,&(md[0]),NULL);
if (memcmp(md,pad2,MDC2_DIGEST_LENGTH) != 0)
{
for (i=0; i<MDC2_DIGEST_LENGTH; i++)
printf("%02X",md[i]);
printf(" <- generated\n");
for (i=0; i<MDC2_DIGEST_LENGTH; i++)
printf("%02X",pad2[i]);
printf(" <- correct\n");
ret=1;
}
else
printf("pad2 - ok\n");
EVP_MD_CTX_cleanup(&c);
#ifdef OPENSSL_SYS_NETWARE
if (ret) printf("ERROR: %d\n", ret);
#endif
EXIT(ret);
return(ret);
}
#endif
| apache-2.0 |
azMallco/TeamTalk | win-client/3rdParty/src/cxImage/png/pngwio.c | 440 | 7611 |
/* pngwio.c - functions for data output
*
* Last changed in libpng 1.2.13 November 13, 2006
* For conditions of distribution and use, see copyright notice in png.h
* Copyright (c) 1998-2006 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This file provides a location for all output. Users who need
* special handling are expected to write functions that have the same
* arguments as these and perform similar functions, but that possibly
* use different output methods. Note that you shouldn't change these
* functions, but rather write replacement functions and then change
* them at run time with png_set_write_fn(...).
*/
#define PNG_INTERNAL
#include "png.h"
#ifdef PNG_WRITE_SUPPORTED
/* Write the data to whatever output you are using. The default routine
writes to a file pointer. Note that this routine sometimes gets called
with very small lengths, so you should implement some kind of simple
buffering if you are using unbuffered writes. This should never be asked
to write more than 64K on a 16 bit machine. */
void /* PRIVATE */
png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
if (png_ptr->write_data_fn != NULL )
(*(png_ptr->write_data_fn))(png_ptr, data, length);
else
png_error(png_ptr, "Call to NULL write function");
}
#if !defined(PNG_NO_STDIO)
/* This is the function that does the actual writing of data. If you are
not writing to a standard C stream, you should create a replacement
write_data function and use it at run time with png_set_write_fn(), rather
than changing the library. */
#ifndef USE_FAR_KEYWORD
void PNGAPI
png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_uint_32 check;
if(png_ptr == NULL) return;
#if defined(_WIN32_WCE)
if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
check = 0;
#else
check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
#endif
if (check != length)
png_error(png_ptr, "Write Error");
}
#else
/* this is the model-independent version. Since the standard I/O library
can't handle far buffers in the medium and small models, we have to copy
the data.
*/
#define NEAR_BUF_SIZE 1024
#define MIN(a,b) (a <= b ? a : b)
void PNGAPI
png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_uint_32 check;
png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
png_FILE_p io_ptr;
if(png_ptr == NULL) return;
/* Check if data really is near. If so, use usual code. */
near_data = (png_byte *)CVT_PTR_NOCHECK(data);
io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
if ((png_bytep)near_data == data)
{
#if defined(_WIN32_WCE)
if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
check = 0;
#else
check = fwrite(near_data, 1, length, io_ptr);
#endif
}
else
{
png_byte buf[NEAR_BUF_SIZE];
png_size_t written, remaining, err;
check = 0;
remaining = length;
do
{
written = MIN(NEAR_BUF_SIZE, remaining);
png_memcpy(buf, data, written); /* copy far buffer to near buffer */
#if defined(_WIN32_WCE)
if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
err = 0;
#else
err = fwrite(buf, 1, written, io_ptr);
#endif
if (err != written)
break;
else
check += err;
data += written;
remaining -= written;
}
while (remaining != 0);
}
if (check != length)
png_error(png_ptr, "Write Error");
}
#endif
#endif
/* This function is called to output any data pending writing (normally
to disk). After png_flush is called, there should be no data pending
writing in any buffers. */
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
void /* PRIVATE */
png_flush(png_structp png_ptr)
{
if (png_ptr->output_flush_fn != NULL)
(*(png_ptr->output_flush_fn))(png_ptr);
}
#if !defined(PNG_NO_STDIO)
void PNGAPI
png_default_flush(png_structp png_ptr)
{
#if !defined(_WIN32_WCE)
png_FILE_p io_ptr;
#endif
if(png_ptr == NULL) return;
#if !defined(_WIN32_WCE)
io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
if (io_ptr != NULL)
fflush(io_ptr);
#endif
}
#endif
#endif
/* This function allows the application to supply new output functions for
libpng if standard C streams aren't being used.
This function takes as its arguments:
png_ptr - pointer to a png output data structure
io_ptr - pointer to user supplied structure containing info about
the output functions. May be NULL.
write_data_fn - pointer to a new output function that takes as its
arguments a pointer to a png_struct, a pointer to
data to be written, and a 32-bit unsigned int that is
the number of bytes to be written. The new write
function should call png_error(png_ptr, "Error msg")
to exit and output any fatal error messages.
flush_data_fn - pointer to a new flush function that takes as its
arguments a pointer to a png_struct. After a call to
the flush function, there should be no data in any buffers
or pending transmission. If the output method doesn't do
any buffering of ouput, a function prototype must still be
supplied although it doesn't have to do anything. If
PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
time, output_flush_fn will be ignored, although it must be
supplied for compatibility. */
void PNGAPI
png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
{
if(png_ptr == NULL) return;
png_ptr->io_ptr = io_ptr;
#if !defined(PNG_NO_STDIO)
if (write_data_fn != NULL)
png_ptr->write_data_fn = write_data_fn;
else
png_ptr->write_data_fn = png_default_write_data;
#else
png_ptr->write_data_fn = write_data_fn;
#endif
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
#if !defined(PNG_NO_STDIO)
if (output_flush_fn != NULL)
png_ptr->output_flush_fn = output_flush_fn;
else
png_ptr->output_flush_fn = png_default_flush;
#else
png_ptr->output_flush_fn = output_flush_fn;
#endif
#endif /* PNG_WRITE_FLUSH_SUPPORTED */
/* It is an error to read while writing a png file */
if (png_ptr->read_data_fn != NULL)
{
png_ptr->read_data_fn = NULL;
png_warning(png_ptr,
"Attempted to set both read_data_fn and write_data_fn in");
png_warning(png_ptr,
"the same structure. Resetting read_data_fn to NULL.");
}
}
#if defined(USE_FAR_KEYWORD)
#if defined(_MSC_VER)
void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
{
void *near_ptr;
void FAR *far_ptr;
FP_OFF(near_ptr) = FP_OFF(ptr);
far_ptr = (void FAR *)near_ptr;
if(check != 0)
if(FP_SEG(ptr) != FP_SEG(far_ptr))
png_error(png_ptr,"segment lost in conversion");
return(near_ptr);
}
# else
void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
{
void *near_ptr;
void FAR *far_ptr;
near_ptr = (void FAR *)ptr;
far_ptr = (void FAR *)near_ptr;
if(check != 0)
if(far_ptr != ptr)
png_error(png_ptr,"segment lost in conversion");
return(near_ptr);
}
# endif
# endif
#endif /* PNG_WRITE_SUPPORTED */
| apache-2.0 |
ARM-software/mbed-beetle | libraries/USBHost/USBHost/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/common/usb0_host_dma.c | 200 | 12791 | /*******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved.
*******************************************************************************/
/*******************************************************************************
* File Name : usb0_host_dma.c
* $Rev: 1116 $
* $Date:: 2014-07-09 16:29:19 +0900#$
* Device(s) : RZ/A1H
* Tool-Chain :
* OS : None
* H/W Platform :
* Description : RZ/A1H R7S72100 USB Sample Program
* Operation :
* Limitations :
*******************************************************************************/
/*******************************************************************************
Includes <System Includes> , "Project Includes"
*******************************************************************************/
#include "usb0_host.h"
/* #include "usb0_host_dmacdrv.h" */
/*******************************************************************************
Typedef definitions
*******************************************************************************/
/*******************************************************************************
Macro definitions
*******************************************************************************/
/*******************************************************************************
Imported global variables and functions (from other files)
*******************************************************************************/
/*******************************************************************************
Exported global variables and functions (to be accessed by other files)
*******************************************************************************/
/*******************************************************************************
Private global variables and functions
*******************************************************************************/
static void usb0_host_dmaint(uint16_t fifo);
static void usb0_host_dmaint_buf2fifo(uint16_t pipe);
static void usb0_host_dmaint_fifo2buf(uint16_t pipe);
/*******************************************************************************
* Function Name: usb0_host_dma_stop_d0
* Description : D0FIFO DMA stop
* Arguments : uint16_t pipe : pipe number
* : uint32_t remain : transfer byte
* Return Value : none
*******************************************************************************/
void usb0_host_dma_stop_d0 (uint16_t pipe, uint32_t remain)
{
uint16_t dtln;
uint16_t dfacc;
uint16_t buffer;
uint16_t sds_b = 1;
dfacc = RZA_IO_RegRead_16(&USB200.D0FBCFG,
USB_DnFBCFG_DFACC_SHIFT,
USB_DnFBCFG_DFACC);
if (dfacc == 2)
{
sds_b = 32;
}
else if (dfacc == 1)
{
sds_b = 16;
}
else
{
if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 2)
{
sds_b = 4;
}
else if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 1)
{
sds_b = 2;
}
else
{
sds_b = 1;
}
}
if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1)
{
if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE)
{
buffer = USB200.D0FIFOCTR;
dtln = (buffer & USB_HOST_BITDTLN);
if ((dtln % sds_b) != 0)
{
remain += (sds_b - (dtln % sds_b));
}
g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain);
g_usb0_host_data_count[pipe] = remain;
}
}
RZA_IO_RegWrite_16(&USB200.D0FIFOSEL,
0,
USB_DnFIFOSEL_DREQE_SHIFT,
USB_DnFIFOSEL_DREQE);
}
/*******************************************************************************
* Function Name: usb0_host_dma_stop_d1
* Description : D1FIFO DMA stop
* Arguments : uint16_t pipe : pipe number
* : uint32_t remain : transfer byte
* Return Value : none
*******************************************************************************/
void usb0_host_dma_stop_d1 (uint16_t pipe, uint32_t remain)
{
uint16_t dtln;
uint16_t dfacc;
uint16_t buffer;
uint16_t sds_b = 1;
dfacc = RZA_IO_RegRead_16(&USB200.D1FBCFG,
USB_DnFBCFG_DFACC_SHIFT,
USB_DnFBCFG_DFACC);
if (dfacc == 2)
{
sds_b = 32;
}
else if (dfacc == 1)
{
sds_b = 16;
}
else
{
if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 2)
{
sds_b = 4;
}
else if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 1)
{
sds_b = 2;
}
else
{
sds_b = 1;
}
}
if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1)
{
if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE)
{
buffer = USB200.D1FIFOCTR;
dtln = (buffer & USB_HOST_BITDTLN);
if ((dtln % sds_b) != 0)
{
remain += (sds_b - (dtln % sds_b));
}
g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain);
g_usb0_host_data_count[pipe] = remain;
}
}
RZA_IO_RegWrite_16(&USB200.D1FIFOSEL,
0,
USB_DnFIFOSEL_DREQE_SHIFT,
USB_DnFIFOSEL_DREQE);
}
/*******************************************************************************
* Function Name: usb0_host_dma_interrupt_d0fifo
* Description : This function is DMA interrupt handler entry.
* : Execute usb1_host_dmaint() after disabling DMA interrupt in this function.
* : Disable DMA interrupt to DMAC executed when USB_HOST_D0FIFO_DMA is
* : specified by dma->fifo.
* : Register this function as DMA complete interrupt.
* Arguments : uint32_t int_sense ; Interrupts detection mode
* : ; INTC_LEVEL_SENSITIVE : Level sense
* : ; INTC_EDGE_TRIGGER : Edge trigger
* Return Value : none
*******************************************************************************/
void usb0_host_dma_interrupt_d0fifo (uint32_t int_sense)
{
usb0_host_dmaint(USB_HOST_D0FIFO);
g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY;
}
/*******************************************************************************
* Function Name: usb0_host_dma_interrupt_d1fifo
* Description : This function is DMA interrupt handler entry.
* : Execute usb0_host_dmaint() after disabling DMA interrupt in this function.
* : Disable DMA interrupt to DMAC executed when USB_HOST_D1FIFO_DMA is
* : specified by dma->fifo.
* : Register this function as DMA complete interrupt.
* Arguments : uint32_t int_sense ; Interrupts detection mode
* : ; INTC_LEVEL_SENSITIVE : Level sense
* : ; INTC_EDGE_TRIGGER : Edge trigger
* Return Value : none
*******************************************************************************/
void usb0_host_dma_interrupt_d1fifo (uint32_t int_sense)
{
usb0_host_dmaint(USB_HOST_D1FIFO);
g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY;
}
/*******************************************************************************
* Function Name: usb0_host_dmaint
* Description : This function is DMA transfer end interrupt
* Arguments : uint16_t fifo ; fifo number
* : ; USB_HOST_D0FIFO
* : ; USB_HOST_D1FIFO
* Return Value : none
*******************************************************************************/
static void usb0_host_dmaint (uint16_t fifo)
{
uint16_t pipe;
pipe = g_usb0_host_DmaPipe[fifo];
if (g_usb0_host_DmaInfo[fifo].dir == USB_HOST_BUF2FIFO)
{
usb0_host_dmaint_buf2fifo(pipe);
}
else
{
usb0_host_dmaint_fifo2buf(pipe);
}
}
/*******************************************************************************
* Function Name: usb0_host_dmaint_fifo2buf
* Description : Executes read completion from FIFO by DMAC.
* Arguments : uint16_t pipe : pipe number
* Return Value : none
*******************************************************************************/
static void usb0_host_dmaint_fifo2buf (uint16_t pipe)
{
uint32_t remain;
uint16_t useport;
if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE)
{
useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE);
if (useport == USB_HOST_D0FIFO_DMA)
{
remain = Userdef_USB_usb0_host_stop_dma0();
usb0_host_dma_stop_d0(pipe, remain);
if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0)
{
if (g_usb0_host_DmaStatus[USB_HOST_D0FIFO] == USB_HOST_DMA_BUSYEND)
{
USB200.D0FIFOCTR = USB_HOST_BITBCLR;
g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE;
}
else
{
usb0_host_enable_brdy_int(pipe);
}
}
}
else
{
remain = Userdef_USB_usb0_host_stop_dma1();
usb0_host_dma_stop_d1(pipe, remain);
if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0)
{
if (g_usb0_host_DmaStatus[USB_HOST_D1FIFO] == USB_HOST_DMA_BUSYEND)
{
USB200.D1FIFOCTR = USB_HOST_BITBCLR;
g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE;
}
else
{
usb0_host_enable_brdy_int(pipe);
}
}
}
}
}
/*******************************************************************************
* Function Name: usb0_host_dmaint_buf2fifo
* Description : Executes write completion in FIFO by DMAC.
* Arguments : uint16_t pipe : pipe number
* Return Value : none
*******************************************************************************/
static void usb0_host_dmaint_buf2fifo (uint16_t pipe)
{
uint16_t useport;
uint32_t remain;
useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE);
if (useport == USB_HOST_D0FIFO_DMA)
{
remain = Userdef_USB_usb0_host_stop_dma0();
usb0_host_dma_stop_d0(pipe, remain);
if (g_usb0_host_DmaBval[USB_HOST_D0FIFO] != 0)
{
RZA_IO_RegWrite_16(&USB200.D0FIFOCTR,
1,
USB_DnFIFOCTR_BVAL_SHIFT,
USB_DnFIFOCTR_BVAL);
}
}
else
{
remain = Userdef_USB_usb0_host_stop_dma1();
usb0_host_dma_stop_d1(pipe, remain);
if (g_usb0_host_DmaBval[USB_HOST_D1FIFO] != 0)
{
RZA_IO_RegWrite_16(&USB200.D1FIFOCTR,
1,
USB_DnFIFOCTR_BVAL_SHIFT,
USB_DnFIFOCTR_BVAL);
}
}
usb0_host_enable_bemp_int(pipe);
}
/* End of File */
| apache-2.0 |
junior1407/AlgoritmoHuffman | RedBlack/cmake-build-debug/CMakeFiles/3.7.1/CompilerIdCXX/CMakeCXXCompilerId.cpp | 971 | 16397 | /* This source file must have a .cpp extension so that all C++ compilers
recognize the extension without flags. Borland does not know .cxx for
example. */
#ifndef __cplusplus
# error "A C compiler has been selected for C++."
#endif
/* Version number components: V=Version, R=Revision, P=Patch
Version date components: YYYY=Year, MM=Month, DD=Day */
#if defined(__COMO__)
# define COMPILER_ID "Comeau"
/* __COMO_VERSION__ = VRR */
# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100)
# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100)
#elif defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
/* __INTEL_COMPILER = VRP */
# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
# if defined(__INTEL_COMPILER_UPDATE)
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
# else
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10)
# endif
# if defined(__INTEL_COMPILER_BUILD_DATE)
/* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif
#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF)
#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
/* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)
#elif defined(__WATCOMC__) && __WATCOMC__ < 1200
# define COMPILER_ID "Watcom"
/* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__WATCOMC__)
# define COMPILER_ID "OpenWatcom"
/* __WATCOMC__ = VVRP + 1100 */
# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__SUNPRO_CC)
# define COMPILER_ID "SunPro"
# if __SUNPRO_CC >= 0x5100
/* __SUNPRO_CC = 0xVRRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)
# else
/* __SUNPRO_CC = 0xVRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF)
# endif
#elif defined(__HP_aCC)
# define COMPILER_ID "HP"
/* __HP_aCC = VVRRPP */
# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000)
# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100)
#elif defined(__DECCXX)
# define COMPILER_ID "Compaq"
/* __DECCXX_VER = VVRRTPPPP */
# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000)
# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100)
# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000)
#elif defined(__IBMCPP__) && defined(__COMPILER_VER__)
# define COMPILER_ID "zOS"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800
# define COMPILER_ID "XL"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800
# define COMPILER_ID "VisualAge"
/* __IBMCPP__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10)
#elif defined(__PGI)
# define COMPILER_ID "PGI"
# define COMPILER_VERSION_MAJOR DEC(__PGIC__)
# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)
# if defined(__PGIC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
# endif
#elif defined(_CRAYC)
# define COMPILER_ID "Cray"
# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR)
# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)
#elif defined(__TI_COMPILER_VERSION__)
# define COMPILER_ID "TI"
/* __TI_COMPILER_VERSION__ = VVVRRRPPP */
# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)
# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000)
# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000)
#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version)
# define COMPILER_ID "Fujitsu"
#elif defined(__SCO_VERSION__)
# define COMPILER_ID "SCO"
#elif defined(__clang__) && defined(__apple_build_version__)
# define COMPILER_ID "AppleClang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__)
#elif defined(__clang__)
# define COMPILER_ID "Clang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__GNUC__)
# define COMPILER_ID "GNU"
# define COMPILER_VERSION_MAJOR DEC(__GNUC__)
# if defined(__GNUC_MINOR__)
# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)
# endif
# if defined(__GNUC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif
#elif defined(_MSC_VER)
# define COMPILER_ID "MSVC"
/* _MSC_VER = VVRR */
# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)
# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)
# if defined(_MSC_FULL_VER)
# if _MSC_VER >= 1400
/* _MSC_FULL_VER = VVRRPPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)
# else
/* _MSC_FULL_VER = VVRRPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)
# endif
# endif
# if defined(_MSC_BUILD)
# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)
# endif
#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)
# define COMPILER_ID "ADSP"
#if defined(__VISUALDSPVERSION__)
/* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)
# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF)
#endif
#elif defined(__IAR_SYSTEMS_ICC__ ) || defined(__IAR_SYSTEMS_ICC)
# define COMPILER_ID "IAR"
#elif defined(__ARMCC_VERSION)
# define COMPILER_ID "ARMCC"
#if __ARMCC_VERSION >= 1000000
/* __ARMCC_VERSION = VRRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#else
/* __ARMCC_VERSION = VRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#endif
#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION)
# define COMPILER_ID "MIPSpro"
# if defined(_SGI_COMPILER_VERSION)
/* _SGI_COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION % 10)
# else
/* _COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION % 10)
# endif
/* These compilers are either not known or too old to define an
identification macro. Try to identify the platform and guess that
it is the native compiler. */
#elif defined(__sgi)
# define COMPILER_ID "MIPSpro"
#elif defined(__hpux) || defined(__hpua)
# define COMPILER_ID "HP"
#else /* unknown compiler */
# define COMPILER_ID ""
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
#ifdef SIMULATE_ID
char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]";
#endif
#ifdef __QNXNTO__
char const* qnxnto = "INFO" ":" "qnxnto[]";
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]";
#endif
#define STRINGIFY_HELPER(X) #X
#define STRINGIFY(X) STRINGIFY_HELPER(X)
/* Identify known platforms by name. */
#if defined(__linux) || defined(__linux__) || defined(linux)
# define PLATFORM_ID "Linux"
#elif defined(__CYGWIN__)
# define PLATFORM_ID "Cygwin"
#elif defined(__MINGW32__)
# define PLATFORM_ID "MinGW"
#elif defined(__APPLE__)
# define PLATFORM_ID "Darwin"
#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# define PLATFORM_ID "Windows"
#elif defined(__FreeBSD__) || defined(__FreeBSD)
# define PLATFORM_ID "FreeBSD"
#elif defined(__NetBSD__) || defined(__NetBSD)
# define PLATFORM_ID "NetBSD"
#elif defined(__OpenBSD__) || defined(__OPENBSD)
# define PLATFORM_ID "OpenBSD"
#elif defined(__sun) || defined(sun)
# define PLATFORM_ID "SunOS"
#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__)
# define PLATFORM_ID "AIX"
#elif defined(__sgi) || defined(__sgi__) || defined(_SGI)
# define PLATFORM_ID "IRIX"
#elif defined(__hpux) || defined(__hpux__)
# define PLATFORM_ID "HP-UX"
#elif defined(__HAIKU__)
# define PLATFORM_ID "Haiku"
#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS)
# define PLATFORM_ID "BeOS"
#elif defined(__QNX__) || defined(__QNXNTO__)
# define PLATFORM_ID "QNX"
#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__)
# define PLATFORM_ID "Tru64"
#elif defined(__riscos) || defined(__riscos__)
# define PLATFORM_ID "RISCos"
#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__)
# define PLATFORM_ID "SINIX"
#elif defined(__UNIX_SV__)
# define PLATFORM_ID "UNIX_SV"
#elif defined(__bsdos__)
# define PLATFORM_ID "BSDOS"
#elif defined(_MPRAS) || defined(MPRAS)
# define PLATFORM_ID "MP-RAS"
#elif defined(__osf) || defined(__osf__)
# define PLATFORM_ID "OSF1"
#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv)
# define PLATFORM_ID "SCO_SV"
#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX)
# define PLATFORM_ID "ULTRIX"
#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX)
# define PLATFORM_ID "Xenix"
#elif defined(__WATCOMC__)
# if defined(__LINUX__)
# define PLATFORM_ID "Linux"
# elif defined(__DOS__)
# define PLATFORM_ID "DOS"
# elif defined(__OS2__)
# define PLATFORM_ID "OS2"
# elif defined(__WINDOWS__)
# define PLATFORM_ID "Windows3x"
# else /* unknown platform */
# define PLATFORM_ID
# endif
#else /* unknown platform */
# define PLATFORM_ID
#endif
/* For windows compilers MSVC and Intel we can determine
the architecture of the compiler being used. This is because
the compilers do not have flags that can change the architecture,
but rather depend on which compiler is being used
*/
#if defined(_WIN32) && defined(_MSC_VER)
# if defined(_M_IA64)
# define ARCHITECTURE_ID "IA64"
# elif defined(_M_X64) || defined(_M_AMD64)
# define ARCHITECTURE_ID "x64"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# elif defined(_M_ARM)
# if _M_ARM == 4
# define ARCHITECTURE_ID "ARMV4I"
# elif _M_ARM == 5
# define ARCHITECTURE_ID "ARMV5I"
# else
# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM)
# endif
# elif defined(_M_MIPS)
# define ARCHITECTURE_ID "MIPS"
# elif defined(_M_SH)
# define ARCHITECTURE_ID "SHx"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#elif defined(__WATCOMC__)
# if defined(_M_I86)
# define ARCHITECTURE_ID "I86"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#else
# define ARCHITECTURE_ID
#endif
/* Convert integer to decimal digit literals. */
#define DEC(n) \
('0' + (((n) / 10000000)%10)), \
('0' + (((n) / 1000000)%10)), \
('0' + (((n) / 100000)%10)), \
('0' + (((n) / 10000)%10)), \
('0' + (((n) / 1000)%10)), \
('0' + (((n) / 100)%10)), \
('0' + (((n) / 10)%10)), \
('0' + ((n) % 10))
/* Convert integer to hex digit literals. */
#define HEX(n) \
('0' + ((n)>>28 & 0xF)), \
('0' + ((n)>>24 & 0xF)), \
('0' + ((n)>>20 & 0xF)), \
('0' + ((n)>>16 & 0xF)), \
('0' + ((n)>>12 & 0xF)), \
('0' + ((n)>>8 & 0xF)), \
('0' + ((n)>>4 & 0xF)), \
('0' + ((n) & 0xF))
/* Construct a string literal encoding the version number components. */
#ifdef COMPILER_VERSION_MAJOR
char const info_version[] = {
'I', 'N', 'F', 'O', ':',
'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',
COMPILER_VERSION_MAJOR,
# ifdef COMPILER_VERSION_MINOR
'.', COMPILER_VERSION_MINOR,
# ifdef COMPILER_VERSION_PATCH
'.', COMPILER_VERSION_PATCH,
# ifdef COMPILER_VERSION_TWEAK
'.', COMPILER_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct a string literal encoding the version number components. */
#ifdef SIMULATE_VERSION_MAJOR
char const info_simulate_version[] = {
'I', 'N', 'F', 'O', ':',
's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[',
SIMULATE_VERSION_MAJOR,
# ifdef SIMULATE_VERSION_MINOR
'.', SIMULATE_VERSION_MINOR,
# ifdef SIMULATE_VERSION_PATCH
'.', SIMULATE_VERSION_PATCH,
# ifdef SIMULATE_VERSION_TWEAK
'.', SIMULATE_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]";
char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]";
const char* info_language_dialect_default = "INFO" ":" "dialect_default["
#if __cplusplus >= 201402L
"14"
#elif __cplusplus >= 201103L
"11"
#else
"98"
#endif
"]";
/*--------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
int require = 0;
require += info_compiler[argc];
require += info_platform[argc];
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
#ifdef SIMULATE_ID
require += info_simulate[argc];
#endif
#ifdef SIMULATE_VERSION_MAJOR
require += info_simulate_version[argc];
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
require += info_cray[argc];
#endif
require += info_language_dialect_default[argc];
(void)argv;
return require;
}
| apache-2.0 |
Ant-Droid/android_kernel_moto_shamu_OLD | drivers/pinctrl/mvebu/pinctrl-armada-370.c | 1999 | 13701 | /*
* Marvell Armada 370 pinctrl driver based on mvebu pinctrl core
*
* Copyright (C) 2012 Marvell
*
* Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*/
#include <linux/err.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pinctrl/pinctrl.h>
#include "pinctrl-mvebu.h"
static struct mvebu_mpp_mode mv88f6710_mpp_modes[] = {
MPP_MODE(0,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "uart0", "rxd")),
MPP_MODE(1,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "uart0", "txd")),
MPP_MODE(2,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "i2c0", "sck"),
MPP_FUNCTION(0x2, "uart0", "txd")),
MPP_MODE(3,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "i2c0", "sda"),
MPP_FUNCTION(0x2, "uart0", "rxd")),
MPP_MODE(4,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "cpu_pd", "vdd")),
MPP_MODE(5,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txclko"),
MPP_FUNCTION(0x2, "uart1", "txd"),
MPP_FUNCTION(0x4, "spi1", "clk"),
MPP_FUNCTION(0x5, "audio", "mclk")),
MPP_MODE(6,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "txd0"),
MPP_FUNCTION(0x2, "sata0", "prsnt"),
MPP_FUNCTION(0x4, "tdm", "rst"),
MPP_FUNCTION(0x5, "audio", "sdo")),
MPP_MODE(7,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd1"),
MPP_FUNCTION(0x4, "tdm", "tdx"),
MPP_FUNCTION(0x5, "audio", "lrclk")),
MPP_MODE(8,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "txd2"),
MPP_FUNCTION(0x2, "uart0", "rts"),
MPP_FUNCTION(0x4, "tdm", "drx"),
MPP_FUNCTION(0x5, "audio", "bclk")),
MPP_MODE(9,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd3"),
MPP_FUNCTION(0x2, "uart1", "txd"),
MPP_FUNCTION(0x3, "sd0", "clk"),
MPP_FUNCTION(0x5, "audio", "spdifo")),
MPP_MODE(10,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "txctl"),
MPP_FUNCTION(0x2, "uart0", "cts"),
MPP_FUNCTION(0x4, "tdm", "fsync"),
MPP_FUNCTION(0x5, "audio", "sdi")),
MPP_MODE(11,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd0"),
MPP_FUNCTION(0x2, "uart1", "rxd"),
MPP_FUNCTION(0x3, "sd0", "cmd"),
MPP_FUNCTION(0x4, "spi0", "cs1"),
MPP_FUNCTION(0x5, "sata1", "prsnt"),
MPP_FUNCTION(0x6, "spi1", "cs1")),
MPP_MODE(12,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd1"),
MPP_FUNCTION(0x2, "i2c1", "sda"),
MPP_FUNCTION(0x3, "sd0", "d0"),
MPP_FUNCTION(0x4, "spi1", "cs0"),
MPP_FUNCTION(0x5, "audio", "spdifi")),
MPP_MODE(13,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd2"),
MPP_FUNCTION(0x2, "i2c1", "sck"),
MPP_FUNCTION(0x3, "sd0", "d1"),
MPP_FUNCTION(0x4, "tdm", "pclk"),
MPP_FUNCTION(0x5, "audio", "rmclk")),
MPP_MODE(14,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd3"),
MPP_FUNCTION(0x2, "pcie", "clkreq0"),
MPP_FUNCTION(0x3, "sd0", "d2"),
MPP_FUNCTION(0x4, "spi1", "mosi"),
MPP_FUNCTION(0x5, "spi0", "cs2")),
MPP_MODE(15,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxctl"),
MPP_FUNCTION(0x2, "pcie", "clkreq1"),
MPP_FUNCTION(0x3, "sd0", "d3"),
MPP_FUNCTION(0x4, "spi1", "miso"),
MPP_FUNCTION(0x5, "spi0", "cs3")),
MPP_MODE(16,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxclk"),
MPP_FUNCTION(0x2, "uart1", "rxd"),
MPP_FUNCTION(0x4, "tdm", "int"),
MPP_FUNCTION(0x5, "audio", "extclk")),
MPP_MODE(17,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge", "mdc")),
MPP_MODE(18,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge", "mdio")),
MPP_MODE(19,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "txclk"),
MPP_FUNCTION(0x2, "ge1", "txclkout"),
MPP_FUNCTION(0x4, "tdm", "pclk")),
MPP_MODE(20,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd4"),
MPP_FUNCTION(0x2, "ge1", "txd0")),
MPP_MODE(21,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd5"),
MPP_FUNCTION(0x2, "ge1", "txd1"),
MPP_FUNCTION(0x4, "uart1", "txd")),
MPP_MODE(22,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd6"),
MPP_FUNCTION(0x2, "ge1", "txd2"),
MPP_FUNCTION(0x4, "uart0", "rts")),
MPP_MODE(23,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "ge0", "txd7"),
MPP_FUNCTION(0x2, "ge1", "txd3"),
MPP_FUNCTION(0x4, "spi1", "mosi")),
MPP_MODE(24,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "col"),
MPP_FUNCTION(0x2, "ge1", "txctl"),
MPP_FUNCTION(0x4, "spi1", "cs0")),
MPP_MODE(25,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxerr"),
MPP_FUNCTION(0x2, "ge1", "rxd0"),
MPP_FUNCTION(0x4, "uart1", "rxd")),
MPP_MODE(26,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "crs"),
MPP_FUNCTION(0x2, "ge1", "rxd1"),
MPP_FUNCTION(0x4, "spi1", "miso")),
MPP_MODE(27,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd4"),
MPP_FUNCTION(0x2, "ge1", "rxd2"),
MPP_FUNCTION(0x4, "uart0", "cts")),
MPP_MODE(28,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd5"),
MPP_FUNCTION(0x2, "ge1", "rxd3")),
MPP_MODE(29,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd6"),
MPP_FUNCTION(0x2, "ge1", "rxctl"),
MPP_FUNCTION(0x4, "i2c1", "sda")),
MPP_MODE(30,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "ge0", "rxd7"),
MPP_FUNCTION(0x2, "ge1", "rxclk"),
MPP_FUNCTION(0x4, "i2c1", "sck")),
MPP_MODE(31,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x3, "tclk", NULL),
MPP_FUNCTION(0x4, "ge0", "txerr")),
MPP_MODE(32,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "spi0", "cs0")),
MPP_MODE(33,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "bootcs"),
MPP_FUNCTION(0x2, "spi0", "cs0")),
MPP_MODE(34,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "wen0"),
MPP_FUNCTION(0x2, "spi0", "mosi")),
MPP_MODE(35,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "oen"),
MPP_FUNCTION(0x2, "spi0", "sck")),
MPP_MODE(36,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "a1"),
MPP_FUNCTION(0x2, "spi0", "miso")),
MPP_MODE(37,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "a0"),
MPP_FUNCTION(0x2, "sata0", "prsnt")),
MPP_MODE(38,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ready"),
MPP_FUNCTION(0x2, "uart1", "cts"),
MPP_FUNCTION(0x3, "uart0", "cts")),
MPP_MODE(39,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad0"),
MPP_FUNCTION(0x2, "audio", "spdifo")),
MPP_MODE(40,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad1"),
MPP_FUNCTION(0x2, "uart1", "rts"),
MPP_FUNCTION(0x3, "uart0", "rts")),
MPP_MODE(41,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad2"),
MPP_FUNCTION(0x2, "uart1", "rxd")),
MPP_MODE(42,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad3"),
MPP_FUNCTION(0x2, "uart1", "txd")),
MPP_MODE(43,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad4"),
MPP_FUNCTION(0x2, "audio", "bclk")),
MPP_MODE(44,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad5"),
MPP_FUNCTION(0x2, "audio", "mclk")),
MPP_MODE(45,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad6"),
MPP_FUNCTION(0x2, "audio", "lrclk")),
MPP_MODE(46,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad7"),
MPP_FUNCTION(0x2, "audio", "sdo")),
MPP_MODE(47,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad8"),
MPP_FUNCTION(0x3, "sd0", "clk"),
MPP_FUNCTION(0x5, "audio", "spdifo")),
MPP_MODE(48,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad9"),
MPP_FUNCTION(0x2, "uart0", "rts"),
MPP_FUNCTION(0x3, "sd0", "cmd"),
MPP_FUNCTION(0x4, "sata1", "prsnt"),
MPP_FUNCTION(0x5, "spi0", "cs1")),
MPP_MODE(49,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad10"),
MPP_FUNCTION(0x2, "pcie", "clkreq1"),
MPP_FUNCTION(0x3, "sd0", "d0"),
MPP_FUNCTION(0x4, "spi1", "cs0"),
MPP_FUNCTION(0x5, "audio", "spdifi")),
MPP_MODE(50,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad11"),
MPP_FUNCTION(0x2, "uart0", "cts"),
MPP_FUNCTION(0x3, "sd0", "d1"),
MPP_FUNCTION(0x4, "spi1", "miso"),
MPP_FUNCTION(0x5, "audio", "rmclk")),
MPP_MODE(51,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad12"),
MPP_FUNCTION(0x2, "i2c1", "sda"),
MPP_FUNCTION(0x3, "sd0", "d2"),
MPP_FUNCTION(0x4, "spi1", "mosi")),
MPP_MODE(52,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad13"),
MPP_FUNCTION(0x2, "i2c1", "sck"),
MPP_FUNCTION(0x3, "sd0", "d3"),
MPP_FUNCTION(0x4, "spi1", "sck")),
MPP_MODE(53,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ad14"),
MPP_FUNCTION(0x2, "sd0", "clk"),
MPP_FUNCTION(0x3, "tdm", "pclk"),
MPP_FUNCTION(0x4, "spi0", "cs2"),
MPP_FUNCTION(0x5, "pcie", "clkreq1")),
MPP_MODE(54,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ad15"),
MPP_FUNCTION(0x3, "tdm", "dtx")),
MPP_MODE(55,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "cs1"),
MPP_FUNCTION(0x2, "uart1", "txd"),
MPP_FUNCTION(0x3, "tdm", "rst"),
MPP_FUNCTION(0x4, "sata1", "prsnt"),
MPP_FUNCTION(0x5, "sata0", "prsnt")),
MPP_MODE(56,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "cs2"),
MPP_FUNCTION(0x2, "uart1", "cts"),
MPP_FUNCTION(0x3, "uart0", "cts"),
MPP_FUNCTION(0x4, "spi0", "cs3"),
MPP_FUNCTION(0x5, "pcie", "clkreq0"),
MPP_FUNCTION(0x6, "spi1", "cs1")),
MPP_MODE(57,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "cs3"),
MPP_FUNCTION(0x2, "uart1", "rxd"),
MPP_FUNCTION(0x3, "tdm", "fsync"),
MPP_FUNCTION(0x4, "sata0", "prsnt"),
MPP_FUNCTION(0x5, "audio", "sdo")),
MPP_MODE(58,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "cs0"),
MPP_FUNCTION(0x2, "uart1", "rts"),
MPP_FUNCTION(0x3, "tdm", "int"),
MPP_FUNCTION(0x5, "audio", "extclk"),
MPP_FUNCTION(0x6, "uart0", "rts")),
MPP_MODE(59,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "ale0"),
MPP_FUNCTION(0x2, "uart1", "rts"),
MPP_FUNCTION(0x3, "uart0", "rts"),
MPP_FUNCTION(0x5, "audio", "bclk")),
MPP_MODE(60,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "ale1"),
MPP_FUNCTION(0x2, "uart1", "rxd"),
MPP_FUNCTION(0x3, "sata0", "prsnt"),
MPP_FUNCTION(0x4, "pcie", "rst-out"),
MPP_FUNCTION(0x5, "audio", "sdi")),
MPP_MODE(61,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "dev", "wen1"),
MPP_FUNCTION(0x2, "uart1", "txd"),
MPP_FUNCTION(0x5, "audio", "rclk")),
MPP_MODE(62,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "dev", "a2"),
MPP_FUNCTION(0x2, "uart1", "cts"),
MPP_FUNCTION(0x3, "tdm", "drx"),
MPP_FUNCTION(0x4, "pcie", "clkreq0"),
MPP_FUNCTION(0x5, "audio", "mclk"),
MPP_FUNCTION(0x6, "uart0", "cts")),
MPP_MODE(63,
MPP_FUNCTION(0x0, "gpo", NULL),
MPP_FUNCTION(0x1, "spi0", "sck"),
MPP_FUNCTION(0x2, "tclk", NULL)),
MPP_MODE(64,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "spi0", "miso"),
MPP_FUNCTION(0x2, "spi0-1", "cs1")),
MPP_MODE(65,
MPP_FUNCTION(0x0, "gpio", NULL),
MPP_FUNCTION(0x1, "spi0", "mosi"),
MPP_FUNCTION(0x2, "spi0-1", "cs2")),
};
static struct mvebu_pinctrl_soc_info armada_370_pinctrl_info;
static struct of_device_id armada_370_pinctrl_of_match[] = {
{ .compatible = "marvell,mv88f6710-pinctrl" },
{ },
};
static struct mvebu_mpp_ctrl mv88f6710_mpp_controls[] = {
MPP_REG_CTRL(0, 65),
};
static struct pinctrl_gpio_range mv88f6710_mpp_gpio_ranges[] = {
MPP_GPIO_RANGE(0, 0, 0, 32),
MPP_GPIO_RANGE(1, 32, 32, 32),
MPP_GPIO_RANGE(2, 64, 64, 2),
};
static int armada_370_pinctrl_probe(struct platform_device *pdev)
{
struct mvebu_pinctrl_soc_info *soc = &armada_370_pinctrl_info;
soc->variant = 0; /* no variants for Armada 370 */
soc->controls = mv88f6710_mpp_controls;
soc->ncontrols = ARRAY_SIZE(mv88f6710_mpp_controls);
soc->modes = mv88f6710_mpp_modes;
soc->nmodes = ARRAY_SIZE(mv88f6710_mpp_modes);
soc->gpioranges = mv88f6710_mpp_gpio_ranges;
soc->ngpioranges = ARRAY_SIZE(mv88f6710_mpp_gpio_ranges);
pdev->dev.platform_data = soc;
return mvebu_pinctrl_probe(pdev);
}
static int armada_370_pinctrl_remove(struct platform_device *pdev)
{
return mvebu_pinctrl_remove(pdev);
}
static struct platform_driver armada_370_pinctrl_driver = {
.driver = {
.name = "armada-370-pinctrl",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(armada_370_pinctrl_of_match),
},
.probe = armada_370_pinctrl_probe,
.remove = armada_370_pinctrl_remove,
};
module_platform_driver(armada_370_pinctrl_driver);
MODULE_AUTHOR("Thomas Petazzoni <thomas.petazzoni@free-electrons.com>");
MODULE_DESCRIPTION("Marvell Armada 370 pinctrl driver");
MODULE_LICENSE("GPL v2");
| apache-2.0 |
OLIMEX/DIY-LAPTOP | SOFTWARE/A64-TERES/linux-a64/drivers/pci/hotplug/ibmphp_hpc.c | 10708 | 33511 | /*
* IBM Hot Plug Controller Driver
*
* Written By: Jyoti Shah, IBM Corporation
*
* Copyright (C) 2001-2003 IBM Corp.
*
* All rights reserved.
*
* This program 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 2 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, GOOD TITLE or
* NON INFRINGEMENT. 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <gregkh@us.ibm.com>
* <jshah@us.ibm.com>
*
*/
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/semaphore.h>
#include <linux/kthread.h>
#include "ibmphp.h"
static int to_debug = 0;
#define debug_polling(fmt, arg...) do { if (to_debug) debug (fmt, arg); } while (0)
//----------------------------------------------------------------------------
// timeout values
//----------------------------------------------------------------------------
#define CMD_COMPLETE_TOUT_SEC 60 // give HPC 60 sec to finish cmd
#define HPC_CTLR_WORKING_TOUT 60 // give HPC 60 sec to finish cmd
#define HPC_GETACCESS_TIMEOUT 60 // seconds
#define POLL_INTERVAL_SEC 2 // poll HPC every 2 seconds
#define POLL_LATCH_CNT 5 // poll latch 5 times, then poll slots
//----------------------------------------------------------------------------
// Winnipeg Architected Register Offsets
//----------------------------------------------------------------------------
#define WPG_I2CMBUFL_OFFSET 0x08 // I2C Message Buffer Low
#define WPG_I2CMOSUP_OFFSET 0x10 // I2C Master Operation Setup Reg
#define WPG_I2CMCNTL_OFFSET 0x20 // I2C Master Control Register
#define WPG_I2CPARM_OFFSET 0x40 // I2C Parameter Register
#define WPG_I2CSTAT_OFFSET 0x70 // I2C Status Register
//----------------------------------------------------------------------------
// Winnipeg Store Type commands (Add this commands to the register offset)
//----------------------------------------------------------------------------
#define WPG_I2C_AND 0x1000 // I2C AND operation
#define WPG_I2C_OR 0x2000 // I2C OR operation
//----------------------------------------------------------------------------
// Command set for I2C Master Operation Setup Register
//----------------------------------------------------------------------------
#define WPG_READATADDR_MASK 0x00010000 // read,bytes,I2C shifted,index
#define WPG_WRITEATADDR_MASK 0x40010000 // write,bytes,I2C shifted,index
#define WPG_READDIRECT_MASK 0x10010000
#define WPG_WRITEDIRECT_MASK 0x60010000
//----------------------------------------------------------------------------
// bit masks for I2C Master Control Register
//----------------------------------------------------------------------------
#define WPG_I2CMCNTL_STARTOP_MASK 0x00000002 // Start the Operation
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
#define WPG_I2C_IOREMAP_SIZE 0x2044 // size of linear address interval
//----------------------------------------------------------------------------
// command index
//----------------------------------------------------------------------------
#define WPG_1ST_SLOT_INDEX 0x01 // index - 1st slot for ctlr
#define WPG_CTLR_INDEX 0x0F // index - ctlr
#define WPG_1ST_EXTSLOT_INDEX 0x10 // index - 1st ext slot for ctlr
#define WPG_1ST_BUS_INDEX 0x1F // index - 1st bus for ctlr
//----------------------------------------------------------------------------
// macro utilities
//----------------------------------------------------------------------------
// if bits 20,22,25,26,27,29,30 are OFF return 1
#define HPC_I2CSTATUS_CHECK(s) ((u8)((s & 0x00000A76) ? 0 : 1))
//----------------------------------------------------------------------------
// global variables
//----------------------------------------------------------------------------
static struct mutex sem_hpcaccess; // lock access to HPC
static struct semaphore semOperations; // lock all operations and
// access to data structures
static struct semaphore sem_exit; // make sure polling thread goes away
static struct task_struct *ibmphp_poll_thread;
//----------------------------------------------------------------------------
// local function prototypes
//----------------------------------------------------------------------------
static u8 i2c_ctrl_read (struct controller *, void __iomem *, u8);
static u8 i2c_ctrl_write (struct controller *, void __iomem *, u8, u8);
static u8 hpc_writecmdtoindex (u8, u8);
static u8 hpc_readcmdtoindex (u8, u8);
static void get_hpc_access (void);
static void free_hpc_access (void);
static int poll_hpc(void *data);
static int process_changeinstatus (struct slot *, struct slot *);
static int process_changeinlatch (u8, u8, struct controller *);
static int hpc_wait_ctlr_notworking (int, struct controller *, void __iomem *, u8 *);
//----------------------------------------------------------------------------
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_initvars
*
* Action: initialize semaphores and variables
*---------------------------------------------------------------------*/
void __init ibmphp_hpc_initvars (void)
{
debug ("%s - Entry\n", __func__);
mutex_init(&sem_hpcaccess);
sema_init(&semOperations, 1);
sema_init(&sem_exit, 0);
to_debug = 0;
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: i2c_ctrl_read
*
* Action: read from HPC over I2C
*
*---------------------------------------------------------------------*/
static u8 i2c_ctrl_read (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index)
{
u8 status;
int i;
void __iomem *wpg_addr; // base addr + offset
unsigned long wpg_data; // data to/from WPG LOHI format
unsigned long ultemp;
unsigned long data; // actual data HILO format
debug_polling ("%s - Entry WPGBbar[%p] index[%x] \n", __func__, WPGBbar, index);
//--------------------------------------------------------------------
// READ - step 1
// read at address, byte length, I2C address (shifted), index
// or read direct, byte length, index
if (ctlr_ptr->ctlr_type == 0x02) {
data = WPG_READATADDR_MASK;
// fill in I2C address
ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr;
ultemp = ultemp >> 1;
data |= (ultemp << 8);
// fill in index
data |= (unsigned long)index;
} else if (ctlr_ptr->ctlr_type == 0x04) {
data = WPG_READDIRECT_MASK;
// fill in index
ultemp = (unsigned long)index;
ultemp = ultemp << 8;
data |= ultemp;
} else {
err ("this controller type is not supported \n");
return HPC_ERROR;
}
wpg_data = swab32 (data); // swap data before writing
wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 2 : clear the message buffer
data = 0x00000000;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 3 : issue start operation, I2C master control bit 30:ON
// 2020 : [20] OR operation at [20] offset 0x20
data = WPG_I2CMCNTL_STARTOP_MASK;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// READ - step 4 : wait until start operation bit clears
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (!(data & WPG_I2CMCNTL_STARTOP_MASK))
break;
i--;
}
if (i == 0) {
debug ("%s - Error : WPG timeout\n", __func__);
return HPC_ERROR;
}
//--------------------------------------------------------------------
// READ - step 5 : read I2C status register
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (HPC_I2CSTATUS_CHECK (data))
break;
i--;
}
if (i == 0) {
debug ("ctrl_read - Exit Error:I2C timeout\n");
return HPC_ERROR;
}
//--------------------------------------------------------------------
// READ - step 6 : get DATA
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
status = (u8) data;
debug_polling ("%s - Exit index[%x] status[%x]\n", __func__, index, status);
return (status);
}
/*----------------------------------------------------------------------
* Name: i2c_ctrl_write
*
* Action: write to HPC over I2C
*
* Return 0 or error codes
*---------------------------------------------------------------------*/
static u8 i2c_ctrl_write (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index, u8 cmd)
{
u8 rc;
void __iomem *wpg_addr; // base addr + offset
unsigned long wpg_data; // data to/from WPG LOHI format
unsigned long ultemp;
unsigned long data; // actual data HILO format
int i;
debug_polling ("%s - Entry WPGBbar[%p] index[%x] cmd[%x]\n", __func__, WPGBbar, index, cmd);
rc = 0;
//--------------------------------------------------------------------
// WRITE - step 1
// write at address, byte length, I2C address (shifted), index
// or write direct, byte length, index
data = 0x00000000;
if (ctlr_ptr->ctlr_type == 0x02) {
data = WPG_WRITEATADDR_MASK;
// fill in I2C address
ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr;
ultemp = ultemp >> 1;
data |= (ultemp << 8);
// fill in index
data |= (unsigned long)index;
} else if (ctlr_ptr->ctlr_type == 0x04) {
data = WPG_WRITEDIRECT_MASK;
// fill in index
ultemp = (unsigned long)index;
ultemp = ultemp << 8;
data |= ultemp;
} else {
err ("this controller type is not supported \n");
return HPC_ERROR;
}
wpg_data = swab32 (data); // swap data before writing
wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 2 : clear the message buffer
data = 0x00000000 | (unsigned long)cmd;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 3 : issue start operation,I2C master control bit 30:ON
// 2020 : [20] OR operation at [20] offset 0x20
data = WPG_I2CMCNTL_STARTOP_MASK;
wpg_data = swab32 (data);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR;
writel (wpg_data, wpg_addr);
//--------------------------------------------------------------------
// WRITE - step 4 : wait until start operation bit clears
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (!(data & WPG_I2CMCNTL_STARTOP_MASK))
break;
i--;
}
if (i == 0) {
debug ("%s - Exit Error:WPG timeout\n", __func__);
rc = HPC_ERROR;
}
//--------------------------------------------------------------------
// WRITE - step 5 : read I2C status register
i = CMD_COMPLETE_TOUT_SEC;
while (i) {
msleep(10);
wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET;
wpg_data = readl (wpg_addr);
data = swab32 (wpg_data);
if (HPC_I2CSTATUS_CHECK (data))
break;
i--;
}
if (i == 0) {
debug ("ctrl_read - Error : I2C timeout\n");
rc = HPC_ERROR;
}
debug_polling ("%s Exit rc[%x]\n", __func__, rc);
return (rc);
}
//------------------------------------------------------------
// Read from ISA type HPC
//------------------------------------------------------------
static u8 isa_ctrl_read (struct controller *ctlr_ptr, u8 offset)
{
u16 start_address;
u16 end_address;
u8 data;
start_address = ctlr_ptr->u.isa_ctlr.io_start;
end_address = ctlr_ptr->u.isa_ctlr.io_end;
data = inb (start_address + offset);
return data;
}
//--------------------------------------------------------------
// Write to ISA type HPC
//--------------------------------------------------------------
static void isa_ctrl_write (struct controller *ctlr_ptr, u8 offset, u8 data)
{
u16 start_address;
u16 port_address;
start_address = ctlr_ptr->u.isa_ctlr.io_start;
port_address = start_address + (u16) offset;
outb (data, port_address);
}
static u8 pci_ctrl_read (struct controller *ctrl, u8 offset)
{
u8 data = 0x00;
debug ("inside pci_ctrl_read\n");
if (ctrl->ctrl_dev)
pci_read_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, &data);
return data;
}
static u8 pci_ctrl_write (struct controller *ctrl, u8 offset, u8 data)
{
u8 rc = -ENODEV;
debug ("inside pci_ctrl_write\n");
if (ctrl->ctrl_dev) {
pci_write_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, data);
rc = 0;
}
return rc;
}
static u8 ctrl_read (struct controller *ctlr, void __iomem *base, u8 offset)
{
u8 rc;
switch (ctlr->ctlr_type) {
case 0:
rc = isa_ctrl_read (ctlr, offset);
break;
case 1:
rc = pci_ctrl_read (ctlr, offset);
break;
case 2:
case 4:
rc = i2c_ctrl_read (ctlr, base, offset);
break;
default:
return -ENODEV;
}
return rc;
}
static u8 ctrl_write (struct controller *ctlr, void __iomem *base, u8 offset, u8 data)
{
u8 rc = 0;
switch (ctlr->ctlr_type) {
case 0:
isa_ctrl_write(ctlr, offset, data);
break;
case 1:
rc = pci_ctrl_write (ctlr, offset, data);
break;
case 2:
case 4:
rc = i2c_ctrl_write(ctlr, base, offset, data);
break;
default:
return -ENODEV;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: hpc_writecmdtoindex()
*
* Action: convert a write command to proper index within a controller
*
* Return index, HPC_ERROR
*---------------------------------------------------------------------*/
static u8 hpc_writecmdtoindex (u8 cmd, u8 index)
{
u8 rc;
switch (cmd) {
case HPC_CTLR_ENABLEIRQ: // 0x00.N.15
case HPC_CTLR_CLEARIRQ: // 0x06.N.15
case HPC_CTLR_RESET: // 0x07.N.15
case HPC_CTLR_IRQSTEER: // 0x08.N.15
case HPC_CTLR_DISABLEIRQ: // 0x01.N.15
case HPC_ALLSLOT_ON: // 0x11.N.15
case HPC_ALLSLOT_OFF: // 0x12.N.15
rc = 0x0F;
break;
case HPC_SLOT_OFF: // 0x02.Y.0-14
case HPC_SLOT_ON: // 0x03.Y.0-14
case HPC_SLOT_ATTNOFF: // 0x04.N.0-14
case HPC_SLOT_ATTNON: // 0x05.N.0-14
case HPC_SLOT_BLINKLED: // 0x13.N.0-14
rc = index;
break;
case HPC_BUS_33CONVMODE:
case HPC_BUS_66CONVMODE:
case HPC_BUS_66PCIXMODE:
case HPC_BUS_100PCIXMODE:
case HPC_BUS_133PCIXMODE:
rc = index + WPG_1ST_BUS_INDEX - 1;
break;
default:
err ("hpc_writecmdtoindex - Error invalid cmd[%x]\n", cmd);
rc = HPC_ERROR;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: hpc_readcmdtoindex()
*
* Action: convert a read command to proper index within a controller
*
* Return index, HPC_ERROR
*---------------------------------------------------------------------*/
static u8 hpc_readcmdtoindex (u8 cmd, u8 index)
{
u8 rc;
switch (cmd) {
case READ_CTLRSTATUS:
rc = 0x0F;
break;
case READ_SLOTSTATUS:
case READ_ALLSTAT:
rc = index;
break;
case READ_EXTSLOTSTATUS:
rc = index + WPG_1ST_EXTSLOT_INDEX;
break;
case READ_BUSSTATUS:
rc = index + WPG_1ST_BUS_INDEX - 1;
break;
case READ_SLOTLATCHLOWREG:
rc = 0x28;
break;
case READ_REVLEVEL:
rc = 0x25;
break;
case READ_HPCOPTIONS:
rc = 0x27;
break;
default:
rc = HPC_ERROR;
}
return rc;
}
/*----------------------------------------------------------------------
* Name: HPCreadslot()
*
* Action: issue a READ command to HPC
*
* Input: pslot - cannot be NULL for READ_ALLSTAT
* pstatus - can be NULL for READ_ALLSTAT
*
* Return 0 or error codes
*---------------------------------------------------------------------*/
int ibmphp_hpc_readslot (struct slot * pslot, u8 cmd, u8 * pstatus)
{
void __iomem *wpg_bbar = NULL;
struct controller *ctlr_ptr;
struct list_head *pslotlist;
u8 index, status;
int rc = 0;
int busindex;
debug_polling ("%s - Entry pslot[%p] cmd[%x] pstatus[%p]\n", __func__, pslot, cmd, pstatus);
if ((pslot == NULL)
|| ((pstatus == NULL) && (cmd != READ_ALLSTAT) && (cmd != READ_BUSSTATUS))) {
rc = -EINVAL;
err ("%s - Error invalid pointer, rc[%d]\n", __func__, rc);
return rc;
}
if (cmd == READ_BUSSTATUS) {
busindex = ibmphp_get_bus_index (pslot->bus);
if (busindex < 0) {
rc = -EINVAL;
err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc);
return rc;
} else
index = (u8) busindex;
} else
index = pslot->ctlr_index;
index = hpc_readcmdtoindex (cmd, index);
if (index == HPC_ERROR) {
rc = -EINVAL;
err ("%s - Exit Error:invalid index, rc[%d]\n", __func__, rc);
return rc;
}
ctlr_ptr = pslot->ctrl;
get_hpc_access ();
//--------------------------------------------------------------------
// map physical address to logical address
//--------------------------------------------------------------------
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE);
//--------------------------------------------------------------------
// check controller status before reading
//--------------------------------------------------------------------
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status);
if (!rc) {
switch (cmd) {
case READ_ALLSTAT:
// update the slot structure
pslot->ctrl->status = status;
pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index);
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar,
&status);
if (!rc)
pslot->ext_status = ctrl_read (ctlr_ptr, wpg_bbar, index + WPG_1ST_EXTSLOT_INDEX);
break;
case READ_SLOTSTATUS:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_EXTSLOTSTATUS:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_CTLRSTATUS:
// DO NOT update the slot structure
*pstatus = status;
break;
case READ_BUSSTATUS:
pslot->busstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_REVLEVEL:
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_HPCOPTIONS:
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
case READ_SLOTLATCHLOWREG:
// DO NOT update the slot structure
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index);
break;
// Not used
case READ_ALLSLOT:
list_for_each (pslotlist, &ibmphp_slot_head) {
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
index = pslot->ctlr_index;
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr,
wpg_bbar, &status);
if (!rc) {
pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index);
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT,
ctlr_ptr, wpg_bbar, &status);
if (!rc)
pslot->ext_status =
ctrl_read (ctlr_ptr, wpg_bbar,
index + WPG_1ST_EXTSLOT_INDEX);
} else {
err ("%s - Error ctrl_read failed\n", __func__);
rc = -EINVAL;
break;
}
}
break;
default:
rc = -EINVAL;
break;
}
}
//--------------------------------------------------------------------
// cleanup
//--------------------------------------------------------------------
// remove physical to logical address mapping
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
iounmap (wpg_bbar);
free_hpc_access ();
debug_polling ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_writeslot()
*
* Action: issue a WRITE command to HPC
*---------------------------------------------------------------------*/
int ibmphp_hpc_writeslot (struct slot * pslot, u8 cmd)
{
void __iomem *wpg_bbar = NULL;
struct controller *ctlr_ptr;
u8 index, status;
int busindex;
u8 done;
int rc = 0;
int timeout;
debug_polling ("%s - Entry pslot[%p] cmd[%x]\n", __func__, pslot, cmd);
if (pslot == NULL) {
rc = -EINVAL;
err ("%s - Error Exit rc[%d]\n", __func__, rc);
return rc;
}
if ((cmd == HPC_BUS_33CONVMODE) || (cmd == HPC_BUS_66CONVMODE) ||
(cmd == HPC_BUS_66PCIXMODE) || (cmd == HPC_BUS_100PCIXMODE) ||
(cmd == HPC_BUS_133PCIXMODE)) {
busindex = ibmphp_get_bus_index (pslot->bus);
if (busindex < 0) {
rc = -EINVAL;
err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc);
return rc;
} else
index = (u8) busindex;
} else
index = pslot->ctlr_index;
index = hpc_writecmdtoindex (cmd, index);
if (index == HPC_ERROR) {
rc = -EINVAL;
err ("%s - Error Exit rc[%d]\n", __func__, rc);
return rc;
}
ctlr_ptr = pslot->ctrl;
get_hpc_access ();
//--------------------------------------------------------------------
// map physical address to logical address
//--------------------------------------------------------------------
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) {
wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE);
debug ("%s - ctlr id[%x] physical[%lx] logical[%lx] i2c[%x]\n", __func__,
ctlr_ptr->ctlr_id, (ulong) (ctlr_ptr->u.wpeg_ctlr.wpegbbar), (ulong) wpg_bbar,
ctlr_ptr->u.wpeg_ctlr.i2c_addr);
}
//--------------------------------------------------------------------
// check controller status before writing
//--------------------------------------------------------------------
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status);
if (!rc) {
ctrl_write (ctlr_ptr, wpg_bbar, index, cmd);
//--------------------------------------------------------------------
// check controller is still not working on the command
//--------------------------------------------------------------------
timeout = CMD_COMPLETE_TOUT_SEC;
done = 0;
while (!done) {
rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar,
&status);
if (!rc) {
if (NEEDTOCHECK_CMDSTATUS (cmd)) {
if (CTLR_FINISHED (status) == HPC_CTLR_FINISHED_YES)
done = 1;
} else
done = 1;
}
if (!done) {
msleep(1000);
if (timeout < 1) {
done = 1;
err ("%s - Error command complete timeout\n", __func__);
rc = -EFAULT;
} else
timeout--;
}
}
ctlr_ptr->status = status;
}
// cleanup
// remove physical to logical address mapping
if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4))
iounmap (wpg_bbar);
free_hpc_access ();
debug_polling ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: get_hpc_access()
*
* Action: make sure only one process can access HPC at one time
*---------------------------------------------------------------------*/
static void get_hpc_access (void)
{
mutex_lock(&sem_hpcaccess);
}
/*----------------------------------------------------------------------
* Name: free_hpc_access()
*---------------------------------------------------------------------*/
void free_hpc_access (void)
{
mutex_unlock(&sem_hpcaccess);
}
/*----------------------------------------------------------------------
* Name: ibmphp_lock_operations()
*
* Action: make sure only one process can change the data structure
*---------------------------------------------------------------------*/
void ibmphp_lock_operations (void)
{
down (&semOperations);
to_debug = 1;
}
/*----------------------------------------------------------------------
* Name: ibmphp_unlock_operations()
*---------------------------------------------------------------------*/
void ibmphp_unlock_operations (void)
{
debug ("%s - Entry\n", __func__);
up (&semOperations);
to_debug = 0;
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: poll_hpc()
*---------------------------------------------------------------------*/
#define POLL_LATCH_REGISTER 0
#define POLL_SLOTS 1
#define POLL_SLEEP 2
static int poll_hpc(void *data)
{
struct slot myslot;
struct slot *pslot = NULL;
struct list_head *pslotlist;
int rc;
int poll_state = POLL_LATCH_REGISTER;
u8 oldlatchlow = 0x00;
u8 curlatchlow = 0x00;
int poll_count = 0;
u8 ctrl_count = 0x00;
debug ("%s - Entry\n", __func__);
while (!kthread_should_stop()) {
/* try to get the lock to do some kind of hardware access */
down (&semOperations);
switch (poll_state) {
case POLL_LATCH_REGISTER:
oldlatchlow = curlatchlow;
ctrl_count = 0x00;
list_for_each (pslotlist, &ibmphp_slot_head) {
if (ctrl_count >= ibmphp_get_total_controllers())
break;
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
if (pslot->ctrl->ctlr_relative_id == ctrl_count) {
ctrl_count++;
if (READ_SLOT_LATCH (pslot->ctrl)) {
rc = ibmphp_hpc_readslot (pslot,
READ_SLOTLATCHLOWREG,
&curlatchlow);
if (oldlatchlow != curlatchlow)
process_changeinlatch (oldlatchlow,
curlatchlow,
pslot->ctrl);
}
}
}
++poll_count;
poll_state = POLL_SLEEP;
break;
case POLL_SLOTS:
list_for_each (pslotlist, &ibmphp_slot_head) {
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
// make a copy of the old status
memcpy ((void *) &myslot, (void *) pslot,
sizeof (struct slot));
rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL);
if ((myslot.status != pslot->status)
|| (myslot.ext_status != pslot->ext_status))
process_changeinstatus (pslot, &myslot);
}
ctrl_count = 0x00;
list_for_each (pslotlist, &ibmphp_slot_head) {
if (ctrl_count >= ibmphp_get_total_controllers())
break;
pslot = list_entry (pslotlist, struct slot, ibm_slot_list);
if (pslot->ctrl->ctlr_relative_id == ctrl_count) {
ctrl_count++;
if (READ_SLOT_LATCH (pslot->ctrl))
rc = ibmphp_hpc_readslot (pslot,
READ_SLOTLATCHLOWREG,
&curlatchlow);
}
}
++poll_count;
poll_state = POLL_SLEEP;
break;
case POLL_SLEEP:
/* don't sleep with a lock on the hardware */
up (&semOperations);
msleep(POLL_INTERVAL_SEC * 1000);
if (kthread_should_stop())
goto out_sleep;
down (&semOperations);
if (poll_count >= POLL_LATCH_CNT) {
poll_count = 0;
poll_state = POLL_SLOTS;
} else
poll_state = POLL_LATCH_REGISTER;
break;
}
/* give up the hardware semaphore */
up (&semOperations);
/* sleep for a short time just for good measure */
out_sleep:
msleep(100);
}
up (&sem_exit);
debug ("%s - Exit\n", __func__);
return 0;
}
/*----------------------------------------------------------------------
* Name: process_changeinstatus
*
* Action: compare old and new slot status, process the change in status
*
* Input: pointer to slot struct, old slot struct
*
* Return 0 or error codes
* Value:
*
* Side
* Effects: None.
*
* Notes:
*---------------------------------------------------------------------*/
static int process_changeinstatus (struct slot *pslot, struct slot *poldslot)
{
u8 status;
int rc = 0;
u8 disable = 0;
u8 update = 0;
debug ("process_changeinstatus - Entry pslot[%p], poldslot[%p]\n", pslot, poldslot);
// bit 0 - HPC_SLOT_POWER
if ((pslot->status & 0x01) != (poldslot->status & 0x01))
update = 1;
// bit 1 - HPC_SLOT_CONNECT
// ignore
// bit 2 - HPC_SLOT_ATTN
if ((pslot->status & 0x04) != (poldslot->status & 0x04))
update = 1;
// bit 3 - HPC_SLOT_PRSNT2
// bit 4 - HPC_SLOT_PRSNT1
if (((pslot->status & 0x08) != (poldslot->status & 0x08))
|| ((pslot->status & 0x10) != (poldslot->status & 0x10)))
update = 1;
// bit 5 - HPC_SLOT_PWRGD
if ((pslot->status & 0x20) != (poldslot->status & 0x20))
// OFF -> ON: ignore, ON -> OFF: disable slot
if ((poldslot->status & 0x20) && (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status)))
disable = 1;
// bit 6 - HPC_SLOT_BUS_SPEED
// ignore
// bit 7 - HPC_SLOT_LATCH
if ((pslot->status & 0x80) != (poldslot->status & 0x80)) {
update = 1;
// OPEN -> CLOSE
if (pslot->status & 0x80) {
if (SLOT_PWRGD (pslot->status)) {
// power goes on and off after closing latch
// check again to make sure power is still ON
msleep(1000);
rc = ibmphp_hpc_readslot (pslot, READ_SLOTSTATUS, &status);
if (SLOT_PWRGD (status))
update = 1;
else // overwrite power in pslot to OFF
pslot->status &= ~HPC_SLOT_POWER;
}
}
// CLOSE -> OPEN
else if ((SLOT_PWRGD (poldslot->status) == HPC_SLOT_PWRGD_GOOD)
&& (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status))) {
disable = 1;
}
// else - ignore
}
// bit 4 - HPC_SLOT_BLINK_ATTN
if ((pslot->ext_status & 0x08) != (poldslot->ext_status & 0x08))
update = 1;
if (disable) {
debug ("process_changeinstatus - disable slot\n");
pslot->flag = 0;
rc = ibmphp_do_disable_slot (pslot);
}
if (update || disable) {
ibmphp_update_slot_info (pslot);
}
debug ("%s - Exit rc[%d] disable[%x] update[%x]\n", __func__, rc, disable, update);
return rc;
}
/*----------------------------------------------------------------------
* Name: process_changeinlatch
*
* Action: compare old and new latch reg status, process the change
*
* Input: old and current latch register status
*
* Return 0 or error codes
* Value:
*---------------------------------------------------------------------*/
static int process_changeinlatch (u8 old, u8 new, struct controller *ctrl)
{
struct slot myslot, *pslot;
u8 i;
u8 mask;
int rc = 0;
debug ("%s - Entry old[%x], new[%x]\n", __func__, old, new);
// bit 0 reserved, 0 is LSB, check bit 1-6 for 6 slots
for (i = ctrl->starting_slot_num; i <= ctrl->ending_slot_num; i++) {
mask = 0x01 << i;
if ((mask & old) != (mask & new)) {
pslot = ibmphp_get_slot_from_physical_num (i);
if (pslot) {
memcpy ((void *) &myslot, (void *) pslot, sizeof (struct slot));
rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL);
debug ("%s - call process_changeinstatus for slot[%d]\n", __func__, i);
process_changeinstatus (pslot, &myslot);
} else {
rc = -EINVAL;
err ("%s - Error bad pointer for slot[%d]\n", __func__, i);
}
}
}
debug ("%s - Exit rc[%d]\n", __func__, rc);
return rc;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_start_poll_thread
*
* Action: start polling thread
*---------------------------------------------------------------------*/
int __init ibmphp_hpc_start_poll_thread (void)
{
debug ("%s - Entry\n", __func__);
ibmphp_poll_thread = kthread_run(poll_hpc, NULL, "hpc_poll");
if (IS_ERR(ibmphp_poll_thread)) {
err ("%s - Error, thread not started\n", __func__);
return PTR_ERR(ibmphp_poll_thread);
}
return 0;
}
/*----------------------------------------------------------------------
* Name: ibmphp_hpc_stop_poll_thread
*
* Action: stop polling thread and cleanup
*---------------------------------------------------------------------*/
void __exit ibmphp_hpc_stop_poll_thread (void)
{
debug ("%s - Entry\n", __func__);
kthread_stop(ibmphp_poll_thread);
debug ("before locking operations \n");
ibmphp_lock_operations ();
debug ("after locking operations \n");
// wait for poll thread to exit
debug ("before sem_exit down \n");
down (&sem_exit);
debug ("after sem_exit down \n");
// cleanup
debug ("before free_hpc_access \n");
free_hpc_access ();
debug ("after free_hpc_access \n");
ibmphp_unlock_operations ();
debug ("after unlock operations \n");
up (&sem_exit);
debug ("after sem exit up\n");
debug ("%s - Exit\n", __func__);
}
/*----------------------------------------------------------------------
* Name: hpc_wait_ctlr_notworking
*
* Action: wait until the controller is in a not working state
*
* Return 0, HPC_ERROR
* Value:
*---------------------------------------------------------------------*/
static int hpc_wait_ctlr_notworking (int timeout, struct controller *ctlr_ptr, void __iomem *wpg_bbar,
u8 * pstatus)
{
int rc = 0;
u8 done = 0;
debug_polling ("hpc_wait_ctlr_notworking - Entry timeout[%d]\n", timeout);
while (!done) {
*pstatus = ctrl_read (ctlr_ptr, wpg_bbar, WPG_CTLR_INDEX);
if (*pstatus == HPC_ERROR) {
rc = HPC_ERROR;
done = 1;
}
if (CTLR_WORKING (*pstatus) == HPC_CTLR_WORKING_NO)
done = 1;
if (!done) {
msleep(1000);
if (timeout < 1) {
done = 1;
err ("HPCreadslot - Error ctlr timeout\n");
rc = HPC_ERROR;
} else
timeout--;
}
}
debug_polling ("hpc_wait_ctlr_notworking - Exit rc[%x] status[%x]\n", rc, *pstatus);
return rc;
}
| apache-2.0 |
aayushkapoor206/whatshot | node_modules/node-sass/src/libsass/src/sass_values.cpp | 225 | 14274 | #include <cstdlib>
#include <cstring>
#include "util.hpp"
#include "eval.hpp"
#include "values.hpp"
#include "sass/values.h"
#include "sass_values.hpp"
extern "C" {
using namespace Sass;
// Return the sass tag for a generic sass value
enum Sass_Tag ADDCALL sass_value_get_tag(const union Sass_Value* v) { return v->unknown.tag; }
// Check value for specified type
bool ADDCALL sass_value_is_null(const union Sass_Value* v) { return v->unknown.tag == SASS_NULL; }
bool ADDCALL sass_value_is_number(const union Sass_Value* v) { return v->unknown.tag == SASS_NUMBER; }
bool ADDCALL sass_value_is_string(const union Sass_Value* v) { return v->unknown.tag == SASS_STRING; }
bool ADDCALL sass_value_is_boolean(const union Sass_Value* v) { return v->unknown.tag == SASS_BOOLEAN; }
bool ADDCALL sass_value_is_color(const union Sass_Value* v) { return v->unknown.tag == SASS_COLOR; }
bool ADDCALL sass_value_is_list(const union Sass_Value* v) { return v->unknown.tag == SASS_LIST; }
bool ADDCALL sass_value_is_map(const union Sass_Value* v) { return v->unknown.tag == SASS_MAP; }
bool ADDCALL sass_value_is_error(const union Sass_Value* v) { return v->unknown.tag == SASS_ERROR; }
bool ADDCALL sass_value_is_warning(const union Sass_Value* v) { return v->unknown.tag == SASS_WARNING; }
// Getters and setters for Sass_Number
double ADDCALL sass_number_get_value(const union Sass_Value* v) { return v->number.value; }
void ADDCALL sass_number_set_value(union Sass_Value* v, double value) { v->number.value = value; }
const char* ADDCALL sass_number_get_unit(const union Sass_Value* v) { return v->number.unit; }
void ADDCALL sass_number_set_unit(union Sass_Value* v, char* unit) { v->number.unit = unit; }
// Getters and setters for Sass_String
const char* ADDCALL sass_string_get_value(const union Sass_Value* v) { return v->string.value; }
void ADDCALL sass_string_set_value(union Sass_Value* v, char* value) { v->string.value = value; }
bool ADDCALL sass_string_is_quoted(const union Sass_Value* v) { return v->string.quoted; }
void ADDCALL sass_string_set_quoted(union Sass_Value* v, bool quoted) { v->string.quoted = quoted; }
// Getters and setters for Sass_Boolean
bool ADDCALL sass_boolean_get_value(const union Sass_Value* v) { return v->boolean.value; }
void ADDCALL sass_boolean_set_value(union Sass_Value* v, bool value) { v->boolean.value = value; }
// Getters and setters for Sass_Color
double ADDCALL sass_color_get_r(const union Sass_Value* v) { return v->color.r; }
void ADDCALL sass_color_set_r(union Sass_Value* v, double r) { v->color.r = r; }
double ADDCALL sass_color_get_g(const union Sass_Value* v) { return v->color.g; }
void ADDCALL sass_color_set_g(union Sass_Value* v, double g) { v->color.g = g; }
double ADDCALL sass_color_get_b(const union Sass_Value* v) { return v->color.b; }
void ADDCALL sass_color_set_b(union Sass_Value* v, double b) { v->color.b = b; }
double ADDCALL sass_color_get_a(const union Sass_Value* v) { return v->color.a; }
void ADDCALL sass_color_set_a(union Sass_Value* v, double a) { v->color.a = a; }
// Getters and setters for Sass_List
size_t ADDCALL sass_list_get_length(const union Sass_Value* v) { return v->list.length; }
enum Sass_Separator ADDCALL sass_list_get_separator(const union Sass_Value* v) { return v->list.separator; }
void ADDCALL sass_list_set_separator(union Sass_Value* v, enum Sass_Separator separator) { v->list.separator = separator; }
// Getters and setters for Sass_List values
union Sass_Value* ADDCALL sass_list_get_value(const union Sass_Value* v, size_t i) { return v->list.values[i]; }
void ADDCALL sass_list_set_value(union Sass_Value* v, size_t i, union Sass_Value* value) { v->list.values[i] = value; }
// Getters and setters for Sass_Map
size_t ADDCALL sass_map_get_length(const union Sass_Value* v) { return v->map.length; }
// Getters and setters for Sass_List keys and values
union Sass_Value* ADDCALL sass_map_get_key(const union Sass_Value* v, size_t i) { return v->map.pairs[i].key; }
union Sass_Value* ADDCALL sass_map_get_value(const union Sass_Value* v, size_t i) { return v->map.pairs[i].value; }
void ADDCALL sass_map_set_key(union Sass_Value* v, size_t i, union Sass_Value* key) { v->map.pairs[i].key = key; }
void ADDCALL sass_map_set_value(union Sass_Value* v, size_t i, union Sass_Value* val) { v->map.pairs[i].value = val; }
// Getters and setters for Sass_Error
char* ADDCALL sass_error_get_message(const union Sass_Value* v) { return v->error.message; };
void ADDCALL sass_error_set_message(union Sass_Value* v, char* msg) { v->error.message = msg; };
// Getters and setters for Sass_Warning
char* ADDCALL sass_warning_get_message(const union Sass_Value* v) { return v->warning.message; };
void ADDCALL sass_warning_set_message(union Sass_Value* v, char* msg) { v->warning.message = msg; };
// Creator functions for all value types
union Sass_Value* ADDCALL sass_make_boolean(bool val)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->boolean.tag = SASS_BOOLEAN;
v->boolean.value = val;
return v;
}
union Sass_Value* ADDCALL sass_make_number(double val, const char* unit)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->number.tag = SASS_NUMBER;
v->number.value = val;
v->number.unit = unit ? sass_strdup(unit) : 0;
if (v->number.unit == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_color(double r, double g, double b, double a)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->color.tag = SASS_COLOR;
v->color.r = r;
v->color.g = g;
v->color.b = b;
v->color.a = a;
return v;
}
union Sass_Value* ADDCALL sass_make_string(const char* val)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->string.quoted = false;
v->string.tag = SASS_STRING;
v->string.value = val ? sass_strdup(val) : 0;
if (v->string.value == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_qstring(const char* val)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->string.quoted = true;
v->string.tag = SASS_STRING;
v->string.value = val ? sass_strdup(val) : 0;
if (v->string.value == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_list(size_t len, enum Sass_Separator sep)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->list.tag = SASS_LIST;
v->list.length = len;
v->list.separator = sep;
v->list.values = (union Sass_Value**) calloc(len, sizeof(union Sass_Value*));
if (v->list.values == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_map(size_t len)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->map.tag = SASS_MAP;
v->map.length = len;
v->map.pairs = (struct Sass_MapPair*) calloc(len, sizeof(struct Sass_MapPair));
if (v->map.pairs == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_null(void)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->null.tag = SASS_NULL;
return v;
}
union Sass_Value* ADDCALL sass_make_error(const char* msg)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->error.tag = SASS_ERROR;
v->error.message = msg ? sass_strdup(msg) : 0;
if (v->error.message == 0) { free(v); return 0; }
return v;
}
union Sass_Value* ADDCALL sass_make_warning(const char* msg)
{
union Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value));
if (v == 0) return 0;
v->warning.tag = SASS_WARNING;
v->warning.message = msg ? sass_strdup(msg) : 0;
if (v->warning.message == 0) { free(v); return 0; }
return v;
}
// will free all associated sass values
void ADDCALL sass_delete_value(union Sass_Value* val) {
size_t i;
if (val == 0) return;
switch(val->unknown.tag) {
case SASS_NULL: {
} break;
case SASS_BOOLEAN: {
} break;
case SASS_NUMBER: {
free(val->number.unit);
} break;
case SASS_COLOR: {
} break;
case SASS_STRING: {
free(val->string.value);
} break;
case SASS_LIST: {
for (i=0; i<val->list.length; i++) {
sass_delete_value(val->list.values[i]);
}
free(val->list.values);
} break;
case SASS_MAP: {
for (i=0; i<val->map.length; i++) {
sass_delete_value(val->map.pairs[i].key);
sass_delete_value(val->map.pairs[i].value);
}
free(val->map.pairs);
} break;
case SASS_ERROR: {
free(val->error.message);
} break;
case SASS_WARNING: {
free(val->error.message);
} break;
}
free(val);
}
// Make a deep cloned copy of the given sass value
union Sass_Value* ADDCALL sass_clone_value (const union Sass_Value* val)
{
size_t i;
if (val == 0) return 0;
switch(val->unknown.tag) {
case SASS_NULL: {
return sass_make_null();
} break;
case SASS_BOOLEAN: {
return sass_make_boolean(val->boolean.value);
} break;
case SASS_NUMBER: {
return sass_make_number(val->number.value, val->number.unit);
} break;
case SASS_COLOR: {
return sass_make_color(val->color.r, val->color.g, val->color.b, val->color.a);
} break;
case SASS_STRING: {
return sass_string_is_quoted(val) ? sass_make_qstring(val->string.value) : sass_make_string(val->string.value);
} break;
case SASS_LIST: {
union Sass_Value* list = sass_make_list(val->list.length, val->list.separator);
for (i = 0; i < list->list.length; i++) {
list->list.values[i] = sass_clone_value(val->list.values[i]);
}
return list;
} break;
case SASS_MAP: {
union Sass_Value* map = sass_make_map(val->map.length);
for (i = 0; i < val->map.length; i++) {
map->map.pairs[i].key = sass_clone_value(val->map.pairs[i].key);
map->map.pairs[i].value = sass_clone_value(val->map.pairs[i].value);
}
return map;
} break;
case SASS_ERROR: {
return sass_make_error(val->error.message);
} break;
case SASS_WARNING: {
return sass_make_warning(val->warning.message);
} break;
}
return 0;
}
union Sass_Value* ADDCALL sass_value_stringify (const union Sass_Value* v, bool compressed, int precision)
{
Memory_Manager mem;
Value* val = sass_value_to_ast_node(mem, v);
std::string str(val->to_string(compressed, precision));
return sass_make_qstring(str.c_str());
}
union Sass_Value* ADDCALL sass_value_op (enum Sass_OP op, const union Sass_Value* a, const union Sass_Value* b)
{
Sass::Value* rv = 0;
Memory_Manager mem;
try {
Value* lhs = sass_value_to_ast_node(mem, a);
Value* rhs = sass_value_to_ast_node(mem, b);
// see if it's a relational expression
switch(op) {
case Sass_OP::EQ: return sass_make_boolean(Eval::eq(lhs, rhs));
case Sass_OP::NEQ: return sass_make_boolean(!Eval::eq(lhs, rhs));
case Sass_OP::GT: return sass_make_boolean(!Eval::lt(lhs, rhs) && !Eval::eq(lhs, rhs));
case Sass_OP::GTE: return sass_make_boolean(!Eval::lt(lhs, rhs));
case Sass_OP::LT: return sass_make_boolean(Eval::lt(lhs, rhs));
case Sass_OP::LTE: return sass_make_boolean(Eval::lt(lhs, rhs) || Eval::eq(lhs, rhs));
default: break;
}
if (sass_value_is_number(a) && sass_value_is_number(b)) {
const Number* l_n = dynamic_cast<const Number*>(lhs);
const Number* r_n = dynamic_cast<const Number*>(rhs);
rv = Eval::op_numbers(mem, op, *l_n, *r_n);
}
else if (sass_value_is_number(a) && sass_value_is_color(a)) {
const Number* l_n = dynamic_cast<const Number*>(lhs);
const Color* r_c = dynamic_cast<const Color*>(rhs);
rv = Eval::op_number_color(mem, op, *l_n, *r_c);
}
else if (sass_value_is_color(a) && sass_value_is_number(b)) {
const Color* l_c = dynamic_cast<const Color*>(lhs);
const Number* r_n = dynamic_cast<const Number*>(rhs);
rv = Eval::op_color_number(mem, op, *l_c, *r_n);
}
else if (sass_value_is_color(a) && sass_value_is_color(b)) {
const Color* l_c = dynamic_cast<const Color*>(lhs);
const Color* r_c = dynamic_cast<const Color*>(rhs);
rv = Eval::op_colors(mem, op, *l_c, *r_c);
}
else /* convert other stuff to string and apply operation */ {
Value* l_v = dynamic_cast<Value*>(lhs);
Value* r_v = dynamic_cast<Value*>(rhs);
rv = Eval::op_strings(mem, op, *l_v, *r_v);
}
// ToDo: maybe we should should return null value?
if (!rv) return sass_make_error("invalid return value");
// convert result back to ast node
return ast_node_to_sass_value(rv);
}
// simply pass the error message back to the caller for now
catch (Exception::InvalidSass& e) { return sass_make_error(e.what()); }
catch (std::bad_alloc&) { return sass_make_error("memory exhausted"); }
catch (std::exception& e) { return sass_make_error(e.what()); }
catch (std::string& e) { return sass_make_error(e.c_str()); }
catch (const char* e) { return sass_make_error(e); }
catch (...) { return sass_make_error("unknown"); }
return 0;
}
}
| apache-2.0 |
goblinr/omim | 3party/icu/i18n/ethpccal.cpp | 235 | 5878 | /*
*******************************************************************************
* Copyright (C) 2003 - 2013, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "umutex.h"
#include "ethpccal.h"
#include "cecal.h"
#include <float.h>
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(EthiopicCalendar)
//static const int32_t JD_EPOCH_OFFSET_AMETE_ALEM = -285019;
static const int32_t JD_EPOCH_OFFSET_AMETE_MIHRET = 1723856;
static const int32_t AMETE_MIHRET_DELTA = 5500; // 5501 - 1 (Amete Alem 5501 = Amete Mihret 1)
//-------------------------------------------------------------------------
// Constructors...
//-------------------------------------------------------------------------
EthiopicCalendar::EthiopicCalendar(const Locale& aLocale,
UErrorCode& success,
EEraType type /*= AMETE_MIHRET_ERA*/)
: CECalendar(aLocale, success),
eraType(type)
{
}
EthiopicCalendar::EthiopicCalendar(const EthiopicCalendar& other)
: CECalendar(other),
eraType(other.eraType)
{
}
EthiopicCalendar::~EthiopicCalendar()
{
}
Calendar*
EthiopicCalendar::clone() const
{
return new EthiopicCalendar(*this);
}
const char *
EthiopicCalendar::getType() const
{
if (isAmeteAlemEra()) {
return "ethiopic-amete-alem";
}
return "ethiopic";
}
void
EthiopicCalendar::setAmeteAlemEra(UBool onOff)
{
eraType = onOff ? AMETE_ALEM_ERA : AMETE_MIHRET_ERA;
}
UBool
EthiopicCalendar::isAmeteAlemEra() const
{
return (eraType == AMETE_ALEM_ERA);
}
//-------------------------------------------------------------------------
// Calendar framework
//-------------------------------------------------------------------------
int32_t
EthiopicCalendar::handleGetExtendedYear()
{
// Ethiopic calendar uses EXTENDED_YEAR aligned to
// Amelete Hihret year always.
int32_t eyear;
if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
eyear = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
} else if (isAmeteAlemEra()) {
eyear = internalGet(UCAL_YEAR, 1 + AMETE_MIHRET_DELTA)
- AMETE_MIHRET_DELTA; // Default to year 1 of Amelete Mihret
} else {
// The year defaults to the epoch start, the era to AMETE_MIHRET
int32_t era = internalGet(UCAL_ERA, AMETE_MIHRET);
if (era == AMETE_MIHRET) {
eyear = internalGet(UCAL_YEAR, 1); // Default to year 1
} else {
eyear = internalGet(UCAL_YEAR, 1) - AMETE_MIHRET_DELTA;
}
}
return eyear;
}
void
EthiopicCalendar::handleComputeFields(int32_t julianDay, UErrorCode &/*status*/)
{
int32_t eyear, month, day, era, year;
jdToCE(julianDay, getJDEpochOffset(), eyear, month, day);
if (isAmeteAlemEra()) {
era = AMETE_ALEM;
year = eyear + AMETE_MIHRET_DELTA;
} else {
if (eyear > 0) {
era = AMETE_MIHRET;
year = eyear;
} else {
era = AMETE_ALEM;
year = eyear + AMETE_MIHRET_DELTA;
}
}
internalSet(UCAL_EXTENDED_YEAR, eyear);
internalSet(UCAL_ERA, era);
internalSet(UCAL_YEAR, year);
internalSet(UCAL_MONTH, month);
internalSet(UCAL_DATE, day);
internalSet(UCAL_DAY_OF_YEAR, (30 * month) + day);
}
int32_t
EthiopicCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const
{
if (isAmeteAlemEra() && field == UCAL_ERA) {
return 0; // Only one era in this mode, era is always 0
}
return CECalendar::handleGetLimit(field, limitType);
}
/**
* The system maintains a static default century start date and Year. They are
* initialized the first time they are used. Once the system default century date
* and year are set, they do not change.
*/
static UDate gSystemDefaultCenturyStart = DBL_MIN;
static int32_t gSystemDefaultCenturyStartYear = -1;
static icu::UInitOnce gSystemDefaultCenturyInit = U_INITONCE_INITIALIZER;
static void U_CALLCONV initializeSystemDefaultCentury()
{
UErrorCode status = U_ZERO_ERROR;
EthiopicCalendar calendar(Locale("@calendar=ethiopic"), status);
if (U_SUCCESS(status)) {
calendar.setTime(Calendar::getNow(), status);
calendar.add(UCAL_YEAR, -80, status);
gSystemDefaultCenturyStart = calendar.getTime(status);
gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
}
// We have no recourse upon failure unless we want to propagate the failure
// out.
}
UDate
EthiopicCalendar::defaultCenturyStart() const
{
// lazy-evaluate systemDefaultCenturyStart
umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
return gSystemDefaultCenturyStart;
}
int32_t
EthiopicCalendar::defaultCenturyStartYear() const
{
// lazy-evaluate systemDefaultCenturyStartYear
umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
if (isAmeteAlemEra()) {
return gSystemDefaultCenturyStartYear + AMETE_MIHRET_DELTA;
}
return gSystemDefaultCenturyStartYear;
}
int32_t
EthiopicCalendar::getJDEpochOffset() const
{
return JD_EPOCH_OFFSET_AMETE_MIHRET;
}
#if 0
// We do not want to introduce this API in ICU4C.
// It was accidentally introduced in ICU4J as a public API.
//-------------------------------------------------------------------------
// Calendar system Conversion methods...
//-------------------------------------------------------------------------
int32_t
EthiopicCalendar::ethiopicToJD(int32_t year, int32_t month, int32_t date)
{
return ceToJD(year, month, date, JD_EPOCH_OFFSET_AMETE_MIHRET);
}
#endif
U_NAMESPACE_END
#endif
| apache-2.0 |
michelborgess/RealOne-Victara-Kernel | samples/hidraw/hid-example.c | 8171 | 3905 | /*
* Hidraw Userspace Example
*
* Copyright (c) 2010 Alan Ott <alan@signal11.us>
* Copyright (c) 2010 Signal 11 Software
*
* The code may be used by anyone for any purpose,
* and can serve as a starting point for developing
* applications using hidraw.
*/
/* Linux */
#include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>
/*
* Ugly hack to work around failing compilation on systems that don't
* yet populate new version of hidraw.h to userspace.
*
* If you need this, please have your distro update the kernel headers.
*/
#ifndef HIDIOCSFEATURE
#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
#endif
/* Unix */
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
/* C */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
const char *bus_str(int bus);
int main(int argc, char **argv)
{
int fd;
int i, res, desc_size = 0;
char buf[256];
struct hidraw_report_descriptor rpt_desc;
struct hidraw_devinfo info;
/* Open the Device with non-blocking reads. In real life,
don't use a hard coded path; use libudev instead. */
fd = open("/dev/hidraw0", O_RDWR|O_NONBLOCK);
if (fd < 0) {
perror("Unable to open device");
return 1;
}
memset(&rpt_desc, 0x0, sizeof(rpt_desc));
memset(&info, 0x0, sizeof(info));
memset(buf, 0x0, sizeof(buf));
/* Get Report Descriptor Size */
res = ioctl(fd, HIDIOCGRDESCSIZE, &desc_size);
if (res < 0)
perror("HIDIOCGRDESCSIZE");
else
printf("Report Descriptor Size: %d\n", desc_size);
/* Get Report Descriptor */
rpt_desc.size = desc_size;
res = ioctl(fd, HIDIOCGRDESC, &rpt_desc);
if (res < 0) {
perror("HIDIOCGRDESC");
} else {
printf("Report Descriptor:\n");
for (i = 0; i < rpt_desc.size; i++)
printf("%hhx ", rpt_desc.value[i]);
puts("\n");
}
/* Get Raw Name */
res = ioctl(fd, HIDIOCGRAWNAME(256), buf);
if (res < 0)
perror("HIDIOCGRAWNAME");
else
printf("Raw Name: %s\n", buf);
/* Get Physical Location */
res = ioctl(fd, HIDIOCGRAWPHYS(256), buf);
if (res < 0)
perror("HIDIOCGRAWPHYS");
else
printf("Raw Phys: %s\n", buf);
/* Get Raw Info */
res = ioctl(fd, HIDIOCGRAWINFO, &info);
if (res < 0) {
perror("HIDIOCGRAWINFO");
} else {
printf("Raw Info:\n");
printf("\tbustype: %d (%s)\n",
info.bustype, bus_str(info.bustype));
printf("\tvendor: 0x%04hx\n", info.vendor);
printf("\tproduct: 0x%04hx\n", info.product);
}
/* Set Feature */
buf[0] = 0x9; /* Report Number */
buf[1] = 0xff;
buf[2] = 0xff;
buf[3] = 0xff;
res = ioctl(fd, HIDIOCSFEATURE(4), buf);
if (res < 0)
perror("HIDIOCSFEATURE");
else
printf("ioctl HIDIOCGFEATURE returned: %d\n", res);
/* Get Feature */
buf[0] = 0x9; /* Report Number */
res = ioctl(fd, HIDIOCGFEATURE(256), buf);
if (res < 0) {
perror("HIDIOCGFEATURE");
} else {
printf("ioctl HIDIOCGFEATURE returned: %d\n", res);
printf("Report data (not containing the report number):\n\t");
for (i = 0; i < res; i++)
printf("%hhx ", buf[i]);
puts("\n");
}
/* Send a Report to the Device */
buf[0] = 0x1; /* Report Number */
buf[1] = 0x77;
res = write(fd, buf, 2);
if (res < 0) {
printf("Error: %d\n", errno);
perror("write");
} else {
printf("write() wrote %d bytes\n", res);
}
/* Get a report from the device */
res = read(fd, buf, 16);
if (res < 0) {
perror("read");
} else {
printf("read() read %d bytes:\n\t", res);
for (i = 0; i < res; i++)
printf("%hhx ", buf[i]);
puts("\n");
}
close(fd);
return 0;
}
const char *
bus_str(int bus)
{
switch (bus) {
case BUS_USB:
return "USB";
break;
case BUS_HIL:
return "HIL";
break;
case BUS_BLUETOOTH:
return "Bluetooth";
break;
case BUS_VIRTUAL:
return "Virtual";
break;
default:
return "Other";
break;
}
}
| apache-2.0 |
morsdatum/ArangoDB | 3rdParty/icu/source/i18n/vzone.cpp | 240 | 5586 | /*
*******************************************************************************
* Copyright (C) 2009-2011, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
/**
* \file
* \brief C API: VTimeZone classes
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "vzone.h"
#include "unicode/vtzone.h"
#include "cmemory.h"
#include "unicode/ustring.h"
#include "unicode/parsepos.h"
U_NAMESPACE_USE
U_CAPI VZone* U_EXPORT2
vzone_openID(const UChar* ID, int32_t idLength){
UnicodeString s(idLength==-1, ID, idLength);
return (VZone*) (VTimeZone::createVTimeZoneByID(s));
}
U_CAPI VZone* U_EXPORT2
vzone_openData(const UChar* vtzdata, int32_t vtzdataLength, UErrorCode& status) {
UnicodeString s(vtzdataLength==-1, vtzdata, vtzdataLength);
return (VZone*) (VTimeZone::createVTimeZone(s,status));
}
U_CAPI void U_EXPORT2
vzone_close(VZone* zone) {
delete (VTimeZone*)zone;
}
U_CAPI VZone* U_EXPORT2
vzone_clone(const VZone *zone) {
return (VZone*) (((VTimeZone*)zone)->VTimeZone::clone());
}
U_CAPI UBool U_EXPORT2
vzone_equals(const VZone* zone1, const VZone* zone2) {
return *(const VTimeZone*)zone1 == *(const VTimeZone*)zone2;
}
U_CAPI UBool U_EXPORT2
vzone_getTZURL(VZone* zone, UChar* & url, int32_t & urlLength) {
UnicodeString s;
UBool b = ((VTimeZone*)zone)->VTimeZone::getTZURL(s);
urlLength = s.length();
memcpy(url,s.getBuffer(),urlLength);
return b;
}
U_CAPI void U_EXPORT2
vzone_setTZURL(VZone* zone, UChar* url, int32_t urlLength) {
UnicodeString s(urlLength==-1, url, urlLength);
((VTimeZone*)zone)->VTimeZone::setTZURL(s);
}
U_CAPI UBool U_EXPORT2
vzone_getLastModified(VZone* zone, UDate& lastModified) {
return ((VTimeZone*)zone)->VTimeZone::getLastModified(lastModified);
}
U_CAPI void U_EXPORT2
vzone_setLastModified(VZone* zone, UDate lastModified) {
return ((VTimeZone*)zone)->VTimeZone::setLastModified(lastModified);
}
U_CAPI void U_EXPORT2
vzone_write(VZone* zone, UChar* & result, int32_t & resultLength, UErrorCode& status) {
UnicodeString s;
((VTimeZone*)zone)->VTimeZone::write(s, status);
resultLength = s.length();
result = (UChar*)uprv_malloc(resultLength);
memcpy(result,s.getBuffer(),resultLength);
return;
}
U_CAPI void U_EXPORT2
vzone_writeFromStart(VZone* zone, UDate start, UChar* & result, int32_t & resultLength, UErrorCode& status) {
UnicodeString s;
((VTimeZone*)zone)->VTimeZone::write(start, s, status);
resultLength = s.length();
result = (UChar*)uprv_malloc(resultLength);
memcpy(result,s.getBuffer(),resultLength);
return;
}
U_CAPI void U_EXPORT2
vzone_writeSimple(VZone* zone, UDate time, UChar* & result, int32_t & resultLength, UErrorCode& status) {
UnicodeString s;
((VTimeZone*)zone)->VTimeZone::writeSimple(time, s, status);
resultLength = s.length();
result = (UChar*)uprv_malloc(resultLength);
memcpy(result,s.getBuffer(),resultLength);
return;
}
U_CAPI int32_t U_EXPORT2
vzone_getOffset(VZone* zone, uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis, UErrorCode& status) {
return ((VTimeZone*)zone)->VTimeZone::getOffset(era, year, month, day, dayOfWeek, millis, status);
}
U_CAPI int32_t U_EXPORT2
vzone_getOffset2(VZone* zone, uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis,
int32_t monthLength, UErrorCode& status) {
return ((VTimeZone*)zone)->VTimeZone::getOffset(era, year, month, day, dayOfWeek, millis, monthLength, status);
}
U_CAPI void U_EXPORT2
vzone_getOffset3(VZone* zone, UDate date, UBool local, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& ec) {
return ((VTimeZone*)zone)->VTimeZone::getOffset(date, local, rawOffset, dstOffset, ec);
}
U_CAPI void U_EXPORT2
vzone_setRawOffset(VZone* zone, int32_t offsetMillis) {
return ((VTimeZone*)zone)->VTimeZone::setRawOffset(offsetMillis);
}
U_CAPI int32_t U_EXPORT2
vzone_getRawOffset(VZone* zone) {
return ((VTimeZone*)zone)->VTimeZone::getRawOffset();
}
U_CAPI UBool U_EXPORT2
vzone_useDaylightTime(VZone* zone) {
return ((VTimeZone*)zone)->VTimeZone::useDaylightTime();
}
U_CAPI UBool U_EXPORT2
vzone_inDaylightTime(VZone* zone, UDate date, UErrorCode& status) {
return ((VTimeZone*)zone)->VTimeZone::inDaylightTime(date, status);
}
U_CAPI UBool U_EXPORT2
vzone_hasSameRules(VZone* zone, const VZone* other) {
return ((VTimeZone*)zone)->VTimeZone::hasSameRules(*(VTimeZone*)other);
}
U_CAPI UBool U_EXPORT2
vzone_getNextTransition(VZone* zone, UDate base, UBool inclusive, ZTrans* result) {
return ((VTimeZone*)zone)->VTimeZone::getNextTransition(base, inclusive, *(TimeZoneTransition*)result);
}
U_CAPI UBool U_EXPORT2
vzone_getPreviousTransition(VZone* zone, UDate base, UBool inclusive, ZTrans* result) {
return ((VTimeZone*)zone)->VTimeZone::getPreviousTransition(base, inclusive, *(TimeZoneTransition*)result);
}
U_CAPI int32_t U_EXPORT2
vzone_countTransitionRules(VZone* zone, UErrorCode& status) {
return ((VTimeZone*)zone)->VTimeZone::countTransitionRules(status);
}
U_CAPI UClassID U_EXPORT2
vzone_getStaticClassID(VZone* zone) {
return ((VTimeZone*)zone)->VTimeZone::getStaticClassID();
}
U_CAPI UClassID U_EXPORT2
vzone_getDynamicClassID(VZone* zone) {
return ((VTimeZone*)zone)->VTimeZone::getDynamicClassID();
}
#endif
| apache-2.0 |
blats002/JLRAssessment | plugins/cordova-plugin-globalization/src/blackberry10/native/public/json_reader.cpp | 253 | 22356 | // Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
/*
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 <json/reader.h>
#include <json/value.h>
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdexcept>
#if _MSC_VER >= 1400 // VC++ 8.0
#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
#endif
namespace Json {
// QNX is strict about declaring C symbols in the std namespace.
#ifdef __QNXNTO__
using std::memcpy;
using std::sprintf;
using std::sscanf;
#endif
// Implementation of class Features
// ////////////////////////////////
Features::Features()
: allowComments_( true )
, strictRoot_( false )
{
}
Features
Features::all()
{
return Features();
}
Features
Features::strictMode()
{
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
{
return c == c1 || c == c2 || c == c3 || c == c4;
}
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
{
return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
}
static bool
containsNewLine( Reader::Location begin,
Reader::Location end )
{
for ( ;begin < end; ++begin )
if ( *begin == '\n' || *begin == '\r' )
return true;
return false;
}
static std::string codePointToUTF8(unsigned int cp)
{
std::string result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f)
{
result.resize(1);
result[0] = static_cast<char>(cp);
}
else if (cp <= 0x7FF)
{
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
}
else if (cp <= 0xFFFF)
{
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
}
else if (cp <= 0x10FFFF)
{
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader()
: features_( Features::all() )
{
}
Reader::Reader( const Features &features )
: features_( features )
{
}
bool
Reader::parse( const std::string &document,
Value &root,
bool collectComments )
{
document_ = document;
const char *begin = document_.c_str();
const char *end = begin + document_.length();
return parse( begin, end, root, collectComments );
}
bool
Reader::parse( std::istream& sin,
Value &root,
bool collectComments )
{
//std::istream_iterator<char> begin(sin);
//std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// create an extra copy.
std::string doc;
std::getline(sin, doc, (char)EOF);
return parse( doc, root, collectComments );
}
bool
Reader::parse( const char *beginDoc, const char *endDoc,
Value &root,
bool collectComments )
{
if ( !features_.allowComments_ )
{
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while ( !nodes_.empty() )
nodes_.pop();
nodes_.push( &root );
bool successful = readValue();
Token token;
skipCommentTokens( token );
if ( collectComments_ && !commentsBefore_.empty() )
root.setComment( commentsBefore_, commentAfter );
if ( features_.strictRoot_ )
{
if ( !root.isArray() && !root.isObject() )
{
// Set error location to start of doc, ideally should be first token found in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError( "A valid JSON document must be either an array or an object value.",
token );
return false;
}
}
return successful;
}
bool
Reader::readValue()
{
Token token;
skipCommentTokens( token );
bool successful = true;
if ( collectComments_ && !commentsBefore_.empty() )
{
currentValue().setComment( commentsBefore_, commentBefore );
commentsBefore_ = "";
}
switch ( token.type_ )
{
case tokenObjectBegin:
successful = readObject( token );
break;
case tokenArrayBegin:
successful = readArray( token );
break;
case tokenNumber:
successful = decodeNumber( token );
break;
case tokenString:
successful = decodeString( token );
break;
case tokenTrue:
currentValue() = true;
break;
case tokenFalse:
currentValue() = false;
break;
case tokenNull:
currentValue() = Value();
break;
default:
return addError( "Syntax error: value, object or array expected.", token );
}
if ( collectComments_ )
{
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
return successful;
}
void
Reader::skipCommentTokens( Token &token )
{
if ( features_.allowComments_ )
{
do
{
readToken( token );
}
while ( token.type_ == tokenComment );
}
else
{
readToken( token );
}
}
bool
Reader::expectToken( TokenType type, Token &token, const char *message )
{
readToken( token );
if ( token.type_ != type )
return addError( message, token );
return true;
}
bool
Reader::readToken( Token &token )
{
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch ( c )
{
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match( "rue", 3 );
break;
case 'f':
token.type_ = tokenFalse;
ok = match( "alse", 4 );
break;
case 'n':
token.type_ = tokenNull;
ok = match( "ull", 3 );
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if ( !ok )
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void
Reader::skipSpaces()
{
while ( current_ != end_ )
{
Char c = *current_;
if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
++current_;
else
break;
}
}
bool
Reader::match( Location pattern,
int patternLength )
{
if ( end_ - current_ < patternLength )
return false;
int index = patternLength;
while ( index-- )
if ( current_[index] != pattern[index] )
return false;
current_ += patternLength;
return true;
}
bool
Reader::readComment()
{
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if ( c == '*' )
successful = readCStyleComment();
else if ( c == '/' )
successful = readCppStyleComment();
if ( !successful )
return false;
if ( collectComments_ )
{
CommentPlacement placement = commentBefore;
if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
{
if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
placement = commentAfterOnSameLine;
}
addComment( commentBegin, current_, placement );
}
return true;
}
void
Reader::addComment( Location begin,
Location end,
CommentPlacement placement )
{
assert( collectComments_ );
if ( placement == commentAfterOnSameLine )
{
assert( lastValue_ != 0 );
lastValue_->setComment( std::string( begin, end ), placement );
}
else
{
if ( !commentsBefore_.empty() )
commentsBefore_ += "\n";
commentsBefore_ += std::string( begin, end );
}
}
bool
Reader::readCStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '*' && *current_ == '/' )
break;
}
return getNextChar() == '/';
}
bool
Reader::readCppStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '\r' || c == '\n' )
break;
}
return true;
}
void
Reader::readNumber()
{
while ( current_ != end_ )
{
if ( !(*current_ >= '0' && *current_ <= '9') &&
!in( *current_, '.', 'e', 'E', '+', '-' ) )
break;
++current_;
}
}
bool
Reader::readString()
{
Char c = 0;
while ( current_ != end_ )
{
c = getNextChar();
if ( c == '\\' )
getNextChar();
else if ( c == '"' )
break;
}
return c == '"';
}
bool
Reader::readObject( Token &tokenStart )
{
Token tokenName;
std::string name;
currentValue() = Value( objectValue );
while ( readToken( tokenName ) )
{
bool initialTokenOk = true;
while ( tokenName.type_ == tokenComment && initialTokenOk )
initialTokenOk = readToken( tokenName );
if ( !initialTokenOk )
break;
if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object
return true;
if ( tokenName.type_ != tokenString )
break;
name = "";
if ( !decodeString( tokenName, name ) )
return recoverFromError( tokenObjectEnd );
Token colon;
if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator )
{
return addErrorAndRecover( "Missing ':' after object member name",
colon,
tokenObjectEnd );
}
Value &value = currentValue()[ name ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenObjectEnd );
Token comma;
if ( !readToken( comma )
|| ( comma.type_ != tokenObjectEnd &&
comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment ) )
{
return addErrorAndRecover( "Missing ',' or '}' in object declaration",
comma,
tokenObjectEnd );
}
bool finalizeTokenOk = true;
while ( comma.type_ == tokenComment &&
finalizeTokenOk )
finalizeTokenOk = readToken( comma );
if ( comma.type_ == tokenObjectEnd )
return true;
}
return addErrorAndRecover( "Missing '}' or object member name",
tokenName,
tokenObjectEnd );
}
bool
Reader::readArray( Token &tokenStart )
{
currentValue() = Value( arrayValue );
skipSpaces();
if ( *current_ == ']' ) // empty array
{
Token endArray;
readToken( endArray );
return true;
}
int index = 0;
while ( true )
{
Value &value = currentValue()[ index++ ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenArrayEnd );
Token token;
// Accept Comment after last item in the array.
ok = readToken( token );
while ( token.type_ == tokenComment && ok )
{
ok = readToken( token );
}
bool badTokenType = ( token.type_ == tokenArraySeparator &&
token.type_ == tokenArrayEnd );
if ( !ok || badTokenType )
{
return addErrorAndRecover( "Missing ',' or ']' in array declaration",
token,
tokenArrayEnd );
}
if ( token.type_ == tokenArrayEnd )
break;
}
return true;
}
bool
Reader::decodeNumber( Token &token )
{
bool isDouble = false;
for ( Location inspect = token.start_; inspect != token.end_; ++inspect )
{
isDouble = isDouble
|| in( *inspect, '.', 'e', 'E', '+' )
|| ( *inspect == '-' && inspect != token.start_ );
}
if ( isDouble )
return decodeDouble( token );
Location current = token.start_;
bool isNegative = *current == '-';
if ( isNegative )
++current;
Value::UInt threshold = (isNegative ? Value::UInt(-Value::minInt)
: Value::maxUInt) / 10;
Value::UInt value = 0;
while ( current < token.end_ )
{
Char c = *current++;
if ( c < '0' || c > '9' )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
if ( value >= threshold )
return decodeDouble( token );
value = value * 10 + Value::UInt(c - '0');
}
if ( isNegative )
currentValue() = -Value::Int( value );
else if ( value <= Value::UInt(Value::maxInt) )
currentValue() = Value::Int( value );
else
currentValue() = value;
return true;
}
bool
Reader::decodeDouble( Token &token )
{
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
if ( length <= bufferSize )
{
Char buffer[bufferSize];
memcpy( buffer, token.start_, length );
buffer[length] = 0;
count = sscanf( buffer, "%lf", &value );
}
else
{
std::string buffer( token.start_, token.end_ );
count = sscanf( buffer.c_str(), "%lf", &value );
}
if ( count != 1 )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
currentValue() = value;
return true;
}
bool
Reader::decodeString( Token &token )
{
std::string decoded;
if ( !decodeString( token, decoded ) )
return false;
currentValue() = decoded;
return true;
}
bool
Reader::decodeString( Token &token, std::string &decoded )
{
decoded.reserve( token.end_ - token.start_ - 2 );
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while ( current != end )
{
Char c = *current++;
if ( c == '"' )
break;
else if ( c == '\\' )
{
if ( current == end )
return addError( "Empty escape sequence in string", token, current );
Char escape = *current++;
switch ( escape )
{
case '"': decoded += '"'; break;
case '/': decoded += '/'; break;
case '\\': decoded += '\\'; break;
case 'b': decoded += '\b'; break;
case 'f': decoded += '\f'; break;
case 'n': decoded += '\n'; break;
case 'r': decoded += '\r'; break;
case 't': decoded += '\t'; break;
case 'u':
{
unsigned int unicode;
if ( !decodeUnicodeCodePoint( token, current, end, unicode ) )
return false;
decoded += codePointToUTF8(unicode);
}
break;
default:
return addError( "Bad escape sequence in string", token, current );
}
}
else
{
decoded += c;
}
}
return true;
}
bool
Reader::decodeUnicodeCodePoint( Token &token,
Location ¤t,
Location end,
unsigned int &unicode )
{
if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF)
{
// surrogate pairs
if (end - current < 6)
return addError( "additional six characters expected to parse unicode surrogate pair.", token, current );
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++)== 'u')
{
if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair ))
{
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
}
else
return false;
}
else
return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current );
}
return true;
}
bool
Reader::decodeUnicodeEscapeSequence( Token &token,
Location ¤t,
Location end,
unsigned int &unicode )
{
if ( end - current < 4 )
return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
unicode = 0;
for ( int index =0; index < 4; ++index )
{
Char c = *current++;
unicode *= 16;
if ( c >= '0' && c <= '9' )
unicode += c - '0';
else if ( c >= 'a' && c <= 'f' )
unicode += c - 'a' + 10;
else if ( c >= 'A' && c <= 'F' )
unicode += c - 'A' + 10;
else
return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
}
return true;
}
bool
Reader::addError( const std::string &message,
Token &token,
Location extra )
{
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back( info );
return false;
}
bool
Reader::recoverFromError( TokenType skipUntilToken )
{
int errorCount = int(errors_.size());
Token skip;
while ( true )
{
if ( !readToken(skip) )
errors_.resize( errorCount ); // discard errors caused by recovery
if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
break;
}
errors_.resize( errorCount );
return false;
}
bool
Reader::addErrorAndRecover( const std::string &message,
Token &token,
TokenType skipUntilToken )
{
addError( message, token );
return recoverFromError( skipUntilToken );
}
Value &
Reader::currentValue()
{
return *(nodes_.top());
}
Reader::Char
Reader::getNextChar()
{
if ( current_ == end_ )
return 0;
return *current_++;
}
void
Reader::getLocationLineAndColumn( Location location,
int &line,
int &column ) const
{
Location current = begin_;
Location lastLineStart = current;
line = 0;
while ( current < location && current != end_ )
{
Char c = *current++;
if ( c == '\r' )
{
if ( *current == '\n' )
++current;
lastLineStart = current;
++line;
}
else if ( c == '\n' )
{
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
std::string
Reader::getLocationLineAndColumn( Location location ) const
{
int line, column;
getLocationLineAndColumn( location, line, column );
char buffer[18+16+16+1];
sprintf( buffer, "Line %d, Column %d", line, column );
return buffer;
}
std::string
Reader::getFormatedErrorMessages() const
{
std::string formattedMessage;
for ( Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError )
{
const ErrorInfo &error = *itError;
formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
formattedMessage += " " + error.message_ + "\n";
if ( error.extra_ )
formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
}
return formattedMessage;
}
std::istream& operator>>( std::istream &sin, Value &root )
{
Json::Reader reader;
bool ok = reader.parse(sin, root, true);
//JSON_ASSERT( ok );
if (!ok) throw std::runtime_error(reader.getFormatedErrorMessages());
return sin;
}
} // namespace Json
| apache-2.0 |
prswan/arduino-mega-ict | libraries/C2650Cpu/C2650Cpu.cpp | 1 | 26576 | //
// Copyright (c) 2015, Paul R. Swan
// 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 HOLDER 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 "Arduino.h"
#include "Error.h"
#include "C2650Cpu.h"
#include "PinMap.h"
//
// Pin prefixes
//
// _ - active low
//
// Pin suffixes
//
// i - input
// o - output
// t - tri-state
//
// NOTE: This implementation was tested using a shield without protection resistors.
// It has not been tested with a "standard" shield with protection resistors.
//
/*
WARNING: Ports E, G & H are used by the LCD/Keypad shield and thus cannot be directly used!
14, // PJ1 - 1
16, // PH1 - 2
18, // PD3 - 3
20, // PD1 - 4
22, // PA0 - 5
24, // PA2 - 6
26, // PA4 - 7
28, // PA6 - 8
30, // PC7 - 9
32, // PC5 - 10
34, // PC3 - 11
36, // PC1 - 12
38, // PD7 - 13
40, // PG1 - 14
42, // PL7 - 15
44, // PL5 - 16
46, // PL3 - 17
48, // PL1 - 18
50, // PB3 - 19
52, // PB1 - 20
53, // PB0 - 21
51, // PB2 - 22 - WRP
49, // PL0 - 23
47, // PL2 - 24 - OPREQ
45, // PL4 - 25
43, // PL6 - 26 - D7
41, // PG0 - 27 - D6
39, // PG2 - 28 - D5
37, // PC0 - 29 - D4
35, // PC2 - 30 - D3
33, // PC4 - 31 - D2
31, // PC6 - 32 - D1
29, // PA7 - 33 - D0
27, // PA5 - 34
25, // PA3 - 35
23, // PA1 - 36 - OPACK
21, // PD0 - 37
19, // PD2 - 38 - CLK
17, // PH0 - 39
15 // PJ0 - 40
*/
//
// Byte-wide port registers
//
static volatile UINT8 * const g_portInA = &PINA;
static volatile UINT8 * const g_portOutA = &PORTA;
static volatile UINT8 * const g_portInB = &PINB;
static volatile UINT8 * const g_portOutB = &PORTB;
static volatile UINT8 * const g_portInC = &PINC;
static volatile UINT8 * const g_portOutC = &PORTC;
static volatile UINT8 * const g_portInD = &PIND;
static volatile UINT8 * const g_portOutD = &PORTD;
static volatile UINT8 * const g_portInG = &PING;
static volatile UINT8 * const g_portOutG = &PORTG;
static volatile UINT8 * const g_portInL = &PINL;
static volatile UINT8 * const g_portOutL = &PORTL;
//
// Input definitions.
//
static const UINT8 s_D2_BIT_IN_CLK = (1 << 2);
static const UINT8 s_A1_BIT_IN_OPACK = (1 << 1);
//
// Output definitions.
//
static const UINT8 s_B2_BIT_OUT_WRP = (1 << 2);
static const UINT8 s_L2_BIT_OUT_OPREQ = (1 << 2);
//
// Data Bus definition
//
static const UINT8 s_A7_BIT_D0 = (1 << 7);
static const UINT8 s_C6_BIT_D1 = (1 << 6);
static const UINT8 s_C4_BIT_D2 = (1 << 4);
static const UINT8 s_C2_BIT_D3 = (1 << 2);
static const UINT8 s_C0_BIT_D4 = (1 << 0);
static const UINT8 s_G2_BIT_D5 = (1 << 2);
static const UINT8 s_G0_BIT_D6 = (1 << 0);
static const UINT8 s_L6_BIT_D7 = (1 << 6);
//
// Wait for CLK rising edge to be detected.
// This loop is 8 instructions total, 500ns.
// Note that the system will hang here if CLK is stuck.
//
#define WAIT_FOR_CLK_RISING_EDGE(r1,r2) \
{ \
while(1) \
{ \
r1 = *g_portInD; \
r2 = *g_portInD; \
\
if (!(r1 & s_D2_BIT_IN_CLK) && \
(r2 & s_D2_BIT_IN_CLK)) \
{ \
break; \
} \
} \
} \
//
// Wait for CLK low.
// This loop is 2 instructions total, 125ns.
// Note that the system will hang here if CLK is stuck.
//
#define WAIT_FOR_CLK_LO(r1) \
{ \
while(1) \
{ \
r1 = *g_portInD; \
\
if (!(r1 & s_D2_BIT_IN_CLK)) \
{ \
break; \
} \
} \
} \
//
// Wait for CLK High.
// This loop is 2 instructions total, 125ns.
// Note that the system will hang here if CLK is stuck.
//
#define WAIT_FOR_CLK_HI(r1) \
{ \
while(1) \
{ \
r1 = *g_portInD; \
\
if ((r1 & s_D2_BIT_IN_CLK)) \
{ \
break; \
} \
} \
} \
//
// Wait for OPACK low.
// This loop is 2 instructions total, 125ns.
// Note that the system will hang here if OPACK is stuck.
//
#define WAIT_FOR_OPACK_LO(r1) \
{ \
while(1) \
{ \
r1 = *g_portInA; \
\
if (!(r1 & s_A1_BIT_IN_OPACK)) \
{ \
break; \
} \
} \
} \
//
// Control Pins
//
static const CONNECTION s_SENSE_i = { 1, "SENSE" };
static const CONNECTION s__ADREN_i = { 15, "_ADREN" };
static const CONNECTION s_RESET_i = { 16, "RESET" };
static const CONNECTION s__INTREQ_i = { 17, "_INTREQ" };
static const CONNECTION s_M_IO_o = { 20, "M_IO" };
static const CONNECTION s_GND_i = { 21, "GND" };
static const CONNECTION s_WRP_o = { 22, "WRP" };
static const CONNECTION s__RW_o = { 23, "_RW" };
static const CONNECTION s_OPREQ_o = { 24, "OPREQ" };
static const CONNECTION s__DBUSEN_i = { 25, "_DBUSEN" };
static const CONNECTION s_INTACK_o = { 34, "INTACK" };
static const CONNECTION s_RUN_WAIT_o = { 35, "RUN_WAIT" };
static const CONNECTION s__OPACK_i = { 36, "_OPACK" };
static const CONNECTION s__PAUSE_i = { 37, "_PAUSE" };
static const CONNECTION s_CLOCK_i = { 38, "CLOCK" };
static const CONNECTION s_Vcc_i = { 39, "Vcc" };
static const CONNECTION s_FLAG_o = { 40, "FLAG" };;
//
// Dual function pins
//
static const CONNECTION s_D_C_ot = { 18, "D_C" };
static const CONNECTION s_E_NE_ot = { 19, "N_NE" };
//
// Bus pins
//
static const CONNECTION s_ADR_ot[] = { {14, "ADR0" },
{13, "ADR1" },
{12, "ADR2" },
{11, "ADR3" },
{10, "ADR4" },
{ 9, "ADR5" },
{ 8, "ADR6" },
{ 7, "ADR7" },
{ 6, "ADR8" },
{ 5, "ADR9" },
{ 4, "ADR10" },
{ 3, "ADR11" },
{ 2, "ADR12" },
{19, "ADR13" },
{18, "ADR14" } }; // 15 bits
static const CONNECTION s_DBUS_iot[] = { {33, "DBUS0" },
{32, "DBUS1" },
{31, "DBUS2" },
{30, "DBUS3" },
{29, "DBUS4" },
{28, "DBUS5" },
{27, "DBUS6" },
{26, "DBUS7" } }; // 8 bits.
C2650Cpu::C2650Cpu(
) : m_busADR(g_pinMap40DIL, s_ADR_ot, ARRAYSIZE(s_ADR_ot)),
m_busDBUS(g_pinMap40DIL, s_DBUS_iot, ARRAYSIZE(s_DBUS_iot)),
m_pinCLOCK(g_pinMap40DIL, &s_CLOCK_i),
m_pinOPREQ(g_pinMap40DIL, &s_OPREQ_o),
m_pinWRP(g_pinMap40DIL, &s_WRP_o),
m_pin_OPACK(g_pinMap40DIL, &s__OPACK_i)
{
};
//
// The idle function sets up the pins into the correct direction (input/output)
// and idle state ready for the next bus cycle.
//
PERROR
C2650Cpu::idle(
)
{
pinMode(g_pinMap40DIL[s_SENSE_i.pin], INPUT);
pinMode(g_pinMap40DIL[s__ADREN_i.pin], INPUT);
pinMode(g_pinMap40DIL[s_RESET_i.pin], INPUT);
pinMode(g_pinMap40DIL[s__INTREQ_i.pin], INPUT);
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], HIGH);
pinMode(g_pinMap40DIL[s_M_IO_o.pin], OUTPUT);
pinMode(g_pinMap40DIL[s_GND_i.pin], INPUT_PULLUP);
digitalWrite(g_pinMap40DIL[s__RW_o.pin], HIGH);
pinMode(g_pinMap40DIL[s__RW_o.pin], OUTPUT);
pinMode(g_pinMap40DIL[s__DBUSEN_i.pin], INPUT);
digitalWrite(g_pinMap40DIL[s_INTACK_o.pin], LOW);
pinMode(g_pinMap40DIL[s_INTACK_o.pin], OUTPUT);
digitalWrite(g_pinMap40DIL[s_RUN_WAIT_o.pin], LOW);
pinMode(g_pinMap40DIL[s_RUN_WAIT_o.pin], OUTPUT);
pinMode(g_pinMap40DIL[s__PAUSE_i.pin], INPUT);
pinMode(g_pinMap40DIL[s_Vcc_i.pin], INPUT);
digitalWrite(g_pinMap40DIL[s_FLAG_o.pin], LOW);
pinMode(g_pinMap40DIL[s_FLAG_o.pin], OUTPUT);
// since the address bus is controlled by ADREN we can't set it output.
m_busADR.pinMode(INPUT_PULLUP);
// since the data bus is controlled by DBUSEN we can't set it output.
m_busDBUS.pinMode(INPUT_PULLUP);
// Set the fast clock & opack pins to input
m_pinCLOCK.pinMode(INPUT);
m_pin_OPACK.pinMode(INPUT);
// Set the fast WRP & OPREQ pin to output and LOW.
m_pinOPREQ.digitalWrite(LOW);
m_pinOPREQ.pinMode(OUTPUT);
m_pinWRP.digitalWrite(HIGH);
m_pinWRP.pinMode(OUTPUT);
return errorSuccess;
}
//
// The check function performs a basic pin check that all the outputs can be pulled high
// by the pullup resistor as a way to detect a GND short or pulled output. It also validates
// the default state of the control pins would allow the CPU to execute instructions.
//
// If check fails the pins are left in the failing state. If check succeeds the pins are reset
// to idle state.
//
PERROR
C2650Cpu::check(
)
{
PERROR error = errorSuccess;
// The ground pin (with pullup) should be connected to GND (LOW)
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s_GND_i, LOW);
// The Vcc pin should be high (power is on).
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s_Vcc_i, HIGH);
// The reset pin should be low (no reset).
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s_RESET_i, LOW);
// The pause pin should be high (running).
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s__PAUSE_i, HIGH);
// In everything we'll be testing, ADREN is tied low.
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s__ADREN_i, LOW);
// In everything we'll be testing, DBUSEN is tied low.
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s__DBUSEN_i, LOW);
// The address bus should be uncontended and pulled high.
CHECK_BUS_VALUE_UINT16_EXIT(error, m_busADR, s_ADR_ot, 0x7FFF);
// The data bus should be uncontended and pulled high.
CHECK_BUS_VALUE_UINT8_EXIT(error, m_busDBUS, s_DBUS_iot, 0xFF);
// Loop to detect a clock by sampling and detecting both high and lows.
{
UINT16 hiCount = 0;
UINT16 loCount = 0;
for (int i = 0 ; i < 1000 ; i++)
{
int value = ::digitalRead(g_pinMap40DIL[s_CLOCK_i.pin]);
if (value == LOW)
{
loCount++;
}
else
{
hiCount++;
}
}
if (loCount == 0)
{
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s_CLOCK_i, LOW);
}
else if (hiCount == 0)
{
CHECK_VALUE_EXIT(error, g_pinMap40DIL, s_CLOCK_i, HIGH);
}
}
Exit:
return error;
}
UINT8
C2650Cpu::dataBusWidth(
UINT32 address
)
{
return 1;
}
UINT8
C2650Cpu::dataAccessWidth(
UINT32 address
)
{
return 1;
}
PERROR
C2650Cpu::memoryRead(
UINT32 address,
UINT16 *data
)
{
if (address > (UINT32) 0xFFFF)
{
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], LOW);
}
else
{
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], HIGH);
}
digitalWrite(g_pinMap40DIL[s_INTACK_o.pin], LOW);
return read((address & 0xFFFF), data);
}
PERROR
C2650Cpu::memoryWrite(
UINT32 address,
UINT16 data
)
{
if (address > (UINT32) 0xFFFF)
{
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], LOW);
}
else
{
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], HIGH);
}
digitalWrite(g_pinMap40DIL[s_INTACK_o.pin], LOW);
return write((address & 0xFFFF), data);
}
//
// This is the internal function that does a read cycle. The caller is expected
// to set the M_IO pin to reflect the actual space being accessed.
//
PERROR
C2650Cpu::read(
UINT32 address,
UINT16 *data
)
{
PERROR error = errorSuccess;
bool interruptsDisabled = false;
// Set a read cycle.
digitalWrite(g_pinMap40DIL[s__RW_o.pin], LOW);
// By default WRP is high unless pulsed for write.
m_pinWRP.digitalWrite(HIGH);
// Enable the address bus and set the value.
m_busADR.pinMode(OUTPUT);
m_busADR.digitalWrite((UINT16) address);
// Set the databus to input.
m_busDBUS.pinMode(INPUT);
// Critical timing section
noInterrupts();
interruptsDisabled = true;
// Timing Note
// -----------
// The critical timing on Zaccaria boards is the 2636.
// Assmbly extract for the critical timing section:
//
// 6f6e: f8 94 cli
// 6f70: 60 91 0b 01 lds r22, 0x010B ; 0x80010b <__data_load_end+0x7f4fe9>
// 6f74: 85 b1 in r24, 0x05 ; 5
// 6f76: 3e 81 ldd r19, Y+6 ; 0x06
// 6f78: 2d 81 ldd r18, Y+5 ; 0x05
// 6f7a: 49 b1 in r20, 0x09 ; 9
// 6f7c: 99 b1 in r25, 0x09 ; 9
// 6f7e: 42 fd sbrc r20, 2
// 6f80: fc cf rjmp .-8 ; 0x6f7a <_ZN8C2650Cpu4readEmPt+0x88>
// 6f82: 92 ff sbrs r25, 2
// 6f84: fa cf rjmp .-12 ; 0x6f7a <_ZN8C2650Cpu4readEmPt+0x88>
// 6f86: 96 2f mov r25, r22
// 6f88: 94 60 ori r25, 0x04 ; 4
// 6f8a: 90 93 0b 01 sts 0x010B, r25 ; 0x80010b <__data_load_end+0x7f4fe9>
// 6f8e: 85 b9 out 0x05, r24 ; 5
// 6f90: 90 b1 in r25, 0x00 ; 0
// 6f92: 90 b1 in r25, 0x00 ; 0
// 6f94: 90 b1 in r25, 0x00 ; 0
// 6f96: 90 b1 in r25, 0x00 ; 0
// 6f98: 90 b1 in r25, 0x00 ; 0
// 6f9a: 01 99 sbic 0x00, 1 ; 0
// 6f9c: fe cf rjmp .-4 ; 0x6f9a <_ZN8C2650Cpu4readEmPt+0xa8>
// 6f9e: 85 b9 out 0x05, r24 ; 5
// 6fa0: 80 b1 in r24, 0x00 ; 0
// 6fa2: 80 b1 in r24, 0x00 ; 0
// 6fa4: 80 b1 in r24, 0x00 ; 0
// 6fa6: 80 b1 in r24, 0x00 ; 0
// 6fa8: 80 b1 in r24, 0x00 ; 0
// 6faa: 80 b1 in r24, 0x00 ; 0
// 6fac: 80 b1 in r24, 0x00 ; 0
// 6fae: 80 b1 in r24, 0x00 ; 0
// 6fb0: 40 91 09 01 lds r20, 0x0109 ; 0x800109 <__data_load_end+0x7f4fe7>
// 6fb4: 82 b3 in r24, 0x12 ; 18
// 6fb6: 96 b1 in r25, 0x06 ; 6
// 6fb8: 50 b1 in r21, 0x00 ; 0
// 6fba: 60 93 0b 01 sts 0x010B, r22 ; 0x80010b <__data_load_end+0x7f4fe9>
//
{
register UINT8 portOutL;
register UINT8 portOutB;
register UINT8 r1;
register UINT8 r2;
register UINT8 r3;
register UINT8 r4;
// Cache the current value of the port.
portOutL = *g_portOutL;
portOutB = *g_portOutB;
// Start the cycle by assert the control lines
*g_portOutB = portOutB;
*g_portOutL = portOutL | s_L2_BIT_OUT_OPREQ;
// 600ns *maximum* for peripherals to assert OPACK
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB; // Wait State, ~300ns
*g_portInA; // Wait state, ~360ns
// Wait for OPACK to be asserted.
WAIT_FOR_OPACK_LO(r1);
//
// The 2636 requires 450ns to assert data on the bus after OPACK
// is asserted.
//
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB; // Wait state, ~300ns
*g_portInA; // Wait state, ~360ns
*g_portInA; // Wait state, ~420ns
*g_portInA; // Wait state, ~480ns
*g_portInA; // Wait state, ~540ns
// Read in reverse order - port L is a slower access.
r1 = *g_portInL;
r2 = *g_portInG;
r3 = *g_portInC;
r4 = *g_portInA;
// Terminate the cycle
*g_portOutL = portOutL;
// Wait For 2636 CE inactive
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB; // Wait state, ~300ns
// Populate the output data word
*data = (((r4 & s_A7_BIT_D0) >> 7) << 0) |
(((r3 & s_C6_BIT_D1) >> 6) << 1) |
(((r3 & s_C4_BIT_D2) >> 4) << 2) |
(((r3 & s_C2_BIT_D3) >> 2) << 3) |
(((r3 & s_C0_BIT_D4) >> 0) << 4) |
(((r2 & s_G2_BIT_D5) >> 2) << 5) |
(((r2 & s_G0_BIT_D6) >> 0) << 6) |
(((r1 & s_L6_BIT_D7) >> 6) << 7);
}
Exit:
if (interruptsDisabled)
{
interrupts();
}
return error;
}
//
// This is the internal function that does a write cycle. The caller is expected
// to set the M_IO pin to reflect the actual space being accessed.
//
PERROR
C2650Cpu::write(
UINT32 address,
UINT16 data
)
{
PERROR error = errorSuccess;
bool interruptsDisabled = false;
// Set a write cycle.
digitalWrite(g_pinMap40DIL[s__RW_o.pin], HIGH);
// By default WRP is high unless pulsed for write.
m_pinWRP.digitalWrite(HIGH);
// Enable the address bus and set the value.
m_busADR.pinMode(OUTPUT);
m_busADR.digitalWrite((UINT16) address);
// Set the databus to output and set a value.
m_busDBUS.pinMode(OUTPUT);
m_busDBUS.digitalWrite(data);
// Critical timing section
noInterrupts();
interruptsDisabled = true;
// Timing Note
// -----------
// The critical timing on Zaccaria boards is the 2636.
// Assmbly extract for the critical timing section:
//
// 717c: f8 94 cli
// 717e: 80 91 0b 01 lds r24, 0x010B ; 0x80010b <__data_load_end+0x7f4fe9>
// 7182: 95 b1 in r25, 0x05 ; 5
// 7184: 39 b1 in r19, 0x09 ; 9
// 7186: 29 b1 in r18, 0x09 ; 9
// 7188: 32 fd sbrc r19, 2
// 718a: fc cf rjmp .-8 ; 0x7184 <_ZN8C2650Cpu11memoryWriteEmt+0xb6>
// 718c: 22 ff sbrs r18, 2
// 718e: fa cf rjmp .-12 ; 0x7184 <_ZN8C2650Cpu11memoryWriteEmt+0xb6>
// 7190: 28 2f mov r18, r24
// 7192: 24 60 ori r18, 0x04 ; 4
// 7194: 20 93 0b 01 sts 0x010B, r18 ; 0x80010b <__data_load_end+0x7f4fe9>
// 7198: 29 2f mov r18, r25
// 719a: 2b 7f andi r18, 0xFB ; 251
// 719c: 25 b9 out 0x05, r18 ; 5
// 719e: 20 b1 in r18, 0x00 ; 0
// 71a0: 20 b1 in r18, 0x00 ; 0
// 71a2: 20 b1 in r18, 0x00 ; 0
// 71a4: 20 b1 in r18, 0x00 ; 0
// 71a6: 20 b1 in r18, 0x00 ; 0
// 71a8: 01 99 sbic 0x00, 1 ; 0
// 71aa: fe cf rjmp .-4 ; 0x71a8 <_ZN8C2650Cpu11memoryWriteEmt+0xda>
// 71ac: 95 b9 out 0x05, r25 ; 5
// 71ae: 90 b1 in r25, 0x00 ; 0
// 71b0: 90 b1 in r25, 0x00 ; 0
// 71b2: 90 b1 in r25, 0x00 ; 0
// 71b4: 90 b1 in r25, 0x00 ; 0
// 71b6: 90 b1 in r25, 0x00 ; 0
// 71b8: 90 b1 in r25, 0x00 ; 0
// 71ba: 90 b1 in r25, 0x00 ; 0
// 71bc: 90 b1 in r25, 0x00 ; 0
// 71be: 90 91 09 01 lds r25, 0x0109 ; 0x800109 <__data_load_end+0x7f4fe7>
// 71c2: 92 b3 in r25, 0x12 ; 18
// 71c4: 96 b1 in r25, 0x06 ; 6
// 71c6: 90 b1 in r25, 0x00 ; 0
// 71c8: 80 93 0b 01 sts 0x010B, r24 ; 0x80010b <__data_load_end+0x7f4fe9>
//
{
register UINT8 portOutL;
register UINT8 portOutB;
register UINT8 r1;
register UINT8 r2;
register UINT8 r3;
register UINT8 r4;
// Cache the current value of the port.
portOutL = *g_portOutL;
portOutB = *g_portOutB;
//
// The 2650 datasheet shows WRP:
// OPREQ: ____-----------------____
// WRP: ----______-----______----
//
// The way this is used on The Invaders for clocking
// the tile RAM write depends on the slow CE from
// the 2636 masking off the first WRP low pulse
// such that the WRP high time clocks the data in
// the middle.
//
// Start the cycle by assert the control lines
*g_portOutB = portOutB & ~s_B2_BIT_OUT_WRP; // WRP - Lo
*g_portOutL = portOutL | s_L2_BIT_OUT_OPREQ;
// 600ns *maximum* for peripherals to assert OPACK
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB; // Wait State, ~300ns, WRP - Hi
*g_portInA; // Wait state, ~360ns
// Wait for OPACK to be asserted.
WAIT_FOR_OPACK_LO(r1);
//
// The 2636 requires 450ns to assert data on the bus after OPACK
// is asserted.
//
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB & ~s_B2_BIT_OUT_WRP; // Wait state, ~300ns, WRP - Lo
*g_portInA; // Wait state, ~360ns
*g_portInA; // Wait state, ~420ns
*g_portInA; // Wait state, ~480ns
*g_portInA; // Wait state, ~540ns
// This is a write but we keep these here to match the read cycle timing.
r1 = *g_portInL;
r2 = *g_portInG;
r3 = *g_portInC;
r4 = *g_portInA;
// Terminate the cycle
*g_portOutL = portOutL;
// Wait For 2636 CE inactive
*g_portInA; // Wait state, ~ 60ns
*g_portInA; // Wait state, ~120ns
*g_portInA; // Wait state, ~180ns
*g_portInA; // Wait state, ~240ns
*g_portOutB = portOutB; // Wait State, ~300ns, WRP - Hi
}
Exit:
if (interruptsDisabled)
{
interrupts();
}
return error;
}
void
C2650Cpu::flagWrite(
UINT8 value
)
{
digitalWrite(g_pinMap40DIL[s_FLAG_o.pin], value);
}
UINT8
C2650Cpu::senseRead(
)
{
return digitalRead(g_pinMap40DIL[s_SENSE_i.pin]);
}
PERROR
C2650Cpu::waitForInterrupt(
Interrupt interrupt,
bool active,
UINT32 timeoutInMs
)
{
PERROR error = errorSuccess;
unsigned long startTime = millis();
unsigned long endTime = startTime + timeoutInMs;
int sense = (active ? LOW : HIGH);
int value = 0;
UINT8 intPin = g_pinMap40DIL[s__INTREQ_i.pin];
do
{
value = ::digitalRead(intPin);
if (value == sense)
{
break;
}
}
while (millis() < endTime);
if (value != sense)
{
error = errorTimeout;
}
Exit:
return error;
}
//
// The 2650 UM states that only INTACK asserted with OPREQ are all that are needed to get the
// interrupt acknowledged and the address returned. However, both MAME, Galaxia & Quasar show
// INTACK is only used to gate off ~REDC, i.e. the INTACK cycle is an IO read control
// (at least A14 and A15 low).
// FYI, Galaxia is hard coded to respond with 0x03.
//
PERROR
C2650Cpu::acknowledgeInterrupt(
UINT16 *response
)
{
digitalWrite(g_pinMap40DIL[s_M_IO_o.pin], LOW);
digitalWrite(g_pinMap40DIL[s_INTACK_o.pin], HIGH);
return read(0, response);
}
| bsd-2-clause |
ibudiselic/contest-problem-solutions | tc bef160/grafixMask.cpp | 1 | 9251 | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int maxr = 399;
const int maxc = 599;
char field[maxr+3][maxc+3];
int r1, c1, r2, c2, s;
vector<int> sol;
stack<pair<int, int> > rek;
class grafixMask {
public:
vector <int> sortedAreas(vector <string> rectangles) {
for (int i=0; i<=maxr+2; ++i) {
field[i][0] = 1;
field[i][maxc+2] = 1;
}
for (int i=1; i<=maxc+1; ++i) {
field[0][i] = 1;
field[maxr+2][i] = 1;
}
for (int i=0; i<rectangles.size(); ++i) {
sscanf(rectangles[i].c_str(), "%d %d %d %d", &r1, &c1, &r2, &c2);
++r1; ++r2;
++c1; ++c2;
for (int r=r1; r<=r2; ++r)
for (int c=c1; c<=c2; ++c) {
assert(r1 >= 1 && r1 <= maxr+1);
assert(c1 >= 1 && c1 <= maxc+1);
assert(r2 >= 1 && r2 <= maxr+1);
assert(c2 >= 1 && c2 <= maxc+1);
field[r][c] = 1;
}
}
for (int r=1; r<=maxr+1; ++r)
for (int c=1; c<=maxc+1; ++c)
if (!field[r][c]) {
field[r][c] = 1;
s = 0;
rek.push(make_pair(r, c));
while (!rek.empty()) {
r1 = rek.top().first; c1 = rek.top().second; rek.pop();
++s;
for (int dx=-1; dx<=1; ++dx)
for (int dy=-1; dy<=1; ++dy)
if (abs(dx)+abs(dy)==1 && !field[r1+dx][c1+dy]) {
rek.push(make_pair(r1+dx, c1+dy));
field[r1+dx][c1+dy] = 1;
}
}
sol.push_back(s);
}
sort(sol.begin(), sol.end());
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = {"0 292 399 307"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 116800, 116800 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, sortedAreas(Arg0)); }
void test_case_1() { string Arr0[] = {"48 192 351 207", "48 392 351 407", "120 52 135 547", "260 52 275 547"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 22816, 192608 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, sortedAreas(Arg0)); }
void test_case_2() { string Arr0[] = {"0 192 399 207", "0 392 399 407", "120 0 135 599", "260 0 275 599"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 22080, 22816, 22816, 23040, 23040, 23808, 23808, 23808, 23808 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, sortedAreas(Arg0)); }
void test_case_3() { string Arr0[] = {"50 300 199 300", "201 300 350 300", "200 50 200 299", "200 301 200 550"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 1, 239199 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, sortedAreas(Arg0)); }
void test_case_4() { string Arr0[] = {"0 20 399 20", "0 44 399 44", "0 68 399 68", "0 92 399 92",
"0 116 399 116", "0 140 399 140", "0 164 399 164", "0 188 399 188",
"0 212 399 212", "0 236 399 236", "0 260 399 260", "0 284 399 284",
"0 308 399 308", "0 332 399 332", "0 356 399 356", "0 380 399 380",
"0 404 399 404", "0 428 399 428", "0 452 399 452", "0 476 399 476",
"0 500 399 500", "0 524 399 524", "0 548 399 548", "0 572 399 572",
"0 596 399 596", "5 0 5 599", "21 0 21 599", "37 0 37 599",
"53 0 53 599", "69 0 69 599", "85 0 85 599", "101 0 101 599",
"117 0 117 599", "133 0 133 599", "149 0 149 599", "165 0 165 599",
"181 0 181 599", "197 0 197 599", "213 0 213 599", "229 0 229 599",
"245 0 245 599", "261 0 261 599", "277 0 277 599", "293 0 293 599",
"309 0 309 599", "325 0 325 599", "341 0 341 599", "357 0 357 599",
"373 0 373 599", "389 0 389 599"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 15, 30, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 100, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 200, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345, 345 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(4, Arg1, sortedAreas(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
grafixMask ___test;
___test.run_test(-1);
}
// END CUT HERE
| bsd-2-clause |
cedric-chaumont-st-dev/optee_os | core/arch/arm/plat-vexpress/vendor_props.c | 1 | 3299 | /*
* Copyright (c) 2016, Linaro Limited.
* 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 HOLDER 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 <tee/tee_svc.h>
#include <user_ta_header.h>
#include <util.h>
#include <kernel/tee_ta_manager.h>
#include <kernel/tee_common_otp.h>
#include <tee/tee_cryp_utl.h>
/*
* The data to hash is 48 bytes made up of:
* - 16 bytes: the UUID of the calling TA.
* - 32 bytes: the hardware device ID
* The resulting endorsement seed is 32 bytes.
*
* The output buffer is the "binary" struct defined in
* the "prop_value" union and therefore comprises:
* - 4 bytes: the size of the binary value data (32)
* - 32 bytes: the binary value data (endorsement seed)
*
* Note that this code assumes an endorsement seed
* size == device ID size for convenience.
*/
static TEE_Result get_prop_endorsement(struct tee_ta_session *sess,
void *buf, size_t *blen)
{
TEE_Result res;
uint32_t ta_endorsement_seed_size = 32;
uint8_t data[sizeof(TEE_UUID) + ta_endorsement_seed_size];
uint32_t bin[1 + ta_endorsement_seed_size / sizeof(uint32_t)];
uint32_t *bin_len = (uint32_t *)bin;
uint8_t *bin_val = (uint8_t *)(&bin[1]);
if (*blen < sizeof(bin)) {
*blen = sizeof(bin);
return TEE_ERROR_SHORT_BUFFER;
}
*blen = sizeof(bin);
memcpy(data, &sess->ctx->uuid, sizeof(TEE_UUID));
if (tee_otp_get_die_id(&data[sizeof(TEE_UUID)],
ta_endorsement_seed_size))
return TEE_ERROR_BAD_STATE;
res = tee_hash_createdigest(TEE_ALG_SHA256, data, sizeof(data),
bin_val, ta_endorsement_seed_size);
if (res != TEE_SUCCESS)
return TEE_ERROR_BAD_STATE;
*bin_len = ta_endorsement_seed_size;
return tee_svc_copy_to_user(sess, (void *)buf, bin, sizeof(bin));
}
static const struct tee_props vendor_propset_array_tee[] = {
{
.name = "com.microsoft.ta.endorsementSeed",
.prop_type = USER_TA_PROP_TYPE_BINARY_BLOCK,
.get_prop_func = get_prop_endorsement
},
};
const struct tee_vendor_props vendor_props_tee = {
.props = vendor_propset_array_tee,
.len = ARRAY_SIZE(vendor_propset_array_tee),
};
| bsd-2-clause |
tm604/rapidcheck | test/gen/TupleTests.cpp | 3 | 5369 | #include <catch.hpp>
#include <rapidcheck/catch.h>
#include "util/ArbitraryRandom.h"
#include "util/Predictable.h"
#include "util/GenUtils.h"
#include "rapidcheck/gen/Tuple.h"
#include "rapidcheck/gen/Create.h"
#include "rapidcheck/shrinkable/Operations.h"
using namespace rc;
using namespace rc::test;
TEST_CASE("gen::tuple") {
prop(
"the root value is a tuple of the root values from the composed"
" generators",
[](int x1, int x2, int x3) {
// TODO gen::constant
const auto gen =
gen::tuple(gen::just(x1), gen::just(x2), gen::just(x3));
const auto shrinkable = gen(Random(), 0);
RC_ASSERT(shrinkable.value() == std::make_tuple(x1, x2, x3));
});
prop("shrinks components from left to right",
[] {
auto number = gen::inRange<int>(0, 3);
const int x1 = *number;
const int x2 = *number;
const int x3 = *number;
auto gen = gen::tuple(genFixedCountdown(x1),
genFixedCountdown(x2),
genFixedCountdown(x3));
RC_ASSERT(shrinkable::all(
gen(Random(), 0),
[](const Shrinkable<std::tuple<int, int, int>> &s) {
const auto value = s.value();
auto shrinks = s.shrinks();
for (int x = std::get<0>(value) - 1; x >= 0; x--) {
const auto shrink = shrinks.next();
const auto expected =
std::make_tuple(x, std::get<1>(value), std::get<2>(value));
if (!shrink || (shrink->value() != expected)) {
return false;
}
}
for (int x = std::get<1>(value) - 1; x >= 0; x--) {
const auto shrink = shrinks.next();
const auto expected =
std::make_tuple(std::get<0>(value), x, std::get<2>(value));
if (!shrink || (shrink->value() != expected)) {
return false;
}
}
for (int x = std::get<2>(value) - 1; x >= 0; x--) {
const auto shrink = shrinks.next();
const auto expected =
std::make_tuple(std::get<0>(value), std::get<1>(value), x);
if (!shrink || (shrink->value() != expected)) {
return false;
}
}
return !shrinks.next();
}));
});
prop("passes the right size of each generator",
[] {
const int size = *gen::nonNegative<int>();
const auto result =
gen::tuple(genSize(), genSize(), genSize())(Random(), size);
RC_ASSERT(result.value() == std::make_tuple(size, size, size));
});
prop("splits the generator N times and passes the splits from left to right",
[](const Random &random) {
const auto result =
gen::tuple(genRandom(), genRandom(), genRandom())(random, 0);
Random r(random);
std::tuple<Random, Random, Random> expected;
std::get<0>(expected) = r.split();
std::get<1>(expected) = r.split();
std::get<2>(expected) = r.split();
RC_ASSERT(result.value() == expected);
});
prop("works with non-copyable types",
[](int v1, int v2) {
const auto xgen = gen::map(gen::just(v1),
[](int x) {
NonCopyable nc;
nc.value = x;
return nc;
});
const auto ygen = gen::map(gen::just(v2),
[](int x) {
NonCopyable nc;
nc.value = x;
return nc;
});
const auto shrinkable = gen::tuple(xgen, ygen)(Random(), 0);
const auto result = shrinkable.value();
RC_ASSERT(std::get<0>(result).value == v1);
RC_ASSERT(std::get<1>(result).value == v2);
});
prop(
"finds minimum if two of the values must larger than a third value"
" which must be larger than some other value",
[] {
static const auto makeShrinkable = [](int x) {
return shrinkable::shrinkRecur(
100, [](int value) { return shrink::towards(value, 0); });
};
int target = *gen::inRange<int>(0, 100);
Gen<int> gen1 = fn::constant(makeShrinkable(200));
Gen<int> gen2 = fn::constant(makeShrinkable(100));
Gen<int> gen3 = fn::constant(makeShrinkable(200));
const auto shrinkable = gen::tuple(gen1, gen2, gen3)(Random(), 0);
const auto result =
shrinkable::findLocalMin(shrinkable,
[=](const std::tuple<int, int, int> &x) {
return (std::get<1>(x) >= target) &&
(std::get<0>(x) > std::get<1>(x)) &&
(std::get<2>(x) > std::get<1>(x));
});
RC_ASSERT(result.first ==
std::make_tuple(target + 1, target, target + 1));
});
}
| bsd-2-clause |
khldragon/Sora | DebugTool/source/DebugPlotChannelLibrary/ShareChannelManager.cpp | 7 | 5964 | #include <Windows.h>
#include <stdio.h>
#include "Channel.h"
#include "DpSharedMemAllocator.h"
#include "DpFixedSizeSharedMemAllocator.h"
#include "RollbackManager.h"
#include "ShareChannelManager.h"
#include "Config.h"
using namespace SharedChannelTable;
struct _EnumPara
{
ChannelEnumCallback callback;
void * userData;
};
typedef bool (* ChannelTableEnumCallback)(ChannelTableItem * item, void * userData);
void SafeEnumChannelTable(ChannelTableItem * base, ChannelTableEnumCallback callback, void * userData);
void SafeEnumChannelTable(ChannelTableItem * base, ChannelTableEnumCallback callback, void * userData)
{
for (int i = 0; i < MAX_CHANNEL; ++i)
{
bool cont = true;
ChannelTableItem * item = base + i;
PreTableOperation(item);
callback(item, userData);
PostTableOperation(item);
if (!cont)
break;
}
}
static bool ChannelTableEnumCallbackFunc(ChannelTableItem * item, void * userData)
{
_EnumPara * para = (_EnumPara *)userData;
ChannelInfo2 info;
info.pidPloter = item->channelInfo.pidPlotter;
info.type = item->channelInfo.type;
strcpy_s(info.name, 256, item->channelInfo.name);
para->callback(&info, para->userData);
return true;
}
ShareChannelManager * ShareChannelManager::__instance = 0;
ShareChannelManager * __stdcall ShareChannelManager::Instance()
{
if (__instance == 0)
{
__instance = new ShareChannelManager();
}
return __instance;
}
void __stdcall ShareChannelManager::Release()
{
if (__instance != 0)
{
delete __instance;
__instance = 0;
}
}
Channel * ShareChannelManager::OpenForRead(int pid, const char * name, int type)
{
ChannelTableItem * itemSelected = 0;
int channelId = -1;
for (int i = 0; i < MAX_CHANNEL; ++i)
{
bool bBreak = false;
ChannelTableItem * item = this->_pChannelTableBase + i;
PreTableOperation(item);
if (
item->channelInfo.pidViewer == 0 && // no one is reading
item->channelInfo.pidPlotter == pid && // writer pid matches
item->channelInfo.type == type && // type matches
strcmp(item->channelInfo.name, name) == 0 // name matches
)
{
itemSelected = item;
channelId = i;
item->channelInfo.pidViewer = ::GetCurrentProcessId();
bBreak = true;
}
PostTableOperation(item);
if (bBreak) break;
}
if (itemSelected != 0)
{
Channel * channel = new Channel(itemSelected, _allocator, _memRollbackManager);
return channel;
}
return 0;
}
void ShareChannelManager::CloseForRead(Channel * pCh)
{
ChannelTableItem * item = pCh->ShareStruct();
PreTableOperation(item);
item->channelInfo.pidViewer = 0;
PostTableOperation(item);
delete pCh;
}
Channel * ShareChannelManager::OpenForWrite(const char * name, int type)
{
if (type == -1)
return 0;
ChannelTableItem * itemSelected = 0;
int channelId = -1;
for (int i = 0; i < MAX_CHANNEL; ++i)
{
bool bBreak = false;
ChannelTableItem * item = this->_pChannelTableBase + i;
PreTableOperation(item);
if (item->channelInfo.type == -1) // no reading && no writing
{
itemSelected = item;
channelId = i;
item->channelInfo.pidPlotter = ::GetCurrentProcessId();
item->channelInfo.type = type;
bBreak = true;
}
PostTableOperation(item);
if (bBreak) break;
}
if (itemSelected != 0)
{
Channel * channel = new Channel(itemSelected, _allocator, _memRollbackManager);
return channel;
}
return 0;
}
void ShareChannelManager::CloseForWrite(Channel * pCh)
{
ChannelTableItem * item = pCh->ShareStruct();
PreTableOperation(item);
item->channelInfo.pidPlotter = 0;
PostTableOperation(item);
delete pCh;
}
ShareChannelManager::ShareChannelManager()
{
_allocator = DpFixedSizeSharedMemAllocator::Create(L"/DbgPlot/Allocator", Config::ALLOC_BLOCK_SIZE(), Config::ALLOC_BLOCK_COUNT());
_smChannel = DpShareMemAllocator::Create(
L"/DbgPlot/ChannelList",
sizeof(RollbackStruct) + sizeof(ChannelTableItem) * MAX_CHANNEL,
ChannelListInitFunc,
this );
_rollbackStruct = (RollbackStruct *)_smChannel->GetAddress();
_pChannelTableBase = (ChannelTableItem *)(_rollbackStruct + 1);
_memRollbackManager = new MemRollbackManager();
_memRollbackManager->RollBackStruct = _rollbackStruct;
_memRollbackManager->tableBasePtr = _pChannelTableBase;
}
ShareChannelManager::~ShareChannelManager()
{
DpFixedSizeSharedMemAllocator::Release(_allocator);
delete _memRollbackManager;
ShareMem::FreeShareMem(_smChannel);
}
BOOL ShareChannelManager::ChannelListInitFunc(ShareMem* sm, void* context)
{
RollbackStruct * rollbackStruct = (RollbackStruct *)sm->GetAddress();
ChannelTableItem * channelTableBase = (ChannelTableItem *)(rollbackStruct + 1);
Init(rollbackStruct);
for (int i = 0; i < MAX_CHANNEL; ++i)
{
ChannelTableItem * item = channelTableBase + i;
Init(item);
}
return TRUE;
}
void ShareChannelManager::Enumerate(ChannelEnumCallback callback, void * userData)
{
GcSession * gcSession = new GcSession();
for (int i = 0; i < MAX_CHANNEL; ++i)
{
ChannelTableItem * item = this->_pChannelTableBase + i;
GC_Channel(item, _memRollbackManager, _allocator, gcSession);
PreTableOperation(item);
if (item->channelInfo.type != -1)
{
ChannelInfo2 chInfo;
chInfo.pidPloter = item->channelInfo.pidPlotter;
chInfo.type = item->channelInfo.type;
chInfo.name = item->channelInfo.name;
callback(&chInfo, userData);
}
PostTableOperation(item);
}
delete gcSession;
}
void ShareChannelManager::Gc()
{
GcSession * gcSession = new GcSession();
for (int i = 0; i < MAX_CHANNEL; ++i)
{
ChannelTableItem * item = this->_pChannelTableBase + i;
GC_Channel(item, _memRollbackManager, _allocator, gcSession);
}
delete gcSession;
}
int ShareChannelManager::FreeBlockCount()
{
int freeCount = 0;
Lock_Mem(_memRollbackManager);
if (IsDirty_Mem(_memRollbackManager))
{
Rollback_Mem(_memRollbackManager);
SetClean_Mem(_memRollbackManager);
}
freeCount = _allocator->FreeCount();
Unlock_Mem(_memRollbackManager);
return freeCount;
}
| bsd-2-clause |
ssaini4/RoboticLamp | mailbox.c | 11 | 7398 | /*
Copyright (c) 2012, Broadcom Europe Ltd.
Copyright (c) 2016, Jeremy Garff
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.
* Neither the name of the copyright holder 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 HOLDER 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mailbox.h"
void *mapmem(uint32_t base, uint32_t size) {
uint32_t pagemask = ~0UL ^ (getpagesize() - 1);
uint32_t offsetmask = getpagesize() - 1;
int mem_fd;
void *mem;
mem_fd = open("/dev/mem", O_RDWR | O_SYNC);
if (mem_fd < 0) {
perror("Can't open /dev/mem");
return NULL;
}
mem = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, mem_fd, base & pagemask);
if (mem == MAP_FAILED) {
perror("mmap error\n");
return NULL;
}
close(mem_fd);
return (char *)mem + (base & offsetmask);
}
void *unmapmem(void *addr, uint32_t size) {
uint32_t pagemask = ~0UL ^ (getpagesize() - 1);
uint32_t baseaddr = (uint32_t)addr & pagemask;
int s;
s = munmap((void *)baseaddr, size);
if (s != 0) {
perror("munmap error\n");
}
return NULL;
}
/*
* use ioctl to send mbox property message
*/
static int mbox_property(int file_desc, void *buf) {
int fd = file_desc;
int ret_val = -1;
if (fd < 0) {
fd = mbox_open();
}
if (fd >= 0) {
ret_val = ioctl(fd, IOCTL_MBOX_PROPERTY, buf);
if (ret_val < 0) {
perror("ioctl_set_msg failed\n");
}
}
if (file_desc < 0) {
mbox_close(fd);
}
return ret_val;
}
uint32_t mem_alloc(int file_desc, uint32_t size, uint32_t align, uint32_t flags) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x3000c; // (the tag id)
p[i++] = 12; // (size of the buffer)
p[i++] = 12; // (size of the data)
p[i++] = size; // (num bytes? or pages?)
p[i++] = align; // (alignment)
p[i++] = flags; // (MEM_FLAG_L1_NONALLOCATING)
p[i++] = 0x00000000; // end tag
p[0] = i*sizeof *p; // actual size
if (mbox_property(file_desc, p) < 0)
return 0;
else
return p[5];
}
uint32_t mem_free(int file_desc, uint32_t handle) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x3000f; // (the tag id)
p[i++] = 4; // (size of the buffer)
p[i++] = 4; // (size of the data)
p[i++] = handle;
p[i++] = 0x00000000; // end tag
p[0] = i*sizeof *p; // actual size
mbox_property(file_desc, p);
return p[5];
}
uint32_t mem_lock(int file_desc, uint32_t handle) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x3000d; // (the tag id)
p[i++] = 4; // (size of the buffer)
p[i++] = 4; // (size of the data)
p[i++] = handle;
p[i++] = 0x00000000; // end tag
p[0] = i*sizeof *p; // actual size
if (mbox_property(file_desc, p) < 0)
return ~0;
else
return p[5];
}
uint32_t mem_unlock(int file_desc, uint32_t handle) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x3000e; // (the tag id)
p[i++] = 4; // (size of the buffer)
p[i++] = 4; // (size of the data)
p[i++] = handle;
p[i++] = 0x00000000; // end tag
p[0] = i * sizeof(*p); // actual size
mbox_property(file_desc, p);
return p[5];
}
uint32_t execute_code(int file_desc, uint32_t code, uint32_t r0, uint32_t r1,
uint32_t r2, uint32_t r3, uint32_t r4, uint32_t r5) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x30010; // (the tag id)
p[i++] = 28; // (size of the buffer)
p[i++] = 28; // (size of the data)
p[i++] = code;
p[i++] = r0;
p[i++] = r1;
p[i++] = r2;
p[i++] = r3;
p[i++] = r4;
p[i++] = r5;
p[i++] = 0x00000000; // end tag
p[0] = i * sizeof(*p); // actual size
mbox_property(file_desc, p);
return p[5];
}
uint32_t qpu_enable(int file_desc, uint32_t enable) {
int i=0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x30012; // (the tag id)
p[i++] = 4; // (size of the buffer)
p[i++] = 4; // (size of the data)
p[i++] = enable;
p[i++] = 0x00000000; // end tag
p[0] = i * sizeof(*p); // actual size
mbox_property(file_desc, p);
return p[5];
}
uint32_t execute_qpu(int file_desc, uint32_t num_qpus, uint32_t control,
uint32_t noflush, uint32_t timeout) {
int i = 0;
uint32_t p[32];
p[i++] = 0; // size
p[i++] = 0x00000000; // process request
p[i++] = 0x30011; // (the tag id)
p[i++] = 16; // (size of the buffer)
p[i++] = 16; // (size of the data)
p[i++] = num_qpus;
p[i++] = control;
p[i++] = noflush;
p[i++] = timeout; // ms
p[i++] = 0x00000000; // end tag
p[0] = i * sizeof(*p); // actual size
mbox_property(file_desc, p);
return p[5];
}
int mbox_open(void) {
int file_desc;
char filename[64];
file_desc = open("/dev/vcio", 0);
if (file_desc >= 0) {
return file_desc;
}
// open a char device file used for communicating with kernel mbox driver
sprintf(filename, "/tmp/mailbox-%d", getpid());
unlink(filename);
if (mknod(filename, S_IFCHR|0600, makedev(100, 0)) < 0) {
perror("Failed to create mailbox device\n");
return -1;
}
file_desc = open(filename, 0);
if (file_desc < 0) {
perror("Can't open device file\n");
unlink(filename);
return -1;
}
unlink(filename);
return file_desc;
}
void mbox_close(int file_desc) {
close(file_desc);
}
| bsd-2-clause |
gale320/sctp-refimpl | APPS/incast/display_ele_sink.c | 11 | 2619 | /*-
* Copyright (c) 2011, by Randall Stewart.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of the authors 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 <incast_fmt.h>
#include <sys/signal.h>
int
main(int argc, char **argv)
{
int i;
FILE *io;
char *infile=NULL;
int infile_size=sizeof(long);
struct elephant_sink_rec sink;
while ((i = getopt(argc, argv, "r:?36")) != EOF) {
switch (i) {
case '3':
/* Reading 32 bit mode */
infile_size = 4;
break;
case '6':
infile_size = 8;
break;
case 'r':
infile = optarg;
break;
default:
case '?':
use:
printf("Use %s -r infile\n", argv[0]);
exit(0);
break;
};
};
if (infile == NULL) {
goto use;
}
io = fopen(infile, "r");
if (io == NULL) {
printf("Can't open file %s - err:%d\n", infile, errno);
return (-1);
}
while(read_a_sink_rec(&sink, io, infile_size) > 0) {
print_an_address((struct sockaddr *)&sink.from, 0);
timespecsub(&sink.mono_end, &sink.mono_start);
printf(" - bytes:%d time:%ld.%9.9ld\n",
sink.number_bytes,
(unsigned long)sink.mono_end.tv_sec,
(unsigned long)sink.mono_end.tv_nsec);
}
fclose(io);
return (0);
}
| bsd-2-clause |
haitao52198/seL4 | src/arch/x86/machine/registerset.c | 15 | 2246 | /*
* Copyright 2014, General Dynamics C4 Systems
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(GD_GPL)
*/
#include <arch/machine/registerset.h>
#include <arch/machine/fpu.h>
#include <arch/object/structures.h>
const register_t msgRegisters[] = {
EDI, EBP
};
const register_t frameRegisters[] = {
FaultEIP, ESP, EFLAGS, EAX, EBX, ECX, EDX, ESI, EDI, EBP
};
const register_t gpRegisters[] = {
TLS_BASE, FS, GS
};
const register_t exceptionMessage[] = {
FaultEIP, ESP, EFLAGS
};
const register_t syscallMessage[] = {
EAX, EBX, ECX, EDX, ESI, EDI, EBP, NextEIP, ESP, EFLAGS
};
void Arch_initContext(user_context_t* context)
{
context->registers[EAX] = 0;
context->registers[EBX] = 0;
context->registers[ECX] = 0;
context->registers[EDX] = 0;
context->registers[ESI] = 0;
context->registers[EDI] = 0;
context->registers[EBP] = 0;
context->registers[DS] = SEL_DS_3;
context->registers[ES] = SEL_DS_3;
context->registers[FS] = SEL_NULL;
context->registers[GS] = SEL_NULL;
context->registers[TLS_BASE] = 0;
context->registers[Error] = 0;
context->registers[FaultEIP] = 0;
context->registers[NextEIP] = 0; /* overwritten by setNextPC() later on */
context->registers[CS] = SEL_CS_3;
context->registers[EFLAGS] = BIT(9) | BIT(1); /* enable interrupts and set bit 1 which is always 1 */
context->registers[ESP] = 0; /* userland has to set it after entry */
context->registers[SS] = SEL_DS_3;
Arch_initFpuContext(context);
}
word_t sanitiseRegister(register_t reg, word_t v)
{
if (reg == EFLAGS) {
v |= BIT(1); /* reserved bit that must be set to 1 */
v &= ~BIT(3); /* reserved bit that must be set to 0 */
v &= ~BIT(5); /* reserved bit that must be set to 0 */
v |= BIT(9); /* interrupts must be enabled in userland */
v &= MASK(12); /* bits 12:31 have to be 0 */
}
if (reg == FS || reg == GS) {
if (v != SEL_TLS && v != SEL_IPCBUF) {
v = 0;
}
}
return v;
}
| bsd-2-clause |
simanstar/nginx-1.0.14_comment | src/os/unix/ngx_darwin_sendfile_chain.c | 17 | 9753 |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
/*
* It seems that Darwin 9.4 (Mac OS X 1.5) sendfile() has the same
* old bug as early FreeBSD sendfile() syscall:
* http://www.freebsd.org/cgi/query-pr.cgi?pr=33771
*
* Besides sendfile() has another bug: if one calls sendfile()
* with both a header and a trailer, then sendfile() ignores a file part
* at all and sends only the header and the trailer together.
* For this reason we send a trailer only if there is no a header.
*
* Although sendfile() allows to pass a header or a trailer,
* it may send the header or the trailer and a part of the file
* in different packets. And FreeBSD workaround (TCP_NOPUSH option)
* does not help.
*/
#if (IOV_MAX > 64)
#define NGX_HEADERS 64
#define NGX_TRAILERS 64
#else
#define NGX_HEADERS IOV_MAX
#define NGX_TRAILERS IOV_MAX
#endif
ngx_chain_t *
ngx_darwin_sendfile_chain(ngx_connection_t *c, ngx_chain_t *in, off_t limit)
{
int rc;
u_char *prev;
off_t size, send, prev_send, aligned, sent, fprev;
off_t header_size, file_size;
ngx_uint_t eintr, complete;
ngx_err_t err;
ngx_buf_t *file;
ngx_array_t header, trailer;
ngx_event_t *wev;
ngx_chain_t *cl;
struct sf_hdtr hdtr;
struct iovec *iov, headers[NGX_HEADERS], trailers[NGX_TRAILERS];
wev = c->write;
if (!wev->ready) {
return in;
}
#if (NGX_HAVE_KQUEUE)
if ((ngx_event_flags & NGX_USE_KQUEUE_EVENT) && wev->pending_eof) {
(void) ngx_connection_error(c, wev->kq_errno,
"kevent() reported about an closed connection");
wev->error = 1;
return NGX_CHAIN_ERROR;
}
#endif
/* the maximum limit size is the maximum size_t value - the page size */
if (limit == 0 || limit > (off_t) (NGX_MAX_SIZE_T_VALUE - ngx_pagesize)) {
limit = NGX_MAX_SIZE_T_VALUE - ngx_pagesize;
}
send = 0;
header.elts = headers;
header.size = sizeof(struct iovec);
header.nalloc = NGX_HEADERS;
header.pool = c->pool;
trailer.elts = trailers;
trailer.size = sizeof(struct iovec);
trailer.nalloc = NGX_TRAILERS;
trailer.pool = c->pool;
for ( ;; ) {
file = NULL;
file_size = 0;
header_size = 0;
eintr = 0;
complete = 0;
prev_send = send;
header.nelts = 0;
trailer.nelts = 0;
/* create the header iovec and coalesce the neighbouring bufs */
prev = NULL;
iov = NULL;
for (cl = in;
cl && header.nelts < IOV_MAX && send < limit;
cl = cl->next)
{
if (ngx_buf_special(cl->buf)) {
continue;
}
if (!ngx_buf_in_memory_only(cl->buf)) {
break;
}
size = cl->buf->last - cl->buf->pos;
if (send + size > limit) {
size = limit - send;
}
if (prev == cl->buf->pos) {
iov->iov_len += (size_t) size;
} else {
iov = ngx_array_push(&header);
if (iov == NULL) {
return NGX_CHAIN_ERROR;
}
iov->iov_base = (void *) cl->buf->pos;
iov->iov_len = (size_t) size;
}
prev = cl->buf->pos + (size_t) size;
header_size += size;
send += size;
}
if (cl && cl->buf->in_file && send < limit) {
file = cl->buf;
/* coalesce the neighbouring file bufs */
do {
size = cl->buf->file_last - cl->buf->file_pos;
if (send + size > limit) {
size = limit - send;
aligned = (cl->buf->file_pos + size + ngx_pagesize - 1)
& ~((off_t) ngx_pagesize - 1);
if (aligned <= cl->buf->file_last) {
size = aligned - cl->buf->file_pos;
}
}
file_size += size;
send += size;
fprev = cl->buf->file_pos + size;
cl = cl->next;
} while (cl
&& cl->buf->in_file
&& send < limit
&& file->file->fd == cl->buf->file->fd
&& fprev == cl->buf->file_pos);
}
if (file && header.nelts == 0) {
/* create the trailer iovec and coalesce the neighbouring bufs */
prev = NULL;
iov = NULL;
while (cl && header.nelts < IOV_MAX && send < limit) {
if (ngx_buf_special(cl->buf)) {
cl = cl->next;
continue;
}
if (!ngx_buf_in_memory_only(cl->buf)) {
break;
}
size = cl->buf->last - cl->buf->pos;
if (send + size > limit) {
size = limit - send;
}
if (prev == cl->buf->pos) {
iov->iov_len += (size_t) size;
} else {
iov = ngx_array_push(&trailer);
if (iov == NULL) {
return NGX_CHAIN_ERROR;
}
iov->iov_base = (void *) cl->buf->pos;
iov->iov_len = (size_t) size;
}
prev = cl->buf->pos + (size_t) size;
send += size;
cl = cl->next;
}
}
if (file) {
/*
* sendfile() returns EINVAL if sf_hdtr's count is 0,
* but corresponding pointer is not NULL
*/
hdtr.headers = header.nelts ? (struct iovec *) header.elts: NULL;
hdtr.hdr_cnt = header.nelts;
hdtr.trailers = trailer.nelts ? (struct iovec *) trailer.elts: NULL;
hdtr.trl_cnt = trailer.nelts;
sent = header_size + file_size;
ngx_log_debug3(NGX_LOG_DEBUG_EVENT, c->log, 0,
"sendfile: @%O %O h:%O",
file->file_pos, sent, header_size);
rc = sendfile(file->file->fd, c->fd, file->file_pos,
&sent, &hdtr, 0);
if (rc == -1) {
err = ngx_errno;
switch (err) {
case NGX_EAGAIN:
break;
case NGX_EINTR:
eintr = 1;
break;
default:
wev->error = 1;
(void) ngx_connection_error(c, err, "sendfile() failed");
return NGX_CHAIN_ERROR;
}
ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, err,
"sendfile() sent only %O bytes", sent);
}
if (rc == 0 && sent == 0) {
/*
* if rc and sent equal to zero, then someone
* has truncated the file, so the offset became beyond
* the end of the file
*/
ngx_log_error(NGX_LOG_ALERT, c->log, 0,
"sendfile() reported that \"%s\" was truncated",
file->file->name.data);
return NGX_CHAIN_ERROR;
}
ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,
"sendfile: %d, @%O %O:%O",
rc, file->file_pos, sent, file_size + header_size);
} else {
rc = writev(c->fd, header.elts, header.nelts);
ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,
"writev: %d of %uz", rc, send);
if (rc == -1) {
err = ngx_errno;
switch (err) {
case NGX_EAGAIN:
break;
case NGX_EINTR:
eintr = 1;
break;
default:
wev->error = 1;
ngx_connection_error(c, err, "writev() failed");
return NGX_CHAIN_ERROR;
}
ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, err,
"writev() not ready");
}
sent = rc > 0 ? rc : 0;
}
if (send - prev_send == sent) {
complete = 1;
}
c->sent += sent;
for (cl = in; cl; cl = cl->next) {
if (ngx_buf_special(cl->buf)) {
continue;
}
if (sent == 0) {
break;
}
size = ngx_buf_size(cl->buf);
if (sent >= size) {
sent -= size;
if (ngx_buf_in_memory(cl->buf)) {
cl->buf->pos = cl->buf->last;
}
if (cl->buf->in_file) {
cl->buf->file_pos = cl->buf->file_last;
}
continue;
}
if (ngx_buf_in_memory(cl->buf)) {
cl->buf->pos += (size_t) sent;
}
if (cl->buf->in_file) {
cl->buf->file_pos += sent;
}
break;
}
if (eintr) {
continue;
}
if (!complete) {
wev->ready = 0;
return cl;
}
if (send >= limit || cl == NULL) {
return cl;
}
in = cl;
}
}
| bsd-2-clause |
hoangt/ScaffCC | clang/test/SemaCXX/warn-sign-conversion.cpp | 18 | 3655 | // RUN: %clang_cc1 -verify -fsyntax-only -Wsign-conversion %s
// NOTE: When a 'enumeral mismatch' warning is implemented then expect several
// of the following cases to be impacted.
// namespace for anonymous enums tests
namespace test1 {
enum { A };
enum { B = -1 };
template <typename T> struct Foo {
enum { C };
enum { D = ~0U };
};
enum { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1a = 1 ? i : Foo<bool>::D; // expected-warning {{test1::Foo<bool>::<anonymous enum at }}
int d1b = 1 ? i : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5>' to 'int'}}
int d2a = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::<anonymous enum at }}
int d2b = 1 ? Foo<bool>::D : i; // expected-warning {{warn-sign-conversion.cpp:13:5>' to 'int'}}
int d3a = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::<anonymous enum at }}
int d3b = 1 ? B : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5>' to 'int'}}
int d4a = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::<anonymous enum at }}
int d4b = 1 ? Foo<bool>::D : B; // expected-warning {{warn-sign-conversion.cpp:13:5>' to 'int'}}
int e1a = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test1::<anonymous enum at }}
int e1b = 1 ? i : E; // expected-warning {{warn-sign-conversion.cpp:16:3>' to 'int'}}
int e2a = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test1::<anonymous enum at }}
int e2b = 1 ? E : i; // expected-warning {{warn-sign-conversion.cpp:16:3>' to 'int'}}
int e3a = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test1::<anonymous enum at }}
int e3b = 1 ? E : B; // expected-warning {{warn-sign-conversion.cpp:16:3>' to 'int'}}
int e4a = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test1::<anonymous enum at }}
int e4b = 1 ? B : E; // expected-warning {{warn-sign-conversion.cpp:16:3>' to 'int'}}
}
}
// namespace for named enums tests
namespace test2 {
enum Named1 { A };
enum Named2 { B = -1 };
template <typename T> struct Foo {
enum Named3 { C };
enum Named4 { D = ~0U };
};
enum Named5 { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1 = 1 ? i : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d2 = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d3 = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d4 = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
}
}
| bsd-2-clause |
gordoncww/ruby-debug-base19 | ext/ruby_debug/breakpoint.c | 50 | 14870 | #include <ruby.h>
#include <stdio.h>
#include <vm_core.h>
#include <iseq.h>
#include "ruby_debug.h"
VALUE rdebug_breakpoints = Qnil;
VALUE rdebug_catchpoints;
static VALUE cBreakpoint;
static ID idEval;
static VALUE
eval_expression(VALUE args)
{
return rb_funcall2(rb_mKernel, idEval, 2, RARRAY_PTR(args));
}
int
check_breakpoint_hit_condition(VALUE breakpoint)
{
debug_breakpoint_t *debug_breakpoint;
if(breakpoint == Qnil)
return 0;
Data_Get_Struct(breakpoint, debug_breakpoint_t, debug_breakpoint);
debug_breakpoint->hit_count++;
if (!Qtrue == debug_breakpoint->enabled) return 0;
switch(debug_breakpoint->hit_condition)
{
case HIT_COND_NONE:
return 1;
case HIT_COND_GE:
{
if(debug_breakpoint->hit_count >= debug_breakpoint->hit_value)
return 1;
break;
}
case HIT_COND_EQ:
{
if(debug_breakpoint->hit_count == debug_breakpoint->hit_value)
return 1;
break;
}
case HIT_COND_MOD:
{
if(debug_breakpoint->hit_count % debug_breakpoint->hit_value == 0)
return 1;
break;
}
}
return 0;
}
static int
check_breakpoint_by_pos(VALUE breakpoint, char *file, int line)
{
debug_breakpoint_t *debug_breakpoint;
if(breakpoint == Qnil)
return 0;
Data_Get_Struct(breakpoint, debug_breakpoint_t, debug_breakpoint);
if (!Qtrue == debug_breakpoint->enabled) return 0;
if(debug_breakpoint->type != BP_POS_TYPE)
return 0;
if(debug_breakpoint->pos.line != line)
return 0;
if(filename_cmp(debug_breakpoint->source, file))
return 1;
return 0;
}
int
check_breakpoint_by_method(VALUE breakpoint, VALUE klass, ID mid, VALUE self)
{
debug_breakpoint_t *debug_breakpoint;
if(breakpoint == Qnil)
return 0;
Data_Get_Struct(breakpoint, debug_breakpoint_t, debug_breakpoint);
if (!Qtrue == debug_breakpoint->enabled) return 0;
if(debug_breakpoint->type != BP_METHOD_TYPE)
return 0;
if(debug_breakpoint->pos.mid != mid)
return 0;
if(classname_cmp(debug_breakpoint->source, klass))
return 1;
if ((rb_type(self) == T_CLASS) &&
classname_cmp(debug_breakpoint->source, self))
return 1;
return 0;
}
VALUE
check_breakpoints_by_pos(debug_context_t *debug_context, char *file, int line)
{
VALUE breakpoint;
int i;
if(!CTX_FL_TEST(debug_context, CTX_FL_ENABLE_BKPT))
return Qnil;
if(check_breakpoint_by_pos(debug_context->breakpoint, file, line))
return debug_context->breakpoint;
if(RARRAY_LEN(rdebug_breakpoints) == 0)
return Qnil;
for(i = 0; i < RARRAY_LEN(rdebug_breakpoints); i++)
{
breakpoint = rb_ary_entry(rdebug_breakpoints, i);
if(check_breakpoint_by_pos(breakpoint, file, line))
return breakpoint;
}
return Qnil;
}
VALUE
check_breakpoints_by_method(debug_context_t *debug_context, VALUE klass, ID mid, VALUE self)
{
VALUE breakpoint;
int i;
if(!CTX_FL_TEST(debug_context, CTX_FL_ENABLE_BKPT))
return Qnil;
if(check_breakpoint_by_method(debug_context->breakpoint, klass, mid, self))
return debug_context->breakpoint;
if(RARRAY_LEN(rdebug_breakpoints) == 0)
return Qnil;
for(i = 0; i < RARRAY_LEN(rdebug_breakpoints); i++)
{
breakpoint = rb_ary_entry(rdebug_breakpoints, i);
if(check_breakpoint_by_method(breakpoint, klass, mid, self))
return breakpoint;
}
return Qnil;
}
int
check_breakpoint_expression(VALUE breakpoint, VALUE binding)
{
debug_breakpoint_t *debug_breakpoint;
VALUE args, expr_result;
Data_Get_Struct(breakpoint, debug_breakpoint_t, debug_breakpoint);
if(NIL_P(debug_breakpoint->expr))
return 1;
args = rb_ary_new3(2, debug_breakpoint->expr, binding);
expr_result = rb_protect(eval_expression, args, 0);
return RTEST(expr_result);
}
static void
breakpoint_mark(void *data)
{
debug_breakpoint_t *breakpoint;
breakpoint = (debug_breakpoint_t *)data;
rb_gc_mark(breakpoint->source);
rb_gc_mark(breakpoint->expr);
}
VALUE
create_breakpoint_from_args(int argc, VALUE *argv, int id)
{
VALUE source, pos, expr;
debug_breakpoint_t *breakpoint;
int type;
if(rb_scan_args(argc, argv, "21", &source, &pos, &expr) == 2)
{
expr = Qnil;
}
type = FIXNUM_P(pos) ? BP_POS_TYPE : BP_METHOD_TYPE;
if(type == BP_POS_TYPE)
source = StringValue(source);
else
pos = StringValue(pos);
breakpoint = ALLOC(debug_breakpoint_t);
breakpoint->id = id;
breakpoint->source = source;
breakpoint->type = type;
if(type == BP_POS_TYPE)
breakpoint->pos.line = FIX2INT(pos);
else
breakpoint->pos.mid = rb_intern(RSTRING_PTR(pos));
breakpoint->enabled = Qtrue;
breakpoint->expr = NIL_P(expr) ? expr: StringValue(expr);
breakpoint->hit_count = 0;
breakpoint->hit_value = 0;
breakpoint->hit_condition = HIT_COND_NONE;
return Data_Wrap_Struct(cBreakpoint, breakpoint_mark, xfree, breakpoint);
}
/*
* call-seq:
* Debugger.remove_breakpoint(id) -> breakpoint
*
* Removes breakpoint by its id.
* <i>id</i> is an identificator of a breakpoint.
*/
VALUE
rdebug_remove_breakpoint(VALUE self, VALUE id_value)
{
int i;
int id;
VALUE breakpoint;
debug_breakpoint_t *debug_breakpoint;
id = FIX2INT(id_value);
for( i = 0; i < RARRAY_LEN(rdebug_breakpoints); i += 1 )
{
breakpoint = rb_ary_entry(rdebug_breakpoints, i);
Data_Get_Struct(breakpoint, debug_breakpoint_t, debug_breakpoint);
if(debug_breakpoint->id == id)
{
rb_ary_delete_at(rdebug_breakpoints, i);
return breakpoint;
}
}
return Qnil;
}
/*
* call-seq:
* Debugger.catchpoints -> hash
*
* Returns a current catchpoints, which is a hash exception names that will
* trigger a debugger when raised. The values are the number of times taht
* catchpoint was hit, initially 0.
*/
VALUE
debug_catchpoints(VALUE self)
{
debug_check_started();
return rdebug_catchpoints;
}
/*
* call-seq:
* Debugger.catchpoint(string) -> string
*
* Sets catchpoint. Returns the string passed.
*/
VALUE
rdebug_add_catchpoint(VALUE self, VALUE value)
{
debug_check_started();
if (TYPE(value) != T_STRING) {
rb_raise(rb_eTypeError, "value of a catchpoint must be String");
}
rb_hash_aset(rdebug_catchpoints, rb_str_dup(value), INT2FIX(0));
return value;
}
/*
* call-seq:
* context.breakpoint -> breakpoint
*
* Returns a context-specific temporary Breakpoint object.
*/
VALUE
context_breakpoint(VALUE self)
{
debug_context_t *debug_context;
debug_check_started();
Data_Get_Struct(self, debug_context_t, debug_context);
return debug_context->breakpoint;
}
/*
* call-seq:
* context.set_breakpoint(source, pos, condition = nil) -> breakpoint
*
* Sets a context-specific temporary breakpoint, which can be used to implement
* 'Run to Cursor' debugger function. When this breakpoint is reached, it will be
* cleared out.
*
* <i>source</i> is a name of a file or a class.
* <i>pos</i> is a line number or a method name if <i>source</i> is a class name.
* <i>condition</i> is a string which is evaluated to +true+ when this breakpoint
* is activated.
*/
VALUE
context_set_breakpoint(int argc, VALUE *argv, VALUE self)
{
VALUE result;
debug_context_t *debug_context;
debug_check_started();
Data_Get_Struct(self, debug_context_t, debug_context);
result = create_breakpoint_from_args(argc, argv, 0);
debug_context->breakpoint = result;
return result;
}
/*
* call-seq:
* breakpoint.enabled?
*
* Returns whether breakpoint is enabled or not.
*/
static VALUE
breakpoint_enabled(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return breakpoint->enabled;
}
/*
* call-seq:
* breakpoint.enabled = bool
*
* Enables or disables breakpoint.
*/
static VALUE
breakpoint_set_enabled(VALUE self, VALUE bool)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return breakpoint->enabled = bool;
}
/*
* call-seq:
* breakpoint.source -> string
*
* Returns a source of the breakpoint.
*/
static VALUE
breakpoint_source(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return breakpoint->source;
}
/*
* call-seq:
* breakpoint.source = string
*
* Sets the source of the breakpoint.
*/
static VALUE
breakpoint_set_source(VALUE self, VALUE value)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
breakpoint->source = StringValue(value);
return value;
}
/*
* call-seq:
* breakpoint.pos -> string or int
*
* Returns the position of this breakpoint.
*/
static VALUE
breakpoint_pos(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
if(breakpoint->type == BP_METHOD_TYPE)
return rb_str_new2(rb_id2name(breakpoint->pos.mid));
else
return INT2FIX(breakpoint->pos.line);
}
/*
* call-seq:
* breakpoint.pos = string or int
*
* Sets the position of this breakpoint.
*/
static VALUE
breakpoint_set_pos(VALUE self, VALUE value)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
if(breakpoint->type == BP_METHOD_TYPE)
{
breakpoint->pos.mid = rb_to_id(StringValue(value));
}
else
breakpoint->pos.line = FIX2INT(value);
return value;
}
/*
* call-seq:
* breakpoint.expr -> string
*
* Returns a codition expression when this breakpoint should be activated.
*/
static VALUE
breakpoint_expr(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return breakpoint->expr;
}
/*
* call-seq:
* breakpoint.expr = string | nil
*
* Sets the codition expression when this breakpoint should be activated.
*/
static VALUE
breakpoint_set_expr(VALUE self, VALUE expr)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
breakpoint->expr = NIL_P(expr) ? expr: StringValue(expr);
return expr;
}
/*
* call-seq:
* breakpoint.id -> int
*
* Returns id of the breakpoint.
*/
static VALUE
breakpoint_id(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return INT2FIX(breakpoint->id);
}
/*
* call-seq:
* breakpoint.hit_count -> int
*
* Returns the hit count of the breakpoint.
*/
static VALUE
breakpoint_hit_count(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return INT2FIX(breakpoint->hit_count);
}
/*
* call-seq:
* breakpoint.hit_value -> int
*
* Returns the hit value of the breakpoint.
*/
static VALUE
breakpoint_hit_value(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
return INT2FIX(breakpoint->hit_value);
}
/*
* call-seq:
* breakpoint.hit_value = int
*
* Sets the hit value of the breakpoint.
*/
static VALUE
breakpoint_set_hit_value(VALUE self, VALUE value)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
breakpoint->hit_value = FIX2INT(value);
return value;
}
/*
* call-seq:
* breakpoint.hit_condition -> symbol
*
* Returns the hit condition of the breakpoint:
*
* +nil+ if it is an unconditional breakpoint, or
* :greater_or_equal, :equal, :modulo
*/
static VALUE
breakpoint_hit_condition(VALUE self)
{
debug_breakpoint_t *breakpoint;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
switch(breakpoint->hit_condition)
{
case HIT_COND_GE:
return ID2SYM(rb_intern("greater_or_equal"));
case HIT_COND_EQ:
return ID2SYM(rb_intern("equal"));
case HIT_COND_MOD:
return ID2SYM(rb_intern("modulo"));
case HIT_COND_NONE:
default:
return Qnil;
}
}
/*
* call-seq:
* breakpoint.hit_condition = symbol
*
* Sets the hit condition of the breakpoint which must be one of the following values:
*
* +nil+ if it is an unconditional breakpoint, or
* :greater_or_equal(:ge), :equal(:eq), :modulo(:mod)
*/
static VALUE
breakpoint_set_hit_condition(VALUE self, VALUE value)
{
debug_breakpoint_t *breakpoint;
ID id_value;
Data_Get_Struct(self, debug_breakpoint_t, breakpoint);
id_value = rb_to_id(value);
if(rb_intern("greater_or_equal") == id_value || rb_intern("ge") == id_value)
breakpoint->hit_condition = HIT_COND_GE;
else if(rb_intern("equal") == id_value || rb_intern("eq") == id_value)
breakpoint->hit_condition = HIT_COND_EQ;
else if(rb_intern("modulo") == id_value || rb_intern("mod") == id_value)
breakpoint->hit_condition = HIT_COND_MOD;
else
rb_raise(rb_eArgError, "Invalid condition parameter");
return value;
}
/*
* Document-class: Breakpoint
*
* == Summary
*
* This class represents a breakpoint. It defines position of the breakpoint and
* condition when this breakpoint should be triggered.
*/
void
Init_breakpoint()
{
cBreakpoint = rb_define_class_under(mDebugger, "Breakpoint", rb_cObject);
rb_define_method(cBreakpoint, "enabled=", breakpoint_set_enabled, 1);
rb_define_method(cBreakpoint, "enabled?", breakpoint_enabled, 0);
rb_define_method(cBreakpoint, "expr", breakpoint_expr, 0);
rb_define_method(cBreakpoint, "expr=", breakpoint_set_expr, 1);
rb_define_method(cBreakpoint, "hit_condition", breakpoint_hit_condition, 0);
rb_define_method(cBreakpoint, "hit_condition=", breakpoint_set_hit_condition, 1);
rb_define_method(cBreakpoint, "hit_count", breakpoint_hit_count, 0);
rb_define_method(cBreakpoint, "hit_value", breakpoint_hit_value, 0);
rb_define_method(cBreakpoint, "hit_value=", breakpoint_set_hit_value, 1);
rb_define_method(cBreakpoint, "id", breakpoint_id, 0);
rb_define_method(cBreakpoint, "pos", breakpoint_pos, 0);
rb_define_method(cBreakpoint, "pos=", breakpoint_set_pos, 1);
rb_define_method(cBreakpoint, "source", breakpoint_source, 0);
rb_define_method(cBreakpoint, "source=", breakpoint_set_source, 1);
idEval = rb_intern("eval");
rdebug_catchpoints = rb_hash_new();
}
| bsd-2-clause |
andrewjylee/omniplay | linux-lts-quantal-3.5.0/arch/mips/jz4740/time.c | 7528 | 3824 | /*
* Copyright (C) 2010, Lars-Peter Clausen <lars@metafoo.de>
* JZ4740 platform time support
*
* This program 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 2 of the License, or (at your
* option) any later version.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/clockchips.h>
#include <asm/mach-jz4740/irq.h>
#include <asm/time.h>
#include "clock.h"
#include "timer.h"
#define TIMER_CLOCKEVENT 0
#define TIMER_CLOCKSOURCE 1
static uint16_t jz4740_jiffies_per_tick;
static cycle_t jz4740_clocksource_read(struct clocksource *cs)
{
return jz4740_timer_get_count(TIMER_CLOCKSOURCE);
}
static struct clocksource jz4740_clocksource = {
.name = "jz4740-timer",
.rating = 200,
.read = jz4740_clocksource_read,
.mask = CLOCKSOURCE_MASK(16),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static irqreturn_t jz4740_clockevent_irq(int irq, void *devid)
{
struct clock_event_device *cd = devid;
jz4740_timer_ack_full(TIMER_CLOCKEVENT);
if (cd->mode != CLOCK_EVT_MODE_PERIODIC)
jz4740_timer_disable(TIMER_CLOCKEVENT);
cd->event_handler(cd);
return IRQ_HANDLED;
}
static void jz4740_clockevent_set_mode(enum clock_event_mode mode,
struct clock_event_device *cd)
{
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
jz4740_timer_set_count(TIMER_CLOCKEVENT, 0);
jz4740_timer_set_period(TIMER_CLOCKEVENT, jz4740_jiffies_per_tick);
case CLOCK_EVT_MODE_RESUME:
jz4740_timer_irq_full_enable(TIMER_CLOCKEVENT);
jz4740_timer_enable(TIMER_CLOCKEVENT);
break;
case CLOCK_EVT_MODE_ONESHOT:
case CLOCK_EVT_MODE_SHUTDOWN:
jz4740_timer_disable(TIMER_CLOCKEVENT);
break;
default:
break;
}
}
static int jz4740_clockevent_set_next(unsigned long evt,
struct clock_event_device *cd)
{
jz4740_timer_set_count(TIMER_CLOCKEVENT, 0);
jz4740_timer_set_period(TIMER_CLOCKEVENT, evt);
jz4740_timer_enable(TIMER_CLOCKEVENT);
return 0;
}
static struct clock_event_device jz4740_clockevent = {
.name = "jz4740-timer",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
.set_next_event = jz4740_clockevent_set_next,
.set_mode = jz4740_clockevent_set_mode,
.rating = 200,
.irq = JZ4740_IRQ_TCU0,
};
static struct irqaction timer_irqaction = {
.handler = jz4740_clockevent_irq,
.flags = IRQF_PERCPU | IRQF_TIMER,
.name = "jz4740-timerirq",
.dev_id = &jz4740_clockevent,
};
void __init plat_time_init(void)
{
int ret;
uint32_t clk_rate;
uint16_t ctrl;
jz4740_timer_init();
clk_rate = jz4740_clock_bdata.ext_rate >> 4;
jz4740_jiffies_per_tick = DIV_ROUND_CLOSEST(clk_rate, HZ);
clockevent_set_clock(&jz4740_clockevent, clk_rate);
jz4740_clockevent.min_delta_ns = clockevent_delta2ns(100, &jz4740_clockevent);
jz4740_clockevent.max_delta_ns = clockevent_delta2ns(0xffff, &jz4740_clockevent);
jz4740_clockevent.cpumask = cpumask_of(0);
clockevents_register_device(&jz4740_clockevent);
ret = clocksource_register_hz(&jz4740_clocksource, clk_rate);
if (ret)
printk(KERN_ERR "Failed to register clocksource: %d\n", ret);
setup_irq(JZ4740_IRQ_TCU0, &timer_irqaction);
ctrl = JZ_TIMER_CTRL_PRESCALE_16 | JZ_TIMER_CTRL_SRC_EXT;
jz4740_timer_set_ctrl(TIMER_CLOCKEVENT, ctrl);
jz4740_timer_set_ctrl(TIMER_CLOCKSOURCE, ctrl);
jz4740_timer_set_period(TIMER_CLOCKEVENT, jz4740_jiffies_per_tick);
jz4740_timer_irq_full_enable(TIMER_CLOCKEVENT);
jz4740_timer_set_period(TIMER_CLOCKSOURCE, 0xffff);
jz4740_timer_enable(TIMER_CLOCKEVENT);
jz4740_timer_enable(TIMER_CLOCKSOURCE);
}
| bsd-2-clause |
aosm/WebKit | win/WebSerializedJSValue.cpp | 142 | 3873 | /*
* Copyright (C) 2009 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. 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.
*/
#include "config.h"
#include "WebKitDLL.h"
#include "WebSerializedJSValue.h"
#include <WebCore/SerializedScriptValue.h>
using namespace WebCore;
WebSerializedJSValue::WebSerializedJSValue()
: m_refCount(0)
{
++gClassCount;
gClassNameCount.add("WebSerializedJSValue");
}
WebSerializedJSValue::~WebSerializedJSValue()
{
--gClassCount;
gClassNameCount.remove("WebSerializedJSValue");
}
COMPtr<WebSerializedJSValue> WebSerializedJSValue::createInstance()
{
return new WebSerializedJSValue();
}
ULONG WebSerializedJSValue::AddRef()
{
return ++m_refCount;
}
ULONG WebSerializedJSValue::Release()
{
ULONG newRefCount = --m_refCount;
if (!newRefCount)
delete this;
return newRefCount;
}
HRESULT WebSerializedJSValue::QueryInterface(REFIID riid, void** ppvObject)
{
if (!ppvObject)
return E_POINTER;
*ppvObject = 0;
if (IsEqualIID(riid, __uuidof(WebSerializedJSValue)))
*ppvObject = this;
else if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebSerializedJSValue*>(this);
else if (IsEqualIID(riid, __uuidof(IWebSerializedJSValue)))
*ppvObject = static_cast<IWebSerializedJSValue*>(this);
else if (IsEqualIID(riid, __uuidof(IWebSerializedJSValuePrivate)))
*ppvObject = static_cast<IWebSerializedJSValuePrivate*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
HRESULT WebSerializedJSValue::serialize(JSContextRef sourceContext, JSValueRef value, JSValueRef* exception)
{
ASSERT_ARG(value, value);
ASSERT_ARG(sourceContext, sourceContext);
if (!value || !sourceContext)
return E_POINTER;
m_value = SerializedScriptValue::create(sourceContext, value, exception);
return S_OK;
}
HRESULT WebSerializedJSValue::deserialize(JSContextRef destinationContext, JSValueRef* outValue)
{
if (!outValue)
return E_POINTER;
if (!m_value)
*outValue = 0;
else
*outValue = m_value->deserialize(destinationContext, 0);
return S_OK;
}
HRESULT WebSerializedJSValue::setInternalRepresentation(void* internalRepresentation)
{
if (!internalRepresentation || m_value)
return E_POINTER;
m_value = reinterpret_cast<SerializedScriptValue*>(internalRepresentation);
return S_OK;
}
HRESULT WebSerializedJSValue::getInternalRepresentation(void** internalRepresentation)
{
if (!m_value)
return E_POINTER;
*internalRepresentation = m_value.get();
return S_OK;
}
| bsd-2-clause |
BloodyKnight/nginx-openresty-windows | nginx/objs/lib/openssl-1.0.1p/crypto/asn1/x_sig.c | 189 | 3486 | /* crypto/asn1/x_sig.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 "cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
ASN1_SEQUENCE(X509_SIG) = {
ASN1_SIMPLE(X509_SIG, algor, X509_ALGOR),
ASN1_SIMPLE(X509_SIG, digest, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(X509_SIG)
IMPLEMENT_ASN1_FUNCTIONS(X509_SIG)
| bsd-2-clause |
mikedlowis-prototypes/albase | source/kernel/arch/x86/kernel/i8259.c | 447 | 11048 | #include <linux/linkage.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/timex.h>
#include <linux/random.h>
#include <linux/init.h>
#include <linux/kernel_stat.h>
#include <linux/syscore_ops.h>
#include <linux/bitops.h>
#include <linux/acpi.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <asm/timer.h>
#include <asm/hw_irq.h>
#include <asm/pgtable.h>
#include <asm/desc.h>
#include <asm/apic.h>
#include <asm/i8259.h>
/*
* This is the 'legacy' 8259A Programmable Interrupt Controller,
* present in the majority of PC/AT boxes.
* plus some generic x86 specific things if generic specifics makes
* any sense at all.
*/
static void init_8259A(int auto_eoi);
static int i8259A_auto_eoi;
DEFINE_RAW_SPINLOCK(i8259A_lock);
/*
* 8259A PIC functions to handle ISA devices:
*/
/*
* This contains the irq mask for both 8259A irq controllers,
*/
unsigned int cached_irq_mask = 0xffff;
/*
* Not all IRQs can be routed through the IO-APIC, eg. on certain (older)
* boards the timer interrupt is not really connected to any IO-APIC pin,
* it's fed to the master 8259A's IR0 line only.
*
* Any '1' bit in this mask means the IRQ is routed through the IO-APIC.
* this 'mixed mode' IRQ handling costs nothing because it's only used
* at IRQ setup time.
*/
unsigned long io_apic_irqs;
static void mask_8259A_irq(unsigned int irq)
{
unsigned int mask = 1 << irq;
unsigned long flags;
raw_spin_lock_irqsave(&i8259A_lock, flags);
cached_irq_mask |= mask;
if (irq & 8)
outb(cached_slave_mask, PIC_SLAVE_IMR);
else
outb(cached_master_mask, PIC_MASTER_IMR);
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
}
static void disable_8259A_irq(struct irq_data *data)
{
mask_8259A_irq(data->irq);
}
static void unmask_8259A_irq(unsigned int irq)
{
unsigned int mask = ~(1 << irq);
unsigned long flags;
raw_spin_lock_irqsave(&i8259A_lock, flags);
cached_irq_mask &= mask;
if (irq & 8)
outb(cached_slave_mask, PIC_SLAVE_IMR);
else
outb(cached_master_mask, PIC_MASTER_IMR);
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
}
static void enable_8259A_irq(struct irq_data *data)
{
unmask_8259A_irq(data->irq);
}
static int i8259A_irq_pending(unsigned int irq)
{
unsigned int mask = 1<<irq;
unsigned long flags;
int ret;
raw_spin_lock_irqsave(&i8259A_lock, flags);
if (irq < 8)
ret = inb(PIC_MASTER_CMD) & mask;
else
ret = inb(PIC_SLAVE_CMD) & (mask >> 8);
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
return ret;
}
static void make_8259A_irq(unsigned int irq)
{
disable_irq_nosync(irq);
io_apic_irqs &= ~(1<<irq);
irq_set_chip_and_handler(irq, &i8259A_chip, handle_level_irq);
enable_irq(irq);
}
/*
* This function assumes to be called rarely. Switching between
* 8259A registers is slow.
* This has to be protected by the irq controller spinlock
* before being called.
*/
static inline int i8259A_irq_real(unsigned int irq)
{
int value;
int irqmask = 1<<irq;
if (irq < 8) {
outb(0x0B, PIC_MASTER_CMD); /* ISR register */
value = inb(PIC_MASTER_CMD) & irqmask;
outb(0x0A, PIC_MASTER_CMD); /* back to the IRR register */
return value;
}
outb(0x0B, PIC_SLAVE_CMD); /* ISR register */
value = inb(PIC_SLAVE_CMD) & (irqmask >> 8);
outb(0x0A, PIC_SLAVE_CMD); /* back to the IRR register */
return value;
}
/*
* Careful! The 8259A is a fragile beast, it pretty
* much _has_ to be done exactly like this (mask it
* first, _then_ send the EOI, and the order of EOI
* to the two 8259s is important!
*/
static void mask_and_ack_8259A(struct irq_data *data)
{
unsigned int irq = data->irq;
unsigned int irqmask = 1 << irq;
unsigned long flags;
raw_spin_lock_irqsave(&i8259A_lock, flags);
/*
* Lightweight spurious IRQ detection. We do not want
* to overdo spurious IRQ handling - it's usually a sign
* of hardware problems, so we only do the checks we can
* do without slowing down good hardware unnecessarily.
*
* Note that IRQ7 and IRQ15 (the two spurious IRQs
* usually resulting from the 8259A-1|2 PICs) occur
* even if the IRQ is masked in the 8259A. Thus we
* can check spurious 8259A IRQs without doing the
* quite slow i8259A_irq_real() call for every IRQ.
* This does not cover 100% of spurious interrupts,
* but should be enough to warn the user that there
* is something bad going on ...
*/
if (cached_irq_mask & irqmask)
goto spurious_8259A_irq;
cached_irq_mask |= irqmask;
handle_real_irq:
if (irq & 8) {
inb(PIC_SLAVE_IMR); /* DUMMY - (do we need this?) */
outb(cached_slave_mask, PIC_SLAVE_IMR);
/* 'Specific EOI' to slave */
outb(0x60+(irq&7), PIC_SLAVE_CMD);
/* 'Specific EOI' to master-IRQ2 */
outb(0x60+PIC_CASCADE_IR, PIC_MASTER_CMD);
} else {
inb(PIC_MASTER_IMR); /* DUMMY - (do we need this?) */
outb(cached_master_mask, PIC_MASTER_IMR);
outb(0x60+irq, PIC_MASTER_CMD); /* 'Specific EOI to master */
}
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
return;
spurious_8259A_irq:
/*
* this is the slow path - should happen rarely.
*/
if (i8259A_irq_real(irq))
/*
* oops, the IRQ _is_ in service according to the
* 8259A - not spurious, go handle it.
*/
goto handle_real_irq;
{
static int spurious_irq_mask;
/*
* At this point we can be sure the IRQ is spurious,
* lets ACK and report it. [once per IRQ]
*/
if (!(spurious_irq_mask & irqmask)) {
printk(KERN_DEBUG
"spurious 8259A interrupt: IRQ%d.\n", irq);
spurious_irq_mask |= irqmask;
}
atomic_inc(&irq_err_count);
/*
* Theoretically we do not have to handle this IRQ,
* but in Linux this does not cause problems and is
* simpler for us.
*/
goto handle_real_irq;
}
}
struct irq_chip i8259A_chip = {
.name = "XT-PIC",
.irq_mask = disable_8259A_irq,
.irq_disable = disable_8259A_irq,
.irq_unmask = enable_8259A_irq,
.irq_mask_ack = mask_and_ack_8259A,
};
static char irq_trigger[2];
/**
* ELCR registers (0x4d0, 0x4d1) control edge/level of IRQ
*/
static void restore_ELCR(char *trigger)
{
outb(trigger[0], 0x4d0);
outb(trigger[1], 0x4d1);
}
static void save_ELCR(char *trigger)
{
/* IRQ 0,1,2,8,13 are marked as reserved */
trigger[0] = inb(0x4d0) & 0xF8;
trigger[1] = inb(0x4d1) & 0xDE;
}
static void i8259A_resume(void)
{
init_8259A(i8259A_auto_eoi);
restore_ELCR(irq_trigger);
}
static int i8259A_suspend(void)
{
save_ELCR(irq_trigger);
return 0;
}
static void i8259A_shutdown(void)
{
/* Put the i8259A into a quiescent state that
* the kernel initialization code can get it
* out of.
*/
outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */
outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */
}
static struct syscore_ops i8259_syscore_ops = {
.suspend = i8259A_suspend,
.resume = i8259A_resume,
.shutdown = i8259A_shutdown,
};
static void mask_8259A(void)
{
unsigned long flags;
raw_spin_lock_irqsave(&i8259A_lock, flags);
outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */
outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
}
static void unmask_8259A(void)
{
unsigned long flags;
raw_spin_lock_irqsave(&i8259A_lock, flags);
outb(cached_master_mask, PIC_MASTER_IMR); /* restore master IRQ mask */
outb(cached_slave_mask, PIC_SLAVE_IMR); /* restore slave IRQ mask */
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
}
static int probe_8259A(void)
{
unsigned long flags;
unsigned char probe_val = ~(1 << PIC_CASCADE_IR);
unsigned char new_val;
/*
* Check to see if we have a PIC.
* Mask all except the cascade and read
* back the value we just wrote. If we don't
* have a PIC, we will read 0xff as opposed to the
* value we wrote.
*/
raw_spin_lock_irqsave(&i8259A_lock, flags);
outb(0xff, PIC_SLAVE_IMR); /* mask all of 8259A-2 */
outb(probe_val, PIC_MASTER_IMR);
new_val = inb(PIC_MASTER_IMR);
if (new_val != probe_val) {
printk(KERN_INFO "Using NULL legacy PIC\n");
legacy_pic = &null_legacy_pic;
}
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
return nr_legacy_irqs();
}
static void init_8259A(int auto_eoi)
{
unsigned long flags;
i8259A_auto_eoi = auto_eoi;
raw_spin_lock_irqsave(&i8259A_lock, flags);
outb(0xff, PIC_MASTER_IMR); /* mask all of 8259A-1 */
/*
* outb_pic - this has to work on a wide range of PC hardware.
*/
outb_pic(0x11, PIC_MASTER_CMD); /* ICW1: select 8259A-1 init */
/* ICW2: 8259A-1 IR0-7 mapped to ISA_IRQ_VECTOR(0) */
outb_pic(ISA_IRQ_VECTOR(0), PIC_MASTER_IMR);
/* 8259A-1 (the master) has a slave on IR2 */
outb_pic(1U << PIC_CASCADE_IR, PIC_MASTER_IMR);
if (auto_eoi) /* master does Auto EOI */
outb_pic(MASTER_ICW4_DEFAULT | PIC_ICW4_AEOI, PIC_MASTER_IMR);
else /* master expects normal EOI */
outb_pic(MASTER_ICW4_DEFAULT, PIC_MASTER_IMR);
outb_pic(0x11, PIC_SLAVE_CMD); /* ICW1: select 8259A-2 init */
/* ICW2: 8259A-2 IR0-7 mapped to ISA_IRQ_VECTOR(8) */
outb_pic(ISA_IRQ_VECTOR(8), PIC_SLAVE_IMR);
/* 8259A-2 is a slave on master's IR2 */
outb_pic(PIC_CASCADE_IR, PIC_SLAVE_IMR);
/* (slave's support for AEOI in flat mode is to be investigated) */
outb_pic(SLAVE_ICW4_DEFAULT, PIC_SLAVE_IMR);
if (auto_eoi)
/*
* In AEOI mode we just have to mask the interrupt
* when acking.
*/
i8259A_chip.irq_mask_ack = disable_8259A_irq;
else
i8259A_chip.irq_mask_ack = mask_and_ack_8259A;
udelay(100); /* wait for 8259A to initialize */
outb(cached_master_mask, PIC_MASTER_IMR); /* restore master IRQ mask */
outb(cached_slave_mask, PIC_SLAVE_IMR); /* restore slave IRQ mask */
raw_spin_unlock_irqrestore(&i8259A_lock, flags);
}
/*
* make i8259 a driver so that we can select pic functions at run time. the goal
* is to make x86 binary compatible among pc compatible and non-pc compatible
* platforms, such as x86 MID.
*/
static void legacy_pic_noop(void) { };
static void legacy_pic_uint_noop(unsigned int unused) { };
static void legacy_pic_int_noop(int unused) { };
static int legacy_pic_irq_pending_noop(unsigned int irq)
{
return 0;
}
static int legacy_pic_probe(void)
{
return 0;
}
struct legacy_pic null_legacy_pic = {
.nr_legacy_irqs = 0,
.chip = &dummy_irq_chip,
.mask = legacy_pic_uint_noop,
.unmask = legacy_pic_uint_noop,
.mask_all = legacy_pic_noop,
.restore_mask = legacy_pic_noop,
.init = legacy_pic_int_noop,
.probe = legacy_pic_probe,
.irq_pending = legacy_pic_irq_pending_noop,
.make_irq = legacy_pic_uint_noop,
};
struct legacy_pic default_legacy_pic = {
.nr_legacy_irqs = NR_IRQS_LEGACY,
.chip = &i8259A_chip,
.mask = mask_8259A_irq,
.unmask = unmask_8259A_irq,
.mask_all = mask_8259A,
.restore_mask = unmask_8259A,
.init = init_8259A,
.probe = probe_8259A,
.irq_pending = i8259A_irq_pending,
.make_irq = make_8259A_irq,
};
struct legacy_pic *legacy_pic = &default_legacy_pic;
static int __init i8259A_init_ops(void)
{
if (legacy_pic == &default_legacy_pic)
register_syscore_ops(&i8259_syscore_ops);
return 0;
}
device_initcall(i8259A_init_ops);
| bsd-2-clause |
endplay/omniplay | linux-lts-quantal-3.5.0/drivers/net/wireless/rtlwifi/rtl8192se/hw.c | 4071 | 71041 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../efuse.h"
#include "../base.h"
#include "../regd.h"
#include "../cam.h"
#include "../ps.h"
#include "../pci.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "dm.h"
#include "fw.h"
#include "led.h"
#include "hw.h"
void rtl92se_get_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
switch (variable) {
case HW_VAR_RCR: {
*((u32 *) (val)) = rtlpci->receive_config;
break;
}
case HW_VAR_RF_STATE: {
*((enum rf_pwrstate *)(val)) = ppsc->rfpwr_state;
break;
}
case HW_VAR_FW_PSMODE_STATUS: {
*((bool *) (val)) = ppsc->fw_current_inpsmode;
break;
}
case HW_VAR_CORRECT_TSF: {
u64 tsf;
u32 *ptsf_low = (u32 *)&tsf;
u32 *ptsf_high = ((u32 *)&tsf) + 1;
*ptsf_high = rtl_read_dword(rtlpriv, (TSFR + 4));
*ptsf_low = rtl_read_dword(rtlpriv, TSFR);
*((u64 *) (val)) = tsf;
break;
}
case HW_VAR_MRC: {
*((bool *)(val)) = rtlpriv->dm.current_mrc_switch;
break;
}
default: {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
}
}
void rtl92se_set_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
switch (variable) {
case HW_VAR_ETHER_ADDR:{
rtl_write_dword(rtlpriv, IDR0, ((u32 *)(val))[0]);
rtl_write_word(rtlpriv, IDR4, ((u16 *)(val + 4))[0]);
break;
}
case HW_VAR_BASIC_RATE:{
u16 rate_cfg = ((u16 *) val)[0];
u8 rate_index = 0;
if (rtlhal->version == VERSION_8192S_ACUT)
rate_cfg = rate_cfg & 0x150;
else
rate_cfg = rate_cfg & 0x15f;
rate_cfg |= 0x01;
rtl_write_byte(rtlpriv, RRSR, rate_cfg & 0xff);
rtl_write_byte(rtlpriv, RRSR + 1,
(rate_cfg >> 8) & 0xff);
while (rate_cfg > 0x1) {
rate_cfg = (rate_cfg >> 1);
rate_index++;
}
rtl_write_byte(rtlpriv, INIRTSMCS_SEL, rate_index);
break;
}
case HW_VAR_BSSID:{
rtl_write_dword(rtlpriv, BSSIDR, ((u32 *)(val))[0]);
rtl_write_word(rtlpriv, BSSIDR + 4,
((u16 *)(val + 4))[0]);
break;
}
case HW_VAR_SIFS:{
rtl_write_byte(rtlpriv, SIFS_OFDM, val[0]);
rtl_write_byte(rtlpriv, SIFS_OFDM + 1, val[1]);
break;
}
case HW_VAR_SLOT_TIME:{
u8 e_aci;
RT_TRACE(rtlpriv, COMP_MLME, DBG_LOUD,
"HW_VAR_SLOT_TIME %x\n", val[0]);
rtl_write_byte(rtlpriv, SLOT_TIME, val[0]);
for (e_aci = 0; e_aci < AC_MAX; e_aci++) {
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_AC_PARAM,
(u8 *)(&e_aci));
}
break;
}
case HW_VAR_ACK_PREAMBLE:{
u8 reg_tmp;
u8 short_preamble = (bool) (*(u8 *) val);
reg_tmp = (mac->cur_40_prime_sc) << 5;
if (short_preamble)
reg_tmp |= 0x80;
rtl_write_byte(rtlpriv, RRSR + 2, reg_tmp);
break;
}
case HW_VAR_AMPDU_MIN_SPACE:{
u8 min_spacing_to_set;
u8 sec_min_space;
min_spacing_to_set = *((u8 *)val);
if (min_spacing_to_set <= 7) {
if (rtlpriv->sec.pairwise_enc_algorithm ==
NO_ENCRYPTION)
sec_min_space = 0;
else
sec_min_space = 1;
if (min_spacing_to_set < sec_min_space)
min_spacing_to_set = sec_min_space;
if (min_spacing_to_set > 5)
min_spacing_to_set = 5;
mac->min_space_cfg =
((mac->min_space_cfg & 0xf8) |
min_spacing_to_set);
*val = min_spacing_to_set;
RT_TRACE(rtlpriv, COMP_MLME, DBG_LOUD,
"Set HW_VAR_AMPDU_MIN_SPACE: %#x\n",
mac->min_space_cfg);
rtl_write_byte(rtlpriv, AMPDU_MIN_SPACE,
mac->min_space_cfg);
}
break;
}
case HW_VAR_SHORTGI_DENSITY:{
u8 density_to_set;
density_to_set = *((u8 *) val);
mac->min_space_cfg = rtlpriv->rtlhal.minspace_cfg;
mac->min_space_cfg |= (density_to_set << 3);
RT_TRACE(rtlpriv, COMP_MLME, DBG_LOUD,
"Set HW_VAR_SHORTGI_DENSITY: %#x\n",
mac->min_space_cfg);
rtl_write_byte(rtlpriv, AMPDU_MIN_SPACE,
mac->min_space_cfg);
break;
}
case HW_VAR_AMPDU_FACTOR:{
u8 factor_toset;
u8 regtoset;
u8 factorlevel[18] = {
2, 4, 4, 7, 7, 13, 13,
13, 2, 7, 7, 13, 13,
15, 15, 15, 15, 0};
u8 index = 0;
factor_toset = *((u8 *) val);
if (factor_toset <= 3) {
factor_toset = (1 << (factor_toset + 2));
if (factor_toset > 0xf)
factor_toset = 0xf;
for (index = 0; index < 17; index++) {
if (factorlevel[index] > factor_toset)
factorlevel[index] =
factor_toset;
}
for (index = 0; index < 8; index++) {
regtoset = ((factorlevel[index * 2]) |
(factorlevel[index *
2 + 1] << 4));
rtl_write_byte(rtlpriv,
AGGLEN_LMT_L + index,
regtoset);
}
regtoset = ((factorlevel[16]) |
(factorlevel[17] << 4));
rtl_write_byte(rtlpriv, AGGLEN_LMT_H, regtoset);
RT_TRACE(rtlpriv, COMP_MLME, DBG_LOUD,
"Set HW_VAR_AMPDU_FACTOR: %#x\n",
factor_toset);
}
break;
}
case HW_VAR_AC_PARAM:{
u8 e_aci = *((u8 *) val);
rtl92s_dm_init_edca_turbo(hw);
if (rtlpci->acm_method != eAcmWay2_SW)
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_ACM_CTRL,
(u8 *)(&e_aci));
break;
}
case HW_VAR_ACM_CTRL:{
u8 e_aci = *((u8 *) val);
union aci_aifsn *p_aci_aifsn = (union aci_aifsn *)(&(
mac->ac[0].aifs));
u8 acm = p_aci_aifsn->f.acm;
u8 acm_ctrl = rtl_read_byte(rtlpriv, AcmHwCtrl);
acm_ctrl = acm_ctrl | ((rtlpci->acm_method == 2) ?
0x0 : 0x1);
if (acm) {
switch (e_aci) {
case AC0_BE:
acm_ctrl |= AcmHw_BeqEn;
break;
case AC2_VI:
acm_ctrl |= AcmHw_ViqEn;
break;
case AC3_VO:
acm_ctrl |= AcmHw_VoqEn;
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"HW_VAR_ACM_CTRL acm set failed: eACI is %d\n",
acm);
break;
}
} else {
switch (e_aci) {
case AC0_BE:
acm_ctrl &= (~AcmHw_BeqEn);
break;
case AC2_VI:
acm_ctrl &= (~AcmHw_ViqEn);
break;
case AC3_VO:
acm_ctrl &= (~AcmHw_BeqEn);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
}
RT_TRACE(rtlpriv, COMP_QOS, DBG_TRACE,
"HW_VAR_ACM_CTRL Write 0x%X\n", acm_ctrl);
rtl_write_byte(rtlpriv, AcmHwCtrl, acm_ctrl);
break;
}
case HW_VAR_RCR:{
rtl_write_dword(rtlpriv, RCR, ((u32 *) (val))[0]);
rtlpci->receive_config = ((u32 *) (val))[0];
break;
}
case HW_VAR_RETRY_LIMIT:{
u8 retry_limit = ((u8 *) (val))[0];
rtl_write_word(rtlpriv, RETRY_LIMIT,
retry_limit << RETRY_LIMIT_SHORT_SHIFT |
retry_limit << RETRY_LIMIT_LONG_SHIFT);
break;
}
case HW_VAR_DUAL_TSF_RST: {
break;
}
case HW_VAR_EFUSE_BYTES: {
rtlefuse->efuse_usedbytes = *((u16 *) val);
break;
}
case HW_VAR_EFUSE_USAGE: {
rtlefuse->efuse_usedpercentage = *((u8 *) val);
break;
}
case HW_VAR_IO_CMD: {
break;
}
case HW_VAR_WPA_CONFIG: {
rtl_write_byte(rtlpriv, REG_SECR, *((u8 *) val));
break;
}
case HW_VAR_SET_RPWM:{
break;
}
case HW_VAR_H2C_FW_PWRMODE:{
break;
}
case HW_VAR_FW_PSMODE_STATUS: {
ppsc->fw_current_inpsmode = *((bool *) val);
break;
}
case HW_VAR_H2C_FW_JOINBSSRPT:{
break;
}
case HW_VAR_AID:{
break;
}
case HW_VAR_CORRECT_TSF:{
break;
}
case HW_VAR_MRC: {
bool bmrc_toset = *((bool *)val);
u8 u1bdata = 0;
if (bmrc_toset) {
rtl_set_bbreg(hw, ROFDM0_TRXPATHENABLE,
MASKBYTE0, 0x33);
u1bdata = (u8)rtl_get_bbreg(hw,
ROFDM1_TRXPATHENABLE,
MASKBYTE0);
rtl_set_bbreg(hw, ROFDM1_TRXPATHENABLE,
MASKBYTE0,
((u1bdata & 0xf0) | 0x03));
u1bdata = (u8)rtl_get_bbreg(hw,
ROFDM0_TRXPATHENABLE,
MASKBYTE1);
rtl_set_bbreg(hw, ROFDM0_TRXPATHENABLE,
MASKBYTE1,
(u1bdata | 0x04));
/* Update current settings. */
rtlpriv->dm.current_mrc_switch = bmrc_toset;
} else {
rtl_set_bbreg(hw, ROFDM0_TRXPATHENABLE,
MASKBYTE0, 0x13);
u1bdata = (u8)rtl_get_bbreg(hw,
ROFDM1_TRXPATHENABLE,
MASKBYTE0);
rtl_set_bbreg(hw, ROFDM1_TRXPATHENABLE,
MASKBYTE0,
((u1bdata & 0xf0) | 0x01));
u1bdata = (u8)rtl_get_bbreg(hw,
ROFDM0_TRXPATHENABLE,
MASKBYTE1);
rtl_set_bbreg(hw, ROFDM0_TRXPATHENABLE,
MASKBYTE1, (u1bdata & 0xfb));
/* Update current settings. */
rtlpriv->dm.current_mrc_switch = bmrc_toset;
}
break;
}
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
}
void rtl92se_enable_hw_security_config(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 sec_reg_value = 0x0;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"PairwiseEncAlgorithm = %d GroupEncAlgorithm = %d\n",
rtlpriv->sec.pairwise_enc_algorithm,
rtlpriv->sec.group_enc_algorithm);
if (rtlpriv->cfg->mod_params->sw_crypto || rtlpriv->sec.use_sw_sec) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"not open hw encryption\n");
return;
}
sec_reg_value = SCR_TXENCENABLE | SCR_RXENCENABLE;
if (rtlpriv->sec.use_defaultkey) {
sec_reg_value |= SCR_TXUSEDK;
sec_reg_value |= SCR_RXUSEDK;
}
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "The SECR-value %x\n",
sec_reg_value);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_WPA_CONFIG, &sec_reg_value);
}
static u8 _rtl92ce_halset_sysclk(struct ieee80211_hw *hw, u8 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 waitcount = 100;
bool bresult = false;
u8 tmpvalue;
rtl_write_byte(rtlpriv, SYS_CLKR + 1, data);
/* Wait the MAC synchronized. */
udelay(400);
/* Check if it is set ready. */
tmpvalue = rtl_read_byte(rtlpriv, SYS_CLKR + 1);
bresult = ((tmpvalue & BIT(7)) == (data & BIT(7)));
if ((data & (BIT(6) | BIT(7))) == false) {
waitcount = 100;
tmpvalue = 0;
while (1) {
waitcount--;
tmpvalue = rtl_read_byte(rtlpriv, SYS_CLKR + 1);
if ((tmpvalue & BIT(6)))
break;
pr_err("wait for BIT(6) return value %x\n", tmpvalue);
if (waitcount == 0)
break;
udelay(10);
}
if (waitcount == 0)
bresult = false;
else
bresult = true;
}
return bresult;
}
void rtl8192se_gpiobit3_cfg_inputmode(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 u1tmp;
/* The following config GPIO function */
rtl_write_byte(rtlpriv, MAC_PINMUX_CFG, (GPIOMUX_EN | GPIOSEL_GPIO));
u1tmp = rtl_read_byte(rtlpriv, GPIO_IO_SEL);
/* config GPIO3 to input */
u1tmp &= HAL_8192S_HW_GPIO_OFF_MASK;
rtl_write_byte(rtlpriv, GPIO_IO_SEL, u1tmp);
}
static u8 _rtl92se_rf_onoff_detect(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 u1tmp;
u8 retval = ERFON;
/* The following config GPIO function */
rtl_write_byte(rtlpriv, MAC_PINMUX_CFG, (GPIOMUX_EN | GPIOSEL_GPIO));
u1tmp = rtl_read_byte(rtlpriv, GPIO_IO_SEL);
/* config GPIO3 to input */
u1tmp &= HAL_8192S_HW_GPIO_OFF_MASK;
rtl_write_byte(rtlpriv, GPIO_IO_SEL, u1tmp);
/* On some of the platform, driver cannot read correct
* value without delay between Write_GPIO_SEL and Read_GPIO_IN */
mdelay(10);
/* check GPIO3 */
u1tmp = rtl_read_byte(rtlpriv, GPIO_IN_SE);
retval = (u1tmp & HAL_8192S_HW_GPIO_OFF_BIT) ? ERFON : ERFOFF;
return retval;
}
static void _rtl92se_macconfig_before_fwdownload(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u8 i;
u8 tmpu1b;
u16 tmpu2b;
u8 pollingcnt = 20;
if (rtlpci->first_init) {
/* Reset PCIE Digital */
tmpu1b = rtl_read_byte(rtlpriv, REG_SYS_FUNC_EN + 1);
tmpu1b &= 0xFE;
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, tmpu1b);
udelay(1);
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, tmpu1b | BIT(0));
}
/* Switch to SW IO control */
tmpu1b = rtl_read_byte(rtlpriv, (SYS_CLKR + 1));
if (tmpu1b & BIT(7)) {
tmpu1b &= ~(BIT(6) | BIT(7));
/* Set failed, return to prevent hang. */
if (!_rtl92ce_halset_sysclk(hw, tmpu1b))
return;
}
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, 0x0);
udelay(50);
rtl_write_byte(rtlpriv, LDOA15_CTRL, 0x34);
udelay(50);
/* Clear FW RPWM for FW control LPS.*/
rtl_write_byte(rtlpriv, RPWM, 0x0);
/* Reset MAC-IO and CPU and Core Digital BIT(10)/11/15 */
tmpu1b = rtl_read_byte(rtlpriv, REG_SYS_FUNC_EN + 1);
tmpu1b &= 0x73;
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, tmpu1b);
/* wait for BIT 10/11/15 to pull high automatically!! */
mdelay(1);
rtl_write_byte(rtlpriv, CMDR, 0);
rtl_write_byte(rtlpriv, TCR, 0);
/* Data sheet not define 0x562!!! Copy from WMAC!!!!! */
tmpu1b = rtl_read_byte(rtlpriv, 0x562);
tmpu1b |= 0x08;
rtl_write_byte(rtlpriv, 0x562, tmpu1b);
tmpu1b &= ~(BIT(3));
rtl_write_byte(rtlpriv, 0x562, tmpu1b);
/* Enable AFE clock source */
tmpu1b = rtl_read_byte(rtlpriv, AFE_XTAL_CTRL);
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL, (tmpu1b | 0x01));
/* Delay 1.5ms */
mdelay(2);
tmpu1b = rtl_read_byte(rtlpriv, AFE_XTAL_CTRL + 1);
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL + 1, (tmpu1b & 0xfb));
/* Enable AFE Macro Block's Bandgap */
tmpu1b = rtl_read_byte(rtlpriv, AFE_MISC);
rtl_write_byte(rtlpriv, AFE_MISC, (tmpu1b | BIT(0)));
mdelay(1);
/* Enable AFE Mbias */
tmpu1b = rtl_read_byte(rtlpriv, AFE_MISC);
rtl_write_byte(rtlpriv, AFE_MISC, (tmpu1b | 0x02));
mdelay(1);
/* Enable LDOA15 block */
tmpu1b = rtl_read_byte(rtlpriv, LDOA15_CTRL);
rtl_write_byte(rtlpriv, LDOA15_CTRL, (tmpu1b | BIT(0)));
/* Set Digital Vdd to Retention isolation Path. */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_ISO_CTRL);
rtl_write_word(rtlpriv, REG_SYS_ISO_CTRL, (tmpu2b | BIT(11)));
/* For warm reboot NIC disappera bug. */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(13)));
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL + 1, 0x68);
/* Enable AFE PLL Macro Block */
/* We need to delay 100u before enabling PLL. */
udelay(200);
tmpu1b = rtl_read_byte(rtlpriv, AFE_PLL_CTRL);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, (tmpu1b | BIT(0) | BIT(4)));
/* for divider reset */
udelay(100);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, (tmpu1b | BIT(0) |
BIT(4) | BIT(6)));
udelay(10);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, (tmpu1b | BIT(0) | BIT(4)));
udelay(10);
/* Enable MAC 80MHZ clock */
tmpu1b = rtl_read_byte(rtlpriv, AFE_PLL_CTRL + 1);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL + 1, (tmpu1b | BIT(0)));
mdelay(1);
/* Release isolation AFE PLL & MD */
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL, 0xA6);
/* Enable MAC clock */
tmpu2b = rtl_read_word(rtlpriv, SYS_CLKR);
rtl_write_word(rtlpriv, SYS_CLKR, (tmpu2b | BIT(12) | BIT(11)));
/* Enable Core digital and enable IOREG R/W */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(11)));
tmpu1b = rtl_read_byte(rtlpriv, REG_SYS_FUNC_EN + 1);
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, tmpu1b & ~(BIT(7)));
/* enable REG_EN */
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(11) | BIT(15)));
/* Switch the control path. */
tmpu2b = rtl_read_word(rtlpriv, SYS_CLKR);
rtl_write_word(rtlpriv, SYS_CLKR, (tmpu2b & (~BIT(2))));
tmpu1b = rtl_read_byte(rtlpriv, (SYS_CLKR + 1));
tmpu1b = ((tmpu1b | BIT(7)) & (~BIT(6)));
if (!_rtl92ce_halset_sysclk(hw, tmpu1b))
return; /* Set failed, return to prevent hang. */
rtl_write_word(rtlpriv, CMDR, 0x07FC);
/* MH We must enable the section of code to prevent load IMEM fail. */
/* Load MAC register from WMAc temporarily We simulate macreg. */
/* txt HW will provide MAC txt later */
rtl_write_byte(rtlpriv, 0x6, 0x30);
rtl_write_byte(rtlpriv, 0x49, 0xf0);
rtl_write_byte(rtlpriv, 0x4b, 0x81);
rtl_write_byte(rtlpriv, 0xb5, 0x21);
rtl_write_byte(rtlpriv, 0xdc, 0xff);
rtl_write_byte(rtlpriv, 0xdd, 0xff);
rtl_write_byte(rtlpriv, 0xde, 0xff);
rtl_write_byte(rtlpriv, 0xdf, 0xff);
rtl_write_byte(rtlpriv, 0x11a, 0x00);
rtl_write_byte(rtlpriv, 0x11b, 0x00);
for (i = 0; i < 32; i++)
rtl_write_byte(rtlpriv, INIMCS_SEL + i, 0x1b);
rtl_write_byte(rtlpriv, 0x236, 0xff);
rtl_write_byte(rtlpriv, 0x503, 0x22);
if (ppsc->support_aspm && !ppsc->support_backdoor)
rtl_write_byte(rtlpriv, 0x560, 0x40);
else
rtl_write_byte(rtlpriv, 0x560, 0x00);
rtl_write_byte(rtlpriv, DBG_PORT, 0x91);
/* Set RX Desc Address */
rtl_write_dword(rtlpriv, RDQDA, rtlpci->rx_ring[RX_MPDU_QUEUE].dma);
rtl_write_dword(rtlpriv, RCDA, rtlpci->rx_ring[RX_CMD_QUEUE].dma);
/* Set TX Desc Address */
rtl_write_dword(rtlpriv, TBKDA, rtlpci->tx_ring[BK_QUEUE].dma);
rtl_write_dword(rtlpriv, TBEDA, rtlpci->tx_ring[BE_QUEUE].dma);
rtl_write_dword(rtlpriv, TVIDA, rtlpci->tx_ring[VI_QUEUE].dma);
rtl_write_dword(rtlpriv, TVODA, rtlpci->tx_ring[VO_QUEUE].dma);
rtl_write_dword(rtlpriv, TBDA, rtlpci->tx_ring[BEACON_QUEUE].dma);
rtl_write_dword(rtlpriv, TCDA, rtlpci->tx_ring[TXCMD_QUEUE].dma);
rtl_write_dword(rtlpriv, TMDA, rtlpci->tx_ring[MGNT_QUEUE].dma);
rtl_write_dword(rtlpriv, THPDA, rtlpci->tx_ring[HIGH_QUEUE].dma);
rtl_write_dword(rtlpriv, HDA, rtlpci->tx_ring[HCCA_QUEUE].dma);
rtl_write_word(rtlpriv, CMDR, 0x37FC);
/* To make sure that TxDMA can ready to download FW. */
/* We should reset TxDMA if IMEM RPT was not ready. */
do {
tmpu1b = rtl_read_byte(rtlpriv, TCR);
if ((tmpu1b & TXDMA_INIT_VALUE) == TXDMA_INIT_VALUE)
break;
udelay(5);
} while (pollingcnt--);
if (pollingcnt <= 0) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Polling TXDMA_INIT_VALUE timeout!! Current TCR(%#x)\n",
tmpu1b);
tmpu1b = rtl_read_byte(rtlpriv, CMDR);
rtl_write_byte(rtlpriv, CMDR, tmpu1b & (~TXDMA_EN));
udelay(2);
/* Reset TxDMA */
rtl_write_byte(rtlpriv, CMDR, tmpu1b | TXDMA_EN);
}
/* After MACIO reset,we must refresh LED state. */
if ((ppsc->rfoff_reason == RF_CHANGE_BY_IPS) ||
(ppsc->rfoff_reason == 0)) {
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_led *pLed0 = &(pcipriv->ledctl.sw_led0);
enum rf_pwrstate rfpwr_state_toset;
rfpwr_state_toset = _rtl92se_rf_onoff_detect(hw);
if (rfpwr_state_toset == ERFON)
rtl92se_sw_led_on(hw, pLed0);
}
}
static void _rtl92se_macconfig_after_fwdownload(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 i;
u16 tmpu2b;
/* 1. System Configure Register (Offset: 0x0000 - 0x003F) */
/* 2. Command Control Register (Offset: 0x0040 - 0x004F) */
/* Turn on 0x40 Command register */
rtl_write_word(rtlpriv, CMDR, (BBRSTN | BB_GLB_RSTN |
SCHEDULE_EN | MACRXEN | MACTXEN | DDMA_EN | FW2HW_EN |
RXDMA_EN | TXDMA_EN | HCI_RXDMA_EN | HCI_TXDMA_EN));
/* Set TCR TX DMA pre 2 FULL enable bit */
rtl_write_dword(rtlpriv, TCR, rtl_read_dword(rtlpriv, TCR) |
TXDMAPRE2FULL);
/* Set RCR */
rtl_write_dword(rtlpriv, RCR, rtlpci->receive_config);
/* 3. MACID Setting Register (Offset: 0x0050 - 0x007F) */
/* 4. Timing Control Register (Offset: 0x0080 - 0x009F) */
/* Set CCK/OFDM SIFS */
/* CCK SIFS shall always be 10us. */
rtl_write_word(rtlpriv, SIFS_CCK, 0x0a0a);
rtl_write_word(rtlpriv, SIFS_OFDM, 0x1010);
/* Set AckTimeout */
rtl_write_byte(rtlpriv, ACK_TIMEOUT, 0x40);
/* Beacon related */
rtl_write_word(rtlpriv, BCN_INTERVAL, 100);
rtl_write_word(rtlpriv, ATIMWND, 2);
/* 5. FIFO Control Register (Offset: 0x00A0 - 0x015F) */
/* 5.1 Initialize Number of Reserved Pages in Firmware Queue */
/* Firmware allocate now, associate with FW internal setting.!!! */
/* 5.2 Setting TX/RX page size 0/1/2/3/4=64/128/256/512/1024 */
/* 5.3 Set driver info, we only accept PHY status now. */
/* 5.4 Set RXDMA arbitration to control RXDMA/MAC/FW R/W for RXFIFO */
rtl_write_byte(rtlpriv, RXDMA, rtl_read_byte(rtlpriv, RXDMA) | BIT(6));
/* 6. Adaptive Control Register (Offset: 0x0160 - 0x01CF) */
/* Set RRSR to all legacy rate and HT rate
* CCK rate is supported by default.
* CCK rate will be filtered out only when associated
* AP does not support it.
* Only enable ACK rate to OFDM 24M
* Disable RRSR for CCK rate in A-Cut */
if (rtlhal->version == VERSION_8192S_ACUT)
rtl_write_byte(rtlpriv, RRSR, 0xf0);
else if (rtlhal->version == VERSION_8192S_BCUT)
rtl_write_byte(rtlpriv, RRSR, 0xff);
rtl_write_byte(rtlpriv, RRSR + 1, 0x01);
rtl_write_byte(rtlpriv, RRSR + 2, 0x00);
/* A-Cut IC do not support CCK rate. We forbid ARFR to */
/* fallback to CCK rate */
for (i = 0; i < 8; i++) {
/*Disable RRSR for CCK rate in A-Cut */
if (rtlhal->version == VERSION_8192S_ACUT)
rtl_write_dword(rtlpriv, ARFR0 + i * 4, 0x1f0ff0f0);
}
/* Different rate use different AMPDU size */
/* MCS32/ MCS15_SG use max AMPDU size 15*2=30K */
rtl_write_byte(rtlpriv, AGGLEN_LMT_H, 0x0f);
/* MCS0/1/2/3 use max AMPDU size 4*2=8K */
rtl_write_word(rtlpriv, AGGLEN_LMT_L, 0x7442);
/* MCS4/5 use max AMPDU size 8*2=16K 6/7 use 10*2=20K */
rtl_write_word(rtlpriv, AGGLEN_LMT_L + 2, 0xddd7);
/* MCS8/9 use max AMPDU size 8*2=16K 10/11 use 10*2=20K */
rtl_write_word(rtlpriv, AGGLEN_LMT_L + 4, 0xd772);
/* MCS12/13/14/15 use max AMPDU size 15*2=30K */
rtl_write_word(rtlpriv, AGGLEN_LMT_L + 6, 0xfffd);
/* Set Data / Response auto rate fallack retry count */
rtl_write_dword(rtlpriv, DARFRC, 0x04010000);
rtl_write_dword(rtlpriv, DARFRC + 4, 0x09070605);
rtl_write_dword(rtlpriv, RARFRC, 0x04010000);
rtl_write_dword(rtlpriv, RARFRC + 4, 0x09070605);
/* 7. EDCA Setting Register (Offset: 0x01D0 - 0x01FF) */
/* Set all rate to support SG */
rtl_write_word(rtlpriv, SG_RATE, 0xFFFF);
/* 8. WMAC, BA, and CCX related Register (Offset: 0x0200 - 0x023F) */
/* Set NAV protection length */
rtl_write_word(rtlpriv, NAV_PROT_LEN, 0x0080);
/* CF-END Threshold */
rtl_write_byte(rtlpriv, CFEND_TH, 0xFF);
/* Set AMPDU minimum space */
rtl_write_byte(rtlpriv, AMPDU_MIN_SPACE, 0x07);
/* Set TXOP stall control for several queue/HI/BCN/MGT/ */
rtl_write_byte(rtlpriv, TXOP_STALL_CTRL, 0x00);
/* 9. Security Control Register (Offset: 0x0240 - 0x025F) */
/* 10. Power Save Control Register (Offset: 0x0260 - 0x02DF) */
/* 11. General Purpose Register (Offset: 0x02E0 - 0x02FF) */
/* 12. Host Interrupt Status Register (Offset: 0x0300 - 0x030F) */
/* 13. Test Mode and Debug Control Register (Offset: 0x0310 - 0x034F) */
/* 14. Set driver info, we only accept PHY status now. */
rtl_write_byte(rtlpriv, RXDRVINFO_SZ, 4);
/* 15. For EEPROM R/W Workaround */
/* 16. For EFUSE to share REG_SYS_FUNC_EN with EEPROM!!! */
tmpu2b = rtl_read_byte(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, tmpu2b | BIT(13));
tmpu2b = rtl_read_byte(rtlpriv, REG_SYS_ISO_CTRL);
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL, tmpu2b & (~BIT(8)));
/* 17. For EFUSE */
/* We may R/W EFUSE in EEPROM mode */
if (rtlefuse->epromtype == EEPROM_BOOT_EFUSE) {
u8 tempval;
tempval = rtl_read_byte(rtlpriv, REG_SYS_ISO_CTRL + 1);
tempval &= 0xFE;
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL + 1, tempval);
/* Change Program timing */
rtl_write_byte(rtlpriv, REG_EFUSE_CTRL + 3, 0x72);
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "EFUSE CONFIG OK\n");
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "OK\n");
}
static void _rtl92se_hw_configure(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u8 reg_bw_opmode = 0;
u32 reg_rrsr = 0;
u8 regtmp = 0;
reg_bw_opmode = BW_OPMODE_20MHZ;
reg_rrsr = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
regtmp = rtl_read_byte(rtlpriv, INIRTSMCS_SEL);
reg_rrsr = ((reg_rrsr & 0x000fffff) << 8) | regtmp;
rtl_write_dword(rtlpriv, INIRTSMCS_SEL, reg_rrsr);
rtl_write_byte(rtlpriv, BW_OPMODE, reg_bw_opmode);
/* Set Retry Limit here */
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_RETRY_LIMIT,
(u8 *)(&rtlpci->shortretry_limit));
rtl_write_byte(rtlpriv, MLT, 0x8f);
/* For Min Spacing configuration. */
switch (rtlphy->rf_type) {
case RF_1T2R:
case RF_1T1R:
rtlhal->minspace_cfg = (MAX_MSS_DENSITY_1T << 3);
break;
case RF_2T2R:
case RF_2T2R_GREEN:
rtlhal->minspace_cfg = (MAX_MSS_DENSITY_2T << 3);
break;
}
rtl_write_byte(rtlpriv, AMPDU_MIN_SPACE, rtlhal->minspace_cfg);
}
int rtl92se_hw_init(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 tmp_byte = 0;
bool rtstatus = true;
u8 tmp_u1b;
int err = false;
u8 i;
int wdcapra_add[] = {
EDCAPARA_BE, EDCAPARA_BK,
EDCAPARA_VI, EDCAPARA_VO};
u8 secr_value = 0x0;
rtlpci->being_init_adapter = true;
rtlpriv->intf_ops->disable_aspm(hw);
/* 1. MAC Initialize */
/* Before FW download, we have to set some MAC register */
_rtl92se_macconfig_before_fwdownload(hw);
rtlhal->version = (enum version_8192s)((rtl_read_dword(rtlpriv,
PMC_FSM) >> 16) & 0xF);
rtl8192se_gpiobit3_cfg_inputmode(hw);
/* 2. download firmware */
rtstatus = rtl92s_download_fw(hw);
if (!rtstatus) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"Failed to download FW. Init HW without FW now... "
"Please copy FW into /lib/firmware/rtlwifi\n");
return 1;
}
/* After FW download, we have to reset MAC register */
_rtl92se_macconfig_after_fwdownload(hw);
/*Retrieve default FW Cmd IO map. */
rtlhal->fwcmd_iomap = rtl_read_word(rtlpriv, LBUS_MON_ADDR);
rtlhal->fwcmd_ioparam = rtl_read_dword(rtlpriv, LBUS_ADDR_MASK);
/* 3. Initialize MAC/PHY Config by MACPHY_reg.txt */
if (!rtl92s_phy_mac_config(hw)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "MAC Config failed\n");
return rtstatus;
}
/* Make sure BB/RF write OK. We should prevent enter IPS. radio off. */
/* We must set flag avoid BB/RF config period later!! */
rtl_write_dword(rtlpriv, CMDR, 0x37FC);
/* 4. Initialize BB After MAC Config PHY_reg.txt, AGC_Tab.txt */
if (!rtl92s_phy_bb_config(hw)) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_EMERG, "BB Config failed\n");
return rtstatus;
}
/* 5. Initiailze RF RAIO_A.txt RF RAIO_B.txt */
/* Before initalizing RF. We can not use FW to do RF-R/W. */
rtlphy->rf_mode = RF_OP_BY_SW_3WIRE;
/* RF Power Save */
#if 0
/* H/W or S/W RF OFF before sleep. */
if (rtlpriv->psc.rfoff_reason > RF_CHANGE_BY_PS) {
u32 rfoffreason = rtlpriv->psc.rfoff_reason;
rtlpriv->psc.rfoff_reason = RF_CHANGE_BY_INIT;
rtlpriv->psc.rfpwr_state = ERFON;
/* FIXME: check spinlocks if this block is uncommented */
rtl_ps_set_rf_state(hw, ERFOFF, rfoffreason);
} else {
/* gpio radio on/off is out of adapter start */
if (rtlpriv->psc.hwradiooff == false) {
rtlpriv->psc.rfpwr_state = ERFON;
rtlpriv->psc.rfoff_reason = 0;
}
}
#endif
/* Before RF-R/W we must execute the IO from Scott's suggestion. */
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL + 1, 0xDB);
if (rtlhal->version == VERSION_8192S_ACUT)
rtl_write_byte(rtlpriv, SPS1_CTRL + 3, 0x07);
else
rtl_write_byte(rtlpriv, RF_CTRL, 0x07);
if (!rtl92s_phy_rf_config(hw)) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "RF Config failed\n");
return rtstatus;
}
/* After read predefined TXT, we must set BB/MAC/RF
* register as our requirement */
rtlphy->rfreg_chnlval[0] = rtl92s_phy_query_rf_reg(hw,
(enum radio_path)0,
RF_CHNLBW,
RFREG_OFFSET_MASK);
rtlphy->rfreg_chnlval[1] = rtl92s_phy_query_rf_reg(hw,
(enum radio_path)1,
RF_CHNLBW,
RFREG_OFFSET_MASK);
/*---- Set CCK and OFDM Block "ON"----*/
rtl_set_bbreg(hw, RFPGA0_RFMOD, BCCKEN, 0x1);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BOFDMEN, 0x1);
/*3 Set Hardware(Do nothing now) */
_rtl92se_hw_configure(hw);
/* Read EEPROM TX power index and PHY_REG_PG.txt to capture correct */
/* TX power index for different rate set. */
/* Get original hw reg values */
rtl92s_phy_get_hw_reg_originalvalue(hw);
/* Write correct tx power index */
rtl92s_phy_set_txpower(hw, rtlphy->current_channel);
/* We must set MAC address after firmware download. */
for (i = 0; i < 6; i++)
rtl_write_byte(rtlpriv, MACIDR0 + i, rtlefuse->dev_addr[i]);
/* EEPROM R/W workaround */
tmp_u1b = rtl_read_byte(rtlpriv, MAC_PINMUX_CFG);
rtl_write_byte(rtlpriv, MAC_PINMUX_CFG, tmp_u1b & (~BIT(3)));
rtl_write_byte(rtlpriv, 0x4d, 0x0);
if (hal_get_firmwareversion(rtlpriv) >= 0x49) {
tmp_byte = rtl_read_byte(rtlpriv, FW_RSVD_PG_CRTL) & (~BIT(4));
tmp_byte = tmp_byte | BIT(5);
rtl_write_byte(rtlpriv, FW_RSVD_PG_CRTL, tmp_byte);
rtl_write_dword(rtlpriv, TXDESC_MSK, 0xFFFFCFFF);
}
/* We enable high power and RA related mechanism after NIC
* initialized. */
rtl92s_phy_set_fw_cmd(hw, FW_CMD_RA_INIT);
/* Add to prevent ASPM bug. */
/* Always enable hst and NIC clock request. */
rtl92s_phy_switch_ephy_parameter(hw);
/* Security related
* 1. Clear all H/W keys.
* 2. Enable H/W encryption/decryption. */
rtl_cam_reset_all_entry(hw);
secr_value |= SCR_TXENCENABLE;
secr_value |= SCR_RXENCENABLE;
secr_value |= SCR_NOSKMC;
rtl_write_byte(rtlpriv, REG_SECR, secr_value);
for (i = 0; i < 4; i++)
rtl_write_dword(rtlpriv, wdcapra_add[i], 0x5e4322);
if (rtlphy->rf_type == RF_1T2R) {
bool mrc2set = true;
/* Turn on B-Path */
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_MRC, (u8 *)&mrc2set);
}
rtlpriv->cfg->ops->led_control(hw, LED_CTL_POWER_ON);
rtl92s_dm_init(hw);
rtlpci->being_init_adapter = false;
return err;
}
void rtl92se_set_mac_addr(struct rtl_io *io, const u8 * addr)
{
}
void rtl92se_set_check_bssid(struct ieee80211_hw *hw, bool check_bssid)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u32 reg_rcr = rtlpci->receive_config;
if (rtlpriv->psc.rfpwr_state != ERFON)
return;
if (check_bssid) {
reg_rcr |= (RCR_CBSSID);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_RCR, (u8 *)(®_rcr));
} else if (!check_bssid) {
reg_rcr &= (~RCR_CBSSID);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_RCR, (u8 *)(®_rcr));
}
}
static int _rtl92se_set_media_status(struct ieee80211_hw *hw,
enum nl80211_iftype type)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 bt_msr = rtl_read_byte(rtlpriv, MSR);
u32 temp;
bt_msr &= ~MSR_LINK_MASK;
switch (type) {
case NL80211_IFTYPE_UNSPECIFIED:
bt_msr |= (MSR_LINK_NONE << MSR_LINK_SHIFT);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Set Network type to NO LINK!\n");
break;
case NL80211_IFTYPE_ADHOC:
bt_msr |= (MSR_LINK_ADHOC << MSR_LINK_SHIFT);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Set Network type to Ad Hoc!\n");
break;
case NL80211_IFTYPE_STATION:
bt_msr |= (MSR_LINK_MANAGED << MSR_LINK_SHIFT);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Set Network type to STA!\n");
break;
case NL80211_IFTYPE_AP:
bt_msr |= (MSR_LINK_MASTER << MSR_LINK_SHIFT);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Set Network type to AP!\n");
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Network type %d not supported!\n", type);
return 1;
break;
}
rtl_write_byte(rtlpriv, (MSR), bt_msr);
temp = rtl_read_dword(rtlpriv, TCR);
rtl_write_dword(rtlpriv, TCR, temp & (~BIT(8)));
rtl_write_dword(rtlpriv, TCR, temp | BIT(8));
return 0;
}
/* HW_VAR_MEDIA_STATUS & HW_VAR_CECHK_BSSID */
int rtl92se_set_network_type(struct ieee80211_hw *hw, enum nl80211_iftype type)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (_rtl92se_set_media_status(hw, type))
return -EOPNOTSUPP;
if (rtlpriv->mac80211.link_state == MAC80211_LINKED) {
if (type != NL80211_IFTYPE_AP)
rtl92se_set_check_bssid(hw, true);
} else {
rtl92se_set_check_bssid(hw, false);
}
return 0;
}
/* don't set REG_EDCA_BE_PARAM here because mac80211 will send pkt when scan */
void rtl92se_set_qos(struct ieee80211_hw *hw, int aci)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl92s_dm_init_edca_turbo(hw);
switch (aci) {
case AC1_BK:
rtl_write_dword(rtlpriv, EDCAPARA_BK, 0xa44f);
break;
case AC0_BE:
/* rtl_write_dword(rtlpriv, EDCAPARA_BE, u4b_ac_param); */
break;
case AC2_VI:
rtl_write_dword(rtlpriv, EDCAPARA_VI, 0x5e4322);
break;
case AC3_VO:
rtl_write_dword(rtlpriv, EDCAPARA_VO, 0x2f3222);
break;
default:
RT_ASSERT(false, "invalid aci: %d !\n", aci);
break;
}
}
void rtl92se_enable_interrupt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
rtl_write_dword(rtlpriv, INTA_MASK, rtlpci->irq_mask[0]);
/* Support Bit 32-37(Assign as Bit 0-5) interrupt setting now */
rtl_write_dword(rtlpriv, INTA_MASK + 4, rtlpci->irq_mask[1] & 0x3F);
}
void rtl92se_disable_interrupt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv;
struct rtl_pci *rtlpci;
rtlpriv = rtl_priv(hw);
/* if firmware not available, no interrupts */
if (!rtlpriv || !rtlpriv->max_fw_size)
return;
rtlpci = rtl_pcidev(rtl_pcipriv(hw));
rtl_write_dword(rtlpriv, INTA_MASK, 0);
rtl_write_dword(rtlpriv, INTA_MASK + 4, 0);
synchronize_irq(rtlpci->pdev->irq);
}
static u8 _rtl92s_set_sysclk(struct ieee80211_hw *hw, u8 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 waitcnt = 100;
bool result = false;
u8 tmp;
rtl_write_byte(rtlpriv, SYS_CLKR + 1, data);
/* Wait the MAC synchronized. */
udelay(400);
/* Check if it is set ready. */
tmp = rtl_read_byte(rtlpriv, SYS_CLKR + 1);
result = ((tmp & BIT(7)) == (data & BIT(7)));
if ((data & (BIT(6) | BIT(7))) == false) {
waitcnt = 100;
tmp = 0;
while (1) {
waitcnt--;
tmp = rtl_read_byte(rtlpriv, SYS_CLKR + 1);
if ((tmp & BIT(6)))
break;
pr_err("wait for BIT(6) return value %x\n", tmp);
if (waitcnt == 0)
break;
udelay(10);
}
if (waitcnt == 0)
result = false;
else
result = true;
}
return result;
}
static void _rtl92s_phy_set_rfhalt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u8 u1btmp;
if (rtlhal->driver_going2unload)
rtl_write_byte(rtlpriv, 0x560, 0x0);
/* Power save for BB/RF */
u1btmp = rtl_read_byte(rtlpriv, LDOV12D_CTRL);
u1btmp |= BIT(0);
rtl_write_byte(rtlpriv, LDOV12D_CTRL, u1btmp);
rtl_write_byte(rtlpriv, SPS1_CTRL, 0x0);
rtl_write_byte(rtlpriv, TXPAUSE, 0xFF);
rtl_write_word(rtlpriv, CMDR, 0x57FC);
udelay(100);
rtl_write_word(rtlpriv, CMDR, 0x77FC);
rtl_write_byte(rtlpriv, PHY_CCA, 0x0);
udelay(10);
rtl_write_word(rtlpriv, CMDR, 0x37FC);
udelay(10);
rtl_write_word(rtlpriv, CMDR, 0x77FC);
udelay(10);
rtl_write_word(rtlpriv, CMDR, 0x57FC);
rtl_write_word(rtlpriv, CMDR, 0x0000);
if (rtlhal->driver_going2unload) {
u1btmp = rtl_read_byte(rtlpriv, (REG_SYS_FUNC_EN + 1));
u1btmp &= ~(BIT(0));
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, u1btmp);
}
u1btmp = rtl_read_byte(rtlpriv, (SYS_CLKR + 1));
/* Add description. After switch control path. register
* after page1 will be invisible. We can not do any IO
* for register>0x40. After resume&MACIO reset, we need
* to remember previous reg content. */
if (u1btmp & BIT(7)) {
u1btmp &= ~(BIT(6) | BIT(7));
if (!_rtl92s_set_sysclk(hw, u1btmp)) {
pr_err("Switch ctrl path fail\n");
return;
}
}
/* Power save for MAC */
if (ppsc->rfoff_reason == RF_CHANGE_BY_IPS &&
!rtlhal->driver_going2unload) {
/* enable LED function */
rtl_write_byte(rtlpriv, 0x03, 0xF9);
/* SW/HW radio off or halt adapter!! For example S3/S4 */
} else {
/* LED function disable. Power range is about 8mA now. */
/* if write 0xF1 disconnet_pci power
* ifconfig wlan0 down power are both high 35:70 */
/* if write oxF9 disconnet_pci power
* ifconfig wlan0 down power are both low 12:45*/
rtl_write_byte(rtlpriv, 0x03, 0xF9);
}
rtl_write_byte(rtlpriv, SYS_CLKR + 1, 0x70);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL + 1, 0x68);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, 0x00);
rtl_write_byte(rtlpriv, LDOA15_CTRL, 0x34);
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL, 0x0E);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
}
static void _rtl92se_gen_refreshledstate(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_led *pLed0 = &(pcipriv->ledctl.sw_led0);
if (rtlpci->up_first_time == 1)
return;
if (rtlpriv->psc.rfoff_reason == RF_CHANGE_BY_IPS)
rtl92se_sw_led_on(hw, pLed0);
else
rtl92se_sw_led_off(hw, pLed0);
}
static void _rtl92se_power_domain_init(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u16 tmpu2b;
u8 tmpu1b;
rtlpriv->psc.pwrdomain_protect = true;
tmpu1b = rtl_read_byte(rtlpriv, (SYS_CLKR + 1));
if (tmpu1b & BIT(7)) {
tmpu1b &= ~(BIT(6) | BIT(7));
if (!_rtl92s_set_sysclk(hw, tmpu1b)) {
rtlpriv->psc.pwrdomain_protect = false;
return;
}
}
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, 0x0);
rtl_write_byte(rtlpriv, LDOA15_CTRL, 0x34);
/* Reset MAC-IO and CPU and Core Digital BIT10/11/15 */
tmpu1b = rtl_read_byte(rtlpriv, REG_SYS_FUNC_EN + 1);
/* If IPS we need to turn LED on. So we not
* not disable BIT 3/7 of reg3. */
if (rtlpriv->psc.rfoff_reason & (RF_CHANGE_BY_IPS | RF_CHANGE_BY_HW))
tmpu1b &= 0xFB;
else
tmpu1b &= 0x73;
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN + 1, tmpu1b);
/* wait for BIT 10/11/15 to pull high automatically!! */
mdelay(1);
rtl_write_byte(rtlpriv, CMDR, 0);
rtl_write_byte(rtlpriv, TCR, 0);
/* Data sheet not define 0x562!!! Copy from WMAC!!!!! */
tmpu1b = rtl_read_byte(rtlpriv, 0x562);
tmpu1b |= 0x08;
rtl_write_byte(rtlpriv, 0x562, tmpu1b);
tmpu1b &= ~(BIT(3));
rtl_write_byte(rtlpriv, 0x562, tmpu1b);
/* Enable AFE clock source */
tmpu1b = rtl_read_byte(rtlpriv, AFE_XTAL_CTRL);
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL, (tmpu1b | 0x01));
/* Delay 1.5ms */
udelay(1500);
tmpu1b = rtl_read_byte(rtlpriv, AFE_XTAL_CTRL + 1);
rtl_write_byte(rtlpriv, AFE_XTAL_CTRL + 1, (tmpu1b & 0xfb));
/* Enable AFE Macro Block's Bandgap */
tmpu1b = rtl_read_byte(rtlpriv, AFE_MISC);
rtl_write_byte(rtlpriv, AFE_MISC, (tmpu1b | BIT(0)));
mdelay(1);
/* Enable AFE Mbias */
tmpu1b = rtl_read_byte(rtlpriv, AFE_MISC);
rtl_write_byte(rtlpriv, AFE_MISC, (tmpu1b | 0x02));
mdelay(1);
/* Enable LDOA15 block */
tmpu1b = rtl_read_byte(rtlpriv, LDOA15_CTRL);
rtl_write_byte(rtlpriv, LDOA15_CTRL, (tmpu1b | BIT(0)));
/* Set Digital Vdd to Retention isolation Path. */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_ISO_CTRL);
rtl_write_word(rtlpriv, REG_SYS_ISO_CTRL, (tmpu2b | BIT(11)));
/* For warm reboot NIC disappera bug. */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(13)));
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL + 1, 0x68);
/* Enable AFE PLL Macro Block */
tmpu1b = rtl_read_byte(rtlpriv, AFE_PLL_CTRL);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL, (tmpu1b | BIT(0) | BIT(4)));
/* Enable MAC 80MHZ clock */
tmpu1b = rtl_read_byte(rtlpriv, AFE_PLL_CTRL + 1);
rtl_write_byte(rtlpriv, AFE_PLL_CTRL + 1, (tmpu1b | BIT(0)));
mdelay(1);
/* Release isolation AFE PLL & MD */
rtl_write_byte(rtlpriv, REG_SYS_ISO_CTRL, 0xA6);
/* Enable MAC clock */
tmpu2b = rtl_read_word(rtlpriv, SYS_CLKR);
rtl_write_word(rtlpriv, SYS_CLKR, (tmpu2b | BIT(12) | BIT(11)));
/* Enable Core digital and enable IOREG R/W */
tmpu2b = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(11)));
/* enable REG_EN */
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, (tmpu2b | BIT(11) | BIT(15)));
/* Switch the control path. */
tmpu2b = rtl_read_word(rtlpriv, SYS_CLKR);
rtl_write_word(rtlpriv, SYS_CLKR, (tmpu2b & (~BIT(2))));
tmpu1b = rtl_read_byte(rtlpriv, (SYS_CLKR + 1));
tmpu1b = ((tmpu1b | BIT(7)) & (~BIT(6)));
if (!_rtl92s_set_sysclk(hw, tmpu1b)) {
rtlpriv->psc.pwrdomain_protect = false;
return;
}
rtl_write_word(rtlpriv, CMDR, 0x37FC);
/* After MACIO reset,we must refresh LED state. */
_rtl92se_gen_refreshledstate(hw);
rtlpriv->psc.pwrdomain_protect = false;
}
void rtl92se_card_disable(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
enum nl80211_iftype opmode;
u8 wait = 30;
rtlpriv->intf_ops->enable_aspm(hw);
if (rtlpci->driver_is_goingto_unload ||
ppsc->rfoff_reason > RF_CHANGE_BY_PS)
rtlpriv->cfg->ops->led_control(hw, LED_CTL_POWER_OFF);
/* we should chnge GPIO to input mode
* this will drop away current about 25mA*/
rtl8192se_gpiobit3_cfg_inputmode(hw);
/* this is very important for ips power save */
while (wait-- >= 10 && rtlpriv->psc.pwrdomain_protect) {
if (rtlpriv->psc.pwrdomain_protect)
mdelay(20);
else
break;
}
mac->link_state = MAC80211_NOLINK;
opmode = NL80211_IFTYPE_UNSPECIFIED;
_rtl92se_set_media_status(hw, opmode);
_rtl92s_phy_set_rfhalt(hw);
udelay(100);
}
void rtl92se_interrupt_recognized(struct ieee80211_hw *hw, u32 *p_inta,
u32 *p_intb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
*p_inta = rtl_read_dword(rtlpriv, ISR) & rtlpci->irq_mask[0];
rtl_write_dword(rtlpriv, ISR, *p_inta);
*p_intb = rtl_read_dword(rtlpriv, ISR + 4) & rtlpci->irq_mask[1];
rtl_write_dword(rtlpriv, ISR + 4, *p_intb);
}
void rtl92se_set_beacon_related_registers(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u16 bcntime_cfg = 0;
u16 bcn_cw = 6, bcn_ifs = 0xf;
u16 atim_window = 2;
/* ATIM Window (in unit of TU). */
rtl_write_word(rtlpriv, ATIMWND, atim_window);
/* Beacon interval (in unit of TU). */
rtl_write_word(rtlpriv, BCN_INTERVAL, mac->beacon_interval);
/* DrvErlyInt (in unit of TU). (Time to send
* interrupt to notify driver to change
* beacon content) */
rtl_write_word(rtlpriv, BCN_DRV_EARLY_INT, 10 << 4);
/* BcnDMATIM(in unit of us). Indicates the
* time before TBTT to perform beacon queue DMA */
rtl_write_word(rtlpriv, BCN_DMATIME, 256);
/* Force beacon frame transmission even
* after receiving beacon frame from
* other ad hoc STA */
rtl_write_byte(rtlpriv, BCN_ERR_THRESH, 100);
/* Beacon Time Configuration */
if (mac->opmode == NL80211_IFTYPE_ADHOC)
bcntime_cfg |= (bcn_cw << BCN_TCFG_CW_SHIFT);
/* TODO: bcn_ifs may required to be changed on ASIC */
bcntime_cfg |= bcn_ifs << BCN_TCFG_IFS;
/*for beacon changed */
rtl92s_phy_set_beacon_hwreg(hw, mac->beacon_interval);
}
void rtl92se_set_beacon_interval(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u16 bcn_interval = mac->beacon_interval;
/* Beacon interval (in unit of TU). */
rtl_write_word(rtlpriv, BCN_INTERVAL, bcn_interval);
/* 2008.10.24 added by tynli for beacon changed. */
rtl92s_phy_set_beacon_hwreg(hw, bcn_interval);
}
void rtl92se_update_interrupt_mask(struct ieee80211_hw *hw,
u32 add_msr, u32 rm_msr)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
RT_TRACE(rtlpriv, COMP_INTR, DBG_LOUD, "add_msr:%x, rm_msr:%x\n",
add_msr, rm_msr);
if (add_msr)
rtlpci->irq_mask[0] |= add_msr;
if (rm_msr)
rtlpci->irq_mask[0] &= (~rm_msr);
rtl92se_disable_interrupt(hw);
rtl92se_enable_interrupt(hw);
}
static void _rtl8192se_get_IC_Inferiority(struct ieee80211_hw *hw)
{
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u8 efuse_id;
rtlhal->ic_class = IC_INFERIORITY_A;
/* Only retrieving while using EFUSE. */
if ((rtlefuse->epromtype == EEPROM_BOOT_EFUSE) &&
!rtlefuse->autoload_failflag) {
efuse_id = efuse_read_1byte(hw, EFUSE_IC_ID_OFFSET);
if (efuse_id == 0xfe)
rtlhal->ic_class = IC_INFERIORITY_B;
}
}
static void _rtl92se_read_adapter_info(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u16 i, usvalue;
u16 eeprom_id;
u8 tempval;
u8 hwinfo[HWSET_MAX_SIZE_92S];
u8 rf_path, index;
if (rtlefuse->epromtype == EEPROM_93C46) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"RTL819X Not boot from eeprom, check it !!\n");
} else if (rtlefuse->epromtype == EEPROM_BOOT_EFUSE) {
rtl_efuse_shadow_map_update(hw);
memcpy((void *)hwinfo, (void *)
&rtlefuse->efuse_map[EFUSE_INIT_MAP][0],
HWSET_MAX_SIZE_92S);
}
RT_PRINT_DATA(rtlpriv, COMP_INIT, DBG_DMESG, "MAP",
hwinfo, HWSET_MAX_SIZE_92S);
eeprom_id = *((u16 *)&hwinfo[0]);
if (eeprom_id != RTL8190_EEPROM_ID) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"EEPROM ID(%#x) is invalid!!\n", eeprom_id);
rtlefuse->autoload_failflag = true;
} else {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "Autoload OK\n");
rtlefuse->autoload_failflag = false;
}
if (rtlefuse->autoload_failflag)
return;
_rtl8192se_get_IC_Inferiority(hw);
/* Read IC Version && Channel Plan */
/* VID, DID SE 0xA-D */
rtlefuse->eeprom_vid = *(u16 *)&hwinfo[EEPROM_VID];
rtlefuse->eeprom_did = *(u16 *)&hwinfo[EEPROM_DID];
rtlefuse->eeprom_svid = *(u16 *)&hwinfo[EEPROM_SVID];
rtlefuse->eeprom_smid = *(u16 *)&hwinfo[EEPROM_SMID];
rtlefuse->eeprom_version = *(u16 *)&hwinfo[EEPROM_VERSION];
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"EEPROMId = 0x%4x\n", eeprom_id);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"EEPROM VID = 0x%4x\n", rtlefuse->eeprom_vid);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"EEPROM DID = 0x%4x\n", rtlefuse->eeprom_did);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"EEPROM SVID = 0x%4x\n", rtlefuse->eeprom_svid);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"EEPROM SMID = 0x%4x\n", rtlefuse->eeprom_smid);
for (i = 0; i < 6; i += 2) {
usvalue = *(u16 *)&hwinfo[EEPROM_MAC_ADDR + i];
*((u16 *) (&rtlefuse->dev_addr[i])) = usvalue;
}
for (i = 0; i < 6; i++)
rtl_write_byte(rtlpriv, MACIDR0 + i, rtlefuse->dev_addr[i]);
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "%pM\n", rtlefuse->dev_addr);
/* Get Tx Power Level by Channel */
/* Read Tx power of Channel 1 ~ 14 from EEPROM. */
/* 92S suupport RF A & B */
for (rf_path = 0; rf_path < 2; rf_path++) {
for (i = 0; i < 3; i++) {
/* Read CCK RF A & B Tx power */
rtlefuse->eeprom_chnlarea_txpwr_cck[rf_path][i] =
hwinfo[EEPROM_TXPOWERBASE + rf_path * 3 + i];
/* Read OFDM RF A & B Tx power for 1T */
rtlefuse->eeprom_chnlarea_txpwr_ht40_1s[rf_path][i] =
hwinfo[EEPROM_TXPOWERBASE + 6 + rf_path * 3 + i];
/* Read OFDM RF A & B Tx power for 2T */
rtlefuse->eeprom_chnlarea_txpwr_ht40_2sdiif[rf_path][i]
= hwinfo[EEPROM_TXPOWERBASE + 12 +
rf_path * 3 + i];
}
}
for (rf_path = 0; rf_path < 2; rf_path++)
for (i = 0; i < 3; i++)
RTPRINT(rtlpriv, FINIT, INIT_EEPROM,
"RF(%d) EEPROM CCK Area(%d) = 0x%x\n",
rf_path, i,
rtlefuse->eeprom_chnlarea_txpwr_cck
[rf_path][i]);
for (rf_path = 0; rf_path < 2; rf_path++)
for (i = 0; i < 3; i++)
RTPRINT(rtlpriv, FINIT, INIT_EEPROM,
"RF(%d) EEPROM HT40 1S Area(%d) = 0x%x\n",
rf_path, i,
rtlefuse->eeprom_chnlarea_txpwr_ht40_1s
[rf_path][i]);
for (rf_path = 0; rf_path < 2; rf_path++)
for (i = 0; i < 3; i++)
RTPRINT(rtlpriv, FINIT, INIT_EEPROM,
"RF(%d) EEPROM HT40 2S Diff Area(%d) = 0x%x\n",
rf_path, i,
rtlefuse->eeprom_chnlarea_txpwr_ht40_2sdiif
[rf_path][i]);
for (rf_path = 0; rf_path < 2; rf_path++) {
/* Assign dedicated channel tx power */
for (i = 0; i < 14; i++) {
/* channel 1~3 use the same Tx Power Level. */
if (i < 3)
index = 0;
/* Channel 4-8 */
else if (i < 8)
index = 1;
/* Channel 9-14 */
else
index = 2;
/* Record A & B CCK /OFDM - 1T/2T Channel area
* tx power */
rtlefuse->txpwrlevel_cck[rf_path][i] =
rtlefuse->eeprom_chnlarea_txpwr_cck
[rf_path][index];
rtlefuse->txpwrlevel_ht40_1s[rf_path][i] =
rtlefuse->eeprom_chnlarea_txpwr_ht40_1s
[rf_path][index];
rtlefuse->txpwrlevel_ht40_2s[rf_path][i] =
rtlefuse->eeprom_chnlarea_txpwr_ht40_2sdiif
[rf_path][index];
}
for (i = 0; i < 14; i++) {
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF(%d)-Ch(%d) [CCK / HT40_1S / HT40_2S] = [0x%x / 0x%x / 0x%x]\n",
rf_path, i,
rtlefuse->txpwrlevel_cck[rf_path][i],
rtlefuse->txpwrlevel_ht40_1s[rf_path][i],
rtlefuse->txpwrlevel_ht40_2s[rf_path][i]);
}
}
for (rf_path = 0; rf_path < 2; rf_path++) {
for (i = 0; i < 3; i++) {
/* Read Power diff limit. */
rtlefuse->eeprom_pwrgroup[rf_path][i] =
hwinfo[EEPROM_TXPWRGROUP + rf_path * 3 + i];
}
}
for (rf_path = 0; rf_path < 2; rf_path++) {
/* Fill Pwr group */
for (i = 0; i < 14; i++) {
/* Chanel 1-3 */
if (i < 3)
index = 0;
/* Channel 4-8 */
else if (i < 8)
index = 1;
/* Channel 9-13 */
else
index = 2;
rtlefuse->pwrgroup_ht20[rf_path][i] =
(rtlefuse->eeprom_pwrgroup[rf_path][index] &
0xf);
rtlefuse->pwrgroup_ht40[rf_path][i] =
((rtlefuse->eeprom_pwrgroup[rf_path][index] &
0xf0) >> 4);
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-%d pwrgroup_ht20[%d] = 0x%x\n",
rf_path, i,
rtlefuse->pwrgroup_ht20[rf_path][i]);
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-%d pwrgroup_ht40[%d] = 0x%x\n",
rf_path, i,
rtlefuse->pwrgroup_ht40[rf_path][i]);
}
}
for (i = 0; i < 14; i++) {
/* Read tx power difference between HT OFDM 20/40 MHZ */
/* channel 1-3 */
if (i < 3)
index = 0;
/* Channel 4-8 */
else if (i < 8)
index = 1;
/* Channel 9-14 */
else
index = 2;
tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_HT20_DIFF +
index]) & 0xff;
rtlefuse->txpwr_ht20diff[RF90_PATH_A][i] = (tempval & 0xF);
rtlefuse->txpwr_ht20diff[RF90_PATH_B][i] =
((tempval >> 4) & 0xF);
/* Read OFDM<->HT tx power diff */
/* Channel 1-3 */
if (i < 3)
index = 0;
/* Channel 4-8 */
else if (i < 8)
index = 0x11;
/* Channel 9-14 */
else
index = 1;
tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF + index])
& 0xff;
rtlefuse->txpwr_legacyhtdiff[RF90_PATH_A][i] =
(tempval & 0xF);
rtlefuse->txpwr_legacyhtdiff[RF90_PATH_B][i] =
((tempval >> 4) & 0xF);
tempval = (*(u8 *)&hwinfo[TX_PWR_SAFETY_CHK]);
rtlefuse->txpwr_safetyflag = (tempval & 0x01);
}
rtlefuse->eeprom_regulatory = 0;
if (rtlefuse->eeprom_version >= 2) {
/* BIT(0)~2 */
if (rtlefuse->eeprom_version >= 4)
rtlefuse->eeprom_regulatory =
(hwinfo[EEPROM_REGULATORY] & 0x7);
else /* BIT(0) */
rtlefuse->eeprom_regulatory =
(hwinfo[EEPROM_REGULATORY] & 0x1);
}
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"eeprom_regulatory = 0x%x\n", rtlefuse->eeprom_regulatory);
for (i = 0; i < 14; i++)
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-A Ht20 to HT40 Diff[%d] = 0x%x\n",
i, rtlefuse->txpwr_ht20diff[RF90_PATH_A][i]);
for (i = 0; i < 14; i++)
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-A Legacy to Ht40 Diff[%d] = 0x%x\n",
i, rtlefuse->txpwr_legacyhtdiff[RF90_PATH_A][i]);
for (i = 0; i < 14; i++)
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-B Ht20 to HT40 Diff[%d] = 0x%x\n",
i, rtlefuse->txpwr_ht20diff[RF90_PATH_B][i]);
for (i = 0; i < 14; i++)
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"RF-B Legacy to HT40 Diff[%d] = 0x%x\n",
i, rtlefuse->txpwr_legacyhtdiff[RF90_PATH_B][i]);
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"TxPwrSafetyFlag = %d\n", rtlefuse->txpwr_safetyflag);
/* Read RF-indication and Tx Power gain
* index diff of legacy to HT OFDM rate. */
tempval = (*(u8 *)&hwinfo[EEPROM_RFIND_POWERDIFF]) & 0xff;
rtlefuse->eeprom_txpowerdiff = tempval;
rtlefuse->legacy_httxpowerdiff =
rtlefuse->txpwr_legacyhtdiff[RF90_PATH_A][0];
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"TxPowerDiff = %#x\n", rtlefuse->eeprom_txpowerdiff);
/* Get TSSI value for each path. */
usvalue = *(u16 *)&hwinfo[EEPROM_TSSI_A];
rtlefuse->eeprom_tssi[RF90_PATH_A] = (u8)((usvalue & 0xff00) >> 8);
usvalue = *(u8 *)&hwinfo[EEPROM_TSSI_B];
rtlefuse->eeprom_tssi[RF90_PATH_B] = (u8)(usvalue & 0xff);
RTPRINT(rtlpriv, FINIT, INIT_TxPower, "TSSI_A = 0x%x, TSSI_B = 0x%x\n",
rtlefuse->eeprom_tssi[RF90_PATH_A],
rtlefuse->eeprom_tssi[RF90_PATH_B]);
/* Read antenna tx power offset of B/C/D to A from EEPROM */
/* and read ThermalMeter from EEPROM */
tempval = *(u8 *)&hwinfo[EEPROM_THERMALMETER];
rtlefuse->eeprom_thermalmeter = tempval;
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"thermalmeter = 0x%x\n", rtlefuse->eeprom_thermalmeter);
/* ThermalMeter, BIT(0)~3 for RFIC1, BIT(4)~7 for RFIC2 */
rtlefuse->thermalmeter[0] = (rtlefuse->eeprom_thermalmeter & 0x1f);
rtlefuse->tssi_13dbm = rtlefuse->eeprom_thermalmeter * 100;
/* Read CrystalCap from EEPROM */
tempval = (*(u8 *)&hwinfo[EEPROM_CRYSTALCAP]) >> 4;
rtlefuse->eeprom_crystalcap = tempval;
/* CrystalCap, BIT(12)~15 */
rtlefuse->crystalcap = rtlefuse->eeprom_crystalcap;
/* Read IC Version && Channel Plan */
/* Version ID, Channel plan */
rtlefuse->eeprom_channelplan = *(u8 *)&hwinfo[EEPROM_CHANNELPLAN];
rtlefuse->txpwr_fromeprom = true;
RTPRINT(rtlpriv, FINIT, INIT_TxPower,
"EEPROM ChannelPlan = 0x%4x\n", rtlefuse->eeprom_channelplan);
/* Read Customer ID or Board Type!!! */
tempval = *(u8 *)&hwinfo[EEPROM_BOARDTYPE];
/* Change RF type definition */
if (tempval == 0)
rtlphy->rf_type = RF_2T2R;
else if (tempval == 1)
rtlphy->rf_type = RF_1T2R;
else if (tempval == 2)
rtlphy->rf_type = RF_1T2R;
else if (tempval == 3)
rtlphy->rf_type = RF_1T1R;
/* 1T2R but 1SS (1x1 receive combining) */
rtlefuse->b1x1_recvcombine = false;
if (rtlphy->rf_type == RF_1T2R) {
tempval = rtl_read_byte(rtlpriv, 0x07);
if (!(tempval & BIT(0))) {
rtlefuse->b1x1_recvcombine = true;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"RF_TYPE=1T2R but only 1SS\n");
}
}
rtlefuse->b1ss_support = rtlefuse->b1x1_recvcombine;
rtlefuse->eeprom_oemid = *(u8 *)&hwinfo[EEPROM_CUSTOMID];
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "EEPROM Customer ID: 0x%2x",
rtlefuse->eeprom_oemid);
/* set channel paln to world wide 13 */
rtlefuse->channel_plan = COUNTRY_CODE_WORLD_WIDE_13;
}
void rtl92se_read_eeprom_info(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 tmp_u1b = 0;
tmp_u1b = rtl_read_byte(rtlpriv, EPROM_CMD);
if (tmp_u1b & BIT(4)) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "Boot from EEPROM\n");
rtlefuse->epromtype = EEPROM_93C46;
} else {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "Boot from EFUSE\n");
rtlefuse->epromtype = EEPROM_BOOT_EFUSE;
}
if (tmp_u1b & BIT(5)) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "Autoload OK\n");
rtlefuse->autoload_failflag = false;
_rtl92se_read_adapter_info(hw);
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "Autoload ERR!!\n");
rtlefuse->autoload_failflag = true;
}
}
static void rtl92se_update_hal_rate_table(struct ieee80211_hw *hw,
struct ieee80211_sta *sta)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u32 ratr_value;
u8 ratr_index = 0;
u8 nmode = mac->ht_enable;
u8 mimo_ps = IEEE80211_SMPS_OFF;
u16 shortgi_rate = 0;
u32 tmp_ratr_value = 0;
u8 curtxbw_40mhz = mac->bw_40;
u8 curshortgi_40mhz = (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_40) ?
1 : 0;
u8 curshortgi_20mhz = (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_20) ?
1 : 0;
enum wireless_mode wirelessmode = mac->mode;
if (rtlhal->current_bandtype == BAND_ON_5G)
ratr_value = sta->supp_rates[1] << 4;
else
ratr_value = sta->supp_rates[0];
ratr_value |= (sta->ht_cap.mcs.rx_mask[1] << 20 |
sta->ht_cap.mcs.rx_mask[0] << 12);
switch (wirelessmode) {
case WIRELESS_MODE_B:
ratr_value &= 0x0000000D;
break;
case WIRELESS_MODE_G:
ratr_value &= 0x00000FF5;
break;
case WIRELESS_MODE_N_24G:
case WIRELESS_MODE_N_5G:
nmode = 1;
if (mimo_ps == IEEE80211_SMPS_STATIC) {
ratr_value &= 0x0007F005;
} else {
u32 ratr_mask;
if (get_rf_type(rtlphy) == RF_1T2R ||
get_rf_type(rtlphy) == RF_1T1R) {
if (curtxbw_40mhz)
ratr_mask = 0x000ff015;
else
ratr_mask = 0x000ff005;
} else {
if (curtxbw_40mhz)
ratr_mask = 0x0f0ff015;
else
ratr_mask = 0x0f0ff005;
}
ratr_value &= ratr_mask;
}
break;
default:
if (rtlphy->rf_type == RF_1T2R)
ratr_value &= 0x000ff0ff;
else
ratr_value &= 0x0f0ff0ff;
break;
}
if (rtlpriv->rtlhal.version >= VERSION_8192S_BCUT)
ratr_value &= 0x0FFFFFFF;
else if (rtlpriv->rtlhal.version == VERSION_8192S_ACUT)
ratr_value &= 0x0FFFFFF0;
if (nmode && ((curtxbw_40mhz &&
curshortgi_40mhz) || (!curtxbw_40mhz &&
curshortgi_20mhz))) {
ratr_value |= 0x10000000;
tmp_ratr_value = (ratr_value >> 12);
for (shortgi_rate = 15; shortgi_rate > 0; shortgi_rate--) {
if ((1 << shortgi_rate) & tmp_ratr_value)
break;
}
shortgi_rate = (shortgi_rate << 12) | (shortgi_rate << 8) |
(shortgi_rate << 4) | (shortgi_rate);
rtl_write_byte(rtlpriv, SG_RATE, shortgi_rate);
}
rtl_write_dword(rtlpriv, ARFR0 + ratr_index * 4, ratr_value);
if (ratr_value & 0xfffff000)
rtl92s_phy_set_fw_cmd(hw, FW_CMD_RA_REFRESH_N);
else
rtl92s_phy_set_fw_cmd(hw, FW_CMD_RA_REFRESH_BG);
RT_TRACE(rtlpriv, COMP_RATR, DBG_DMESG, "%x\n",
rtl_read_dword(rtlpriv, ARFR0));
}
static void rtl92se_update_hal_rate_mask(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
u8 rssi_level)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_sta_info *sta_entry = NULL;
u32 ratr_bitmap;
u8 ratr_index = 0;
u8 curtxbw_40mhz = (sta->ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40)
? 1 : 0;
u8 curshortgi_40mhz = (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_40) ?
1 : 0;
u8 curshortgi_20mhz = (sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_20) ?
1 : 0;
enum wireless_mode wirelessmode = 0;
bool shortgi = false;
u32 ratr_value = 0;
u8 shortgi_rate = 0;
u32 mask = 0;
u32 band = 0;
bool bmulticast = false;
u8 macid = 0;
u8 mimo_ps = IEEE80211_SMPS_OFF;
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
wirelessmode = sta_entry->wireless_mode;
if (mac->opmode == NL80211_IFTYPE_STATION)
curtxbw_40mhz = mac->bw_40;
else if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_ADHOC)
macid = sta->aid + 1;
if (rtlhal->current_bandtype == BAND_ON_5G)
ratr_bitmap = sta->supp_rates[1] << 4;
else
ratr_bitmap = sta->supp_rates[0];
ratr_bitmap |= (sta->ht_cap.mcs.rx_mask[1] << 20 |
sta->ht_cap.mcs.rx_mask[0] << 12);
switch (wirelessmode) {
case WIRELESS_MODE_B:
band |= WIRELESS_11B;
ratr_index = RATR_INX_WIRELESS_B;
if (ratr_bitmap & 0x0000000c)
ratr_bitmap &= 0x0000000d;
else
ratr_bitmap &= 0x0000000f;
break;
case WIRELESS_MODE_G:
band |= (WIRELESS_11G | WIRELESS_11B);
ratr_index = RATR_INX_WIRELESS_GB;
if (rssi_level == 1)
ratr_bitmap &= 0x00000f00;
else if (rssi_level == 2)
ratr_bitmap &= 0x00000ff0;
else
ratr_bitmap &= 0x00000ff5;
break;
case WIRELESS_MODE_A:
band |= WIRELESS_11A;
ratr_index = RATR_INX_WIRELESS_A;
ratr_bitmap &= 0x00000ff0;
break;
case WIRELESS_MODE_N_24G:
case WIRELESS_MODE_N_5G:
band |= (WIRELESS_11N | WIRELESS_11G | WIRELESS_11B);
ratr_index = RATR_INX_WIRELESS_NGB;
if (mimo_ps == IEEE80211_SMPS_STATIC) {
if (rssi_level == 1)
ratr_bitmap &= 0x00070000;
else if (rssi_level == 2)
ratr_bitmap &= 0x0007f000;
else
ratr_bitmap &= 0x0007f005;
} else {
if (rtlphy->rf_type == RF_1T2R ||
rtlphy->rf_type == RF_1T1R) {
if (rssi_level == 1) {
ratr_bitmap &= 0x000f0000;
} else if (rssi_level == 3) {
ratr_bitmap &= 0x000fc000;
} else if (rssi_level == 5) {
ratr_bitmap &= 0x000ff000;
} else {
if (curtxbw_40mhz)
ratr_bitmap &= 0x000ff015;
else
ratr_bitmap &= 0x000ff005;
}
} else {
if (rssi_level == 1) {
ratr_bitmap &= 0x0f8f0000;
} else if (rssi_level == 3) {
ratr_bitmap &= 0x0f8fc000;
} else if (rssi_level == 5) {
ratr_bitmap &= 0x0f8ff000;
} else {
if (curtxbw_40mhz)
ratr_bitmap &= 0x0f8ff015;
else
ratr_bitmap &= 0x0f8ff005;
}
}
}
if ((curtxbw_40mhz && curshortgi_40mhz) ||
(!curtxbw_40mhz && curshortgi_20mhz)) {
if (macid == 0)
shortgi = true;
else if (macid == 1)
shortgi = false;
}
break;
default:
band |= (WIRELESS_11N | WIRELESS_11G | WIRELESS_11B);
ratr_index = RATR_INX_WIRELESS_NGB;
if (rtlphy->rf_type == RF_1T2R)
ratr_bitmap &= 0x000ff0ff;
else
ratr_bitmap &= 0x0f8ff0ff;
break;
}
if (rtlpriv->rtlhal.version >= VERSION_8192S_BCUT)
ratr_bitmap &= 0x0FFFFFFF;
else if (rtlpriv->rtlhal.version == VERSION_8192S_ACUT)
ratr_bitmap &= 0x0FFFFFF0;
if (shortgi) {
ratr_bitmap |= 0x10000000;
/* Get MAX MCS available. */
ratr_value = (ratr_bitmap >> 12);
for (shortgi_rate = 15; shortgi_rate > 0; shortgi_rate--) {
if ((1 << shortgi_rate) & ratr_value)
break;
}
shortgi_rate = (shortgi_rate << 12) | (shortgi_rate << 8) |
(shortgi_rate << 4) | (shortgi_rate);
rtl_write_byte(rtlpriv, SG_RATE, shortgi_rate);
}
mask |= (bmulticast ? 1 : 0) << 9 | (macid & 0x1f) << 4 | (band & 0xf);
RT_TRACE(rtlpriv, COMP_RATR, DBG_TRACE, "mask = %x, bitmap = %x\n",
mask, ratr_bitmap);
rtl_write_dword(rtlpriv, 0x2c4, ratr_bitmap);
rtl_write_dword(rtlpriv, WFM5, (FW_RA_UPDATE_MASK | (mask << 8)));
if (macid != 0)
sta_entry->ratr_index = ratr_index;
}
void rtl92se_update_hal_rate_tbl(struct ieee80211_hw *hw,
struct ieee80211_sta *sta, u8 rssi_level)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (rtlpriv->dm.useramask)
rtl92se_update_hal_rate_mask(hw, sta, rssi_level);
else
rtl92se_update_hal_rate_table(hw, sta);
}
void rtl92se_update_channel_access_setting(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u16 sifs_timer;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SLOT_TIME,
(u8 *)&mac->slot_time);
sifs_timer = 0x0e0e;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SIFS, (u8 *)&sifs_timer);
}
/* this ifunction is for RFKILL, it's different with windows,
* because UI will disable wireless when GPIO Radio Off.
* And here we not check or Disable/Enable ASPM like windows*/
bool rtl92se_gpio_radio_on_off_checking(struct ieee80211_hw *hw, u8 *valid)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
enum rf_pwrstate rfpwr_toset /*, cur_rfstate */;
unsigned long flag = 0;
bool actuallyset = false;
bool turnonbypowerdomain = false;
/* just 8191se can check gpio before firstup, 92c/92d have fixed it */
if ((rtlpci->up_first_time == 1) || (rtlpci->being_init_adapter))
return false;
if (ppsc->swrf_processing)
return false;
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flag);
if (ppsc->rfchange_inprogress) {
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flag);
return false;
} else {
ppsc->rfchange_inprogress = true;
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flag);
}
/* cur_rfstate = ppsc->rfpwr_state;*/
/* because after _rtl92s_phy_set_rfhalt, all power
* closed, so we must open some power for GPIO check,
* or we will always check GPIO RFOFF here,
* And we should close power after GPIO check */
if (RT_IN_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC)) {
_rtl92se_power_domain_init(hw);
turnonbypowerdomain = true;
}
rfpwr_toset = _rtl92se_rf_onoff_detect(hw);
if ((ppsc->hwradiooff) && (rfpwr_toset == ERFON)) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"RFKILL-HW Radio ON, RF ON\n");
rfpwr_toset = ERFON;
ppsc->hwradiooff = false;
actuallyset = true;
} else if ((!ppsc->hwradiooff) && (rfpwr_toset == ERFOFF)) {
RT_TRACE(rtlpriv, COMP_RF,
DBG_DMESG, "RFKILL-HW Radio OFF, RF OFF\n");
rfpwr_toset = ERFOFF;
ppsc->hwradiooff = true;
actuallyset = true;
}
if (actuallyset) {
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flag);
ppsc->rfchange_inprogress = false;
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flag);
/* this not include ifconfig wlan0 down case */
/* } else if (rfpwr_toset == ERFOFF || cur_rfstate == ERFOFF) { */
} else {
/* because power_domain_init may be happen when
* _rtl92s_phy_set_rfhalt, this will open some powers
* and cause current increasing about 40 mA for ips,
* rfoff and ifconfig down, so we set
* _rtl92s_phy_set_rfhalt again here */
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_HALT_NIC &&
turnonbypowerdomain) {
_rtl92s_phy_set_rfhalt(hw);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
}
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flag);
ppsc->rfchange_inprogress = false;
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flag);
}
*valid = 1;
return !ppsc->hwradiooff;
}
/* Is_wepkey just used for WEP used as group & pairwise key
* if pairwise is AES ang group is WEP Is_wepkey == false.*/
void rtl92se_set_key(struct ieee80211_hw *hw, u32 key_index, u8 *p_macaddr,
bool is_group, u8 enc_algo, bool is_wepkey, bool clear_all)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 *macaddr = p_macaddr;
u32 entry_id = 0;
bool is_pairwise = false;
static u8 cam_const_addr[4][6] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x03}
};
static u8 cam_const_broad[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
if (clear_all) {
u8 idx = 0;
u8 cam_offset = 0;
u8 clear_number = 5;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "clear_all\n");
for (idx = 0; idx < clear_number; idx++) {
rtl_cam_mark_invalid(hw, cam_offset + idx);
rtl_cam_empty_entry(hw, cam_offset + idx);
if (idx < 5) {
memset(rtlpriv->sec.key_buf[idx], 0,
MAX_KEY_LEN);
rtlpriv->sec.key_len[idx] = 0;
}
}
} else {
switch (enc_algo) {
case WEP40_ENCRYPTION:
enc_algo = CAM_WEP40;
break;
case WEP104_ENCRYPTION:
enc_algo = CAM_WEP104;
break;
case TKIP_ENCRYPTION:
enc_algo = CAM_TKIP;
break;
case AESCCMP_ENCRYPTION:
enc_algo = CAM_AES;
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
enc_algo = CAM_TKIP;
break;
}
if (is_wepkey || rtlpriv->sec.use_defaultkey) {
macaddr = cam_const_addr[key_index];
entry_id = key_index;
} else {
if (is_group) {
macaddr = cam_const_broad;
entry_id = key_index;
} else {
if (mac->opmode == NL80211_IFTYPE_AP) {
entry_id = rtl_cam_get_free_entry(hw,
p_macaddr);
if (entry_id >= TOTAL_CAM_ENTRY) {
RT_TRACE(rtlpriv,
COMP_SEC, DBG_EMERG,
"Can not find free hw security cam entry\n");
return;
}
} else {
entry_id = CAM_PAIRWISE_KEY_POSITION;
}
key_index = PAIRWISE_KEYIDX;
is_pairwise = true;
}
}
if (rtlpriv->sec.key_len[key_index] == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"delete one entry, entry_id is %d\n",
entry_id);
if (mac->opmode == NL80211_IFTYPE_AP)
rtl_cam_del_entry(hw, p_macaddr);
rtl_cam_delete_one_entry(hw, p_macaddr, entry_id);
} else {
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The insert KEY length is %d\n",
rtlpriv->sec.key_len[PAIRWISE_KEYIDX]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The insert KEY is %x %x\n",
rtlpriv->sec.key_buf[0][0],
rtlpriv->sec.key_buf[0][1]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"add one entry\n");
if (is_pairwise) {
RT_PRINT_DATA(rtlpriv, COMP_SEC, DBG_LOUD,
"Pairwise Key content",
rtlpriv->sec.pairwise_key,
rtlpriv->sec.
key_len[PAIRWISE_KEYIDX]);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set Pairwise key\n");
rtl_cam_add_one_entry(hw, macaddr, key_index,
entry_id, enc_algo,
CAM_CONFIG_NO_USEDK,
rtlpriv->sec.key_buf[key_index]);
} else {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set group key\n");
if (mac->opmode == NL80211_IFTYPE_ADHOC) {
rtl_cam_add_one_entry(hw,
rtlefuse->dev_addr,
PAIRWISE_KEYIDX,
CAM_PAIRWISE_KEY_POSITION,
enc_algo, CAM_CONFIG_NO_USEDK,
rtlpriv->sec.key_buf[entry_id]);
}
rtl_cam_add_one_entry(hw, macaddr, key_index,
entry_id, enc_algo,
CAM_CONFIG_NO_USEDK,
rtlpriv->sec.key_buf[entry_id]);
}
}
}
}
void rtl92se_suspend(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
rtlpci->up_first_time = true;
}
void rtl92se_resume(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u32 val;
pci_read_config_dword(rtlpci->pdev, 0x40, &val);
if ((val & 0x0000ff00) != 0)
pci_write_config_dword(rtlpci->pdev, 0x40,
val & 0xffff00ff);
}
| bsd-2-clause |
hnhoan/LED-Matrix-Arduino | LedMxLib/ledmxfont.c | 1 | 24445 | /*---------------------------------------------------------------------------
File : ledmxfont.c
Author : Hoang Nguyen Hoan Feb. 28, 2011
Desc : Font definitions for use with LED Matrix Display
Copyright (c) 2011, I-SYST inc, all rights reserved
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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include "ledmxfont.h"
const LEDMXFONT_BITMAP g_FontBitmap[256] PROGMEM = {
{0, {0,}}, // 0x00 (0)
{0, {0,}}, // 0x01 (1)
{0, {0,}}, // 0x02 (2)
{0, {0,}}, // 0x03 (3)
{0, {0,}}, // 0x04 (4)
{0, {0,}}, // 0x05 (5)
{0, {0,}}, // 0x06 (6)
{0, {0,}}, // 0x07 (7)
{0, {0,}}, // 0x08 (8)
{0, {0,}}, // 0x09 (9)
{0, {0,}}, // 0x0A (10)
{0, {0,}}, // 0x0B (11)
{0, {0,}}, // 0x0C (12)
{0, {0,}}, // 0x0D (13)
{0, {0,}}, // 0x0E (14)
{0, {0,}}, // 0x0F (15)
{0, {0,}}, // 0x10 (16)
{0, {0,}}, // 0x11 (17)
{0, {0,}}, // 0x12 (18)
{0, {0,}}, // 0x13 (19)
{0, {0,}}, // 0x14 (20)
{0, {0,}}, // 0x15 (21)
{0, {0,}}, // 0x16 (22)
{0, {0,}}, // 0x17 (23)
{0, {0,}}, // 0x18 (24)
{0, {0,}}, // 0x19 (25)
{0, {0,}}, // 0x1A (26)
{0, {0,}}, // 0x1B (27)
{0, {0,}}, // 0x1C (28)
{0, {0,}}, // 0x1D (29)
{0, {0,}}, // 0x1E (30)
{0, {0,}}, // 0x1F (31)
{5, {0,}}, // space 0x20 (32)
{2, {0xfa, 0,}}, // ! 0x21 (33)
// #
// #
// #
// #
// #
//
// #
//
{5, {0x20, 0xc0, 0x20, 0xc0,}}, // " 0x22 (34)
// # #
// # #
// # #
//
//
//
//
//
{6, {0x28, 0xfe, 0x28, 0xfe, 0x28,}}, // # 0x23 (35)
// # #
// # #
// #####
// # #
// #####
// # #
// # #
//
{4, {0x64, 0xfe, 0x4c,}}, // $
// #
// ###
// ##
// #
// ##
// ###
// #
//
{6, {0x44, 0xa8, 0x54, 0x2a, 0x44,}}, // %
// #
// # # #
// # #
// #
// # #
// # # #
// #
//
{6, {0x4c, 0xb2, 0x4a, 0x04, 0x0a,}}, // &
// #
// # #
// #
// #
// # # #
// # #
// ## #
//
{3, {0x20, 0xc0,}}, // '
// #
// #
// #
//
//
//
//
//
{4, {0x38, 0x44, 0x82,}}, // (
{4, {0x82, 0x44, 0x38,}}, // )
{6, {0x54, 0x38, 0xfe, 0x38, 0x54,}}, // *
{6, {0x10, 0x10, 0x7c, 0x10, 0x10,}}, // +
{3, {0x1, 0x6,}}, // ,
//
//
//
//
//
// #
// #
// #
{5, {0x10, 0x10, 0x10, 0x10,}}, // -
//
//
//
// ####
//
//
//
//
{2, {0x2,}}, // .
//
//
//
//
//
//
// #
//
{6, {0x2, 0xc, 0x10, 0x60, 0x80,}}, // /
// #
// #
// #
// #
// #
// #
// #
//
{5, {0x7c, 0x82, 0x82, 0x7c,}}, // 0
{4, {0x42, 0xfe, 0x2,}}, // 1
{5, {0x46, 0x8a, 0x92, 0x62,}}, // 2
{5, {0x44, 0x92, 0x92, 0x6c,}}, // 3
{6, {0x18, 0x28, 0x48, 0xfe, 0x8,}}, // 4
{5, {0xf4, 0x92, 0x92, 0x1c,}}, // 5
{5, {0x7c, 0x92, 0x92, 0x0c,}}, // 6
{5, {0x86, 0x88, 0x90, 0xe0,}}, // 7
{5, {0x6c, 0x92, 0x92, 0x6c,}}, // 8
{5, {0x62, 0x92, 0x92, 0x7c,}}, // 9
{2, {0x24,}}, // :
{3, {1, 0x16,}}, // ;
{5, {0x10, 0x28, 0x44, 0x82,}}, // <
{5, {0x28, 0x28, 0x28, 0x28,}}, // =
{5, {0x82, 0x44, 0x28, 0x10,}}, // >
{5, {0x40, 0x8a, 0x90, 0x60,}}, // ?
{6, {0x3c, 0x42, 0x9a, 0xaa, 0x7a,}}, // @
{6, {0x3e, 0x48, 0x88, 0x48, 0x3e,}}, // A
{6, {0xfe, 0x92, 0x92, 0x92, 0x6c,}}, // B
{6, {0x7c, 0x82, 0x82, 0x82, 0x44,}}, // C
{6, {0xfe, 0x82, 0x82, 0x82, 0x7c,}}, // D
{6, {0xfe, 0x92, 0x92, 0x92, 0x82,}}, // E
{6, {0xfe, 0x90, 0x90, 0x90, 0x80,}}, // F
{6, {0x7c, 0x82, 0x82, 0x92, 0x9c,}}, // G
{6, {0xfe, 0x10, 0x10, 0x10, 0xfe,}}, // H
{4, {0x82, 0xfe, 0x82,}}, // I
{6, {4, 2, 0x82, 0xfc, 0x80}}, // J
{6, {0xfe, 0x10, 0x28, 0x44, 0x82,}}, // K
{5, {0xfe, 2, 2, 2,}}, // L
{6, {0xfe, 0x40, 0x20, 0x40, 0xfe,}}, // M
{6, {0xfe, 0x40, 0x20, 0x10, 0xfe,}}, // N
{6, {0x7c, 0x82, 0x82, 0x82, 0x7c,}}, // O
{6, {0xfe, 0x90, 0x90, 0x90, 0x60,}}, // P
{6, {0x7c, 0x82, 0x86, 0x82, 0x7d,}}, // Q
{6, {0xfe, 0x90, 0x98, 0x94, 0x62,}}, // R
{6, {0x64, 0x92, 0x92, 0x92, 0x4c,}}, // S
{6, {0x80, 0x80, 0xfe, 0x80, 0x80,}}, // T
{6, {0xfc, 2, 2, 2, 0xfc,}}, // U
{6, {0xf8, 4, 2, 4, 0xf8,}}, // V
{6, {0xfc, 2, 0x3c, 2, 0xfc,}}, // W
{6, {0xc6, 0x28, 0x10, 0x28, 0xc6,}}, // X
{6, {0xc0, 0x20, 0x1e, 0x20, 0xc0,}}, // Y
{6, {0x86, 0x8a, 0x92, 0xa2, 0xc2,}}, // Z
{4, {0xfe, 0x82, 0x82,}}, // [
{6, {0x80, 0x60, 0x10, 0xc, 0x2,}}, // '\'
// #
// #
// #
// #
// #
// #
// #
//
{4, {0x82, 0x82, 0xfe,}}, // ]
{6, {0x20, 0x40, 0x80, 0x40, 0x20,}}, // ^
{6, {2, 2, 2, 2, 2, 2,}}, // _
{4, {0x80, 0x40, 0x20,}}, // `
// #
// #
// #
//
//
//
//
//
{6, {4, 0x2a, 0x2a, 0x1c, 2,}}, // a
//
//
// ##
// #
// ###
// # #
// ## #
//
{5, {0xfe, 0x22, 0x22, 0x1c,}}, // b
// #
// #
// ###
// # #
// # #
// # #
// ###
//
{5, {0x1c, 0x22, 0x22, 0x22,}}, // c
//
//
// ###
// #
// #
// #
// ###
//
{5, {0x1c, 0x22, 0x22, 0xfe,}}, // d
// #
// #
// ###
// # #
// # #
// # #
// ###
//
{5, {0x1c, 0x2a, 0x2a, 0x12,}}, // e
//
//
// ##
// # #
// ###
// #
// ###
//
{5, {0x20, 0x7e, 0xa0, 0xa0,}}, // f
// ##
// #
// ####
// #
// #
// #
// #
//
{5, {0x19, 0x25, 0x25, 0x3e,}}, // g
//
//
// ###
// # #
// # #
// ###
// #
// ###
{5, {0xfe, 0x10, 0x20, 0x1e,}}, // h
// #
// #
// # #
// ## #
// # #
// # #
// # #
//
{4, {0x22, 0xbe, 2}}, // i
// #
//
// ##
// #
// #
// #
// ###
//
{4, {1, 0x21, 0xbe,}}, // j
// #
//
// ##
// #
// #
// #
// #
// ##
{5, {0xfe, 8, 0x14, 0x22,}}, // k
// #
// #
// # #
// # #
// ##
// # #
// # #
//
{4, {0x82, 0xfe, 2, }}, // l
// ##
// #
// #
// #
// #
// #
// ###
//
{6, {0x3e, 0x10, 0x3e, 0x10, 0x3e,}}, // m
//
//
// # # #
// #####
// # # #
// # # #
// # # #
//
{5, {0x3e, 0x10, 0x20, 0x1e,}}, // n
//
//
// # #
// ## #
// # #
// # #
// # #
//
{5, {0x1c, 0x22, 0x22, 0x1c,}}, // o
//
//
// ##
// # #
// # #
// # #
// ##
//
{5, {0x3f, 0x24, 0x24, 0x18,}}, // p
//
//
// ###
// # #
// # #
// ###
// #
// #
{5, {0x18, 0x24, 0x24, 0x3f,}}, // q
{5, {0x3e, 0x10, 0x20, 0x20,}}, // r
//
//
// # ##
// ##
// #
// #
// #
//
{5, {0x12, 0x2a, 0x2a, 0x24,}}, // s
{5, {0x20, 0xfc, 0x22, 0x22,}}, // t
{5, {0x3c, 2, 4, 0x3e,}}, // u
//
//
// # #
// # #
// # #
// # ##
// # #
//
{6, {0x38, 4, 2, 4, 0x38,}}, // v
//
//
// # #
// # #
// # #
// # #
// #
//
{6, {0x3c, 2, 0x1c, 2, 0x3c,}}, // w
//
//
// # #
// # # #
// # # #
// # # #
// # #
//
{6, {0x22, 0x14, 8, 0x14, 0x22,}}, // x
//
//
// # #
// # #
// #
// # #
// # #
//
{5, {0x39, 5, 5, 0x3e,}}, // y
//
//
// # #
// # #
// # #
// ###
// #
// ###
{6, {0x22, 0x26, 0x2a, 0x32, 0x22}}, // z
//
//
// #####
// #
// #
// #
// #####
//
{5, {0x10, 0x6c, 0x82, 0x82,}}, // {
{2, {0xfe,}}, // |
{5, {0x82, 0x82, 0x6c, 0x10,}}, // }
{7, {8, 0x10, 0x10, 8, 8, 0x10,}}, // ~
{7, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff,}}, // 0x7f (127)
{7, {0x28, 0x38, 0x6c, 0xaa, 0xaa, 0x82,}}, // 0x80 (128)
// ###
// #
// #####
// #
// #####
// #
// ###
//
{0, {0,}}, // 0x81
{0, {0,}}, // 0x82
{0, {0,}}, // 0x83
{0, {0,}}, // 0x84
{0, {0,}}, // 0x85
{0, {0,}}, // 0x86
{0, {0,}}, // 0x87
{0, {0,}}, // 0x88
{0, {0,}}, // 0x89
{0, {0,}}, // 0x8A
{0, {0,}}, // 0x8B
{0, {0,}}, // 0x8C
{0, {0,}}, // 0x8D
{0, {0,}}, // 0x8E
{0, {0,}}, // 0x8F
{0, {0,}}, // 0x90
{0, {0,}}, // 0x91
{0, {0,}}, // 0x92
{0, {0,}}, // 0x93
{0, {0,}}, // 0x94
{0, {0,}}, // 0x95
{0, {0,}}, // 0x96
{0, {0,}}, // 0x97
{0, {0,}}, // 0x98
{0, {0,}}, // 0x99
{0, {0,}}, // 0x9A
{0, {0,}}, // 0x9B
{0, {0,}}, // 0x9C
{0, {0,}}, // 0x9D
{0, {0,}}, // 0x9E
{0, {0,}}, // 0x9F
{0, {0,}}, // 0xA0 (160)
{0, {0,}}, // 0xA1
{0, {0,}}, // 0xA2
{0, {0,}}, // 0xA3
{0, {0,}}, // 0xA4
{0, {0,}}, // 0xA5
{0, {0,}}, // 0xA6
{0, {0,}}, // 0xA7
{0, {0,}}, // 0xA8
{0, {0,}}, // 0xA9
{0, {0,}}, // 0xAA
{6, {0x10, 0x28, 0x54, 0x28, 0x44,}}, // « 0xAB (171)
//
// # #
// # #
// # #
// # #
// # #
//
//
{0, {0,}}, // 0xAC (172)
{0, {0,}}, // 0xAD (173)
{0, {0,}}, // 0xAE (174)
{0, {0,}}, // 0xAF (175)
{0, {0,}}, // 0xB0 (176)
{0, {0,}}, // 0xB1
{0, {0,}}, // 0xB2
{0, {0,}}, // 0xB3
{0, {0,}}, // 0xB4
{0, {0,}}, // 0xB5
{0, {0,}}, // 0xB6
{0, {0,}}, // 0xB7
{0, {0,}}, // 0xB8
{0, {0,}}, // 0xB9
{0, {0,}}, // 0xBA
{6, {0x44, 0x28, 0x54, 0x28, 0x10,}}, // » 0xBB (187)
//
// # #
// # #
// # #
// # #
// # #
//
//
{0, {0,}}, // 0xBC
{0, {0,}}, // ½ 0xBD (189)
{0, {0,}}, // 0xBE
{0, {0,}}, // 0xBF
{5, {0x1e, 0xa8, 0x48, 0x28, 0x1e,}}, // À 0xC0 (192)
// #
// #
// # #
// # #
// #####
// # #
// # #
//
{6, {0x1e, 0x28, 0x48, 0xa8, 0x1e,}}, // Á
// #
// #
// # #
// # #
// #####
// # #
// # #
//
{6, {0x1e, 0x68, 0xc8, 0x68, 0x1e,}}, // Â
// #
// ###
// # #
// # #
// #####
// # #
// # #
//
{6, {0x1e, 0x68, 0xc8, 0x68, 0x1e,}}, // Ã
// # #
// ###
// # #
// # #
// #####
// # #
// # #
//
{6, {0x1e, 0xa8, 0x48, 0xa8, 0x1e,}}, // Ä
// # #
// #
// # #
// # #
// #####
// # #
// # #
//
{6, {0xe, 0x58, 0xa8, 0x58, 0xe,}}, // Å
// #
// # #
// #
// # #
// #####
// # #
// # #
//
{7, {0x3e, 0x50, 0x90, 0xfe, 0x92, 0x82}},// Æ
// ####
// # #
// # #
// #####
// # #
// # #
// # ###
//
{6, {0x7c, 0x82, 0x83, 0x82, 0x82,}}, // Ç
// ####
// #
// #
// #
// #
// #
// ####
// #
{6, {0x3e, 0xaa, 0x6a, 0x22, 0x22, }}, // È
// #
// #
// #####
// #
// ###
// #
// #####
//
{6, {0x3e, 0x2a, 0x6a, 0xa2, 0x22, }}, // É
// #
// #
// #####
// #
// ###
// #
// #####
//
{6, {0x3e, 0x6a, 0xaa, 0x6a, 0x22 }}, // Ê
// #
// # #
// #####
// #
// ###
// #
// #####
//
{6, {0x3e, 0xaa, 0x2a, 0xaa, 0x22}}, // Ë
// # #
//
// #####
// #
// ###
// #
// #####
//
{6, {0x22, 0xa2, 0x7e, 0x22, 0x22, }}, // Ì
// #
// #
// #####
// #
// #
// #
// #####
//
{6, {0x22, 0x22, 0x7e, 0xa2, 0x22, }}, // Í
// #
// #
// #####
// #
// #
// #
// #####
//
{6, {0x22, 0x62, 0xbe, 0x62, 0x22, }}, // Î
// #
// # #
// #####
// #
// #
// #
// #####
//
{6, {0x22, 0xa2, 0x3e, 0xa2, 0x22, }}, // Ï
// # #
//
// #####
// #
// #
// #
// #####
//
{6, {0x10, 0xfe, 0x92, 0x82, 0x7c, }}, // Ð
// ###
// # #
// # #
// ### #
// # #
// # #
// ###
//
{6, {0x3e, 0x50, 0x88, 0x44, 0xde, }}, // Ñ
// # #
// # #
// # #
// ## #
// # # #
// # ##
// # #
//
{6, {0x1c, 0xa2, 0x62, 0x22, 0x1c, }}, // Ò
// #
// #
// ###
// # #
// # #
// # #
// ###
//
{6, {0x1c, 0x22, 0x62, 0xa2, 0x1c, }}, // Ó
// #
// #
// ###
// # #
// # #
// # #
// ###
//
{6, {0x1c, 0x62, 0xa2, 0x62, 0x1c, }}, // Ô
// #
// # #
// ###
// # #
// # #
// # #
// ###
//
{6, {0x1c, 0x62, 0xa2, 0x62, 0x9c, }}, // Õ
// # #
// # #
// ###
// # #
// # #
// # #
// ###
//
{6, {0x1c, 0xa2, 0x22, 0xa2, 0x1c, }}, // Ö
// # #
//
// ###
// # #
// # #
// # #
// ###
//
{4, {0, 0x18, 0x18,}}, // �
{6, {0x7e, 0x8a, 0x92, 0xa2, 0xfc, }}, // Ø
// ####
// # #
// # ##
// # # #
// ## #
// # #
// ####
//
{6, {0x3c, 0x82, 0x42, 0x2, 0x3c, }}, // Ù
// #
// #
// # #
// # #
// # #
// # #
// ###
//
{6, {0x3c, 0x2, 0x42, 0x82, 0x3c, }}, // Ú
// #
// #
// # #
// # #
// # #
// # #
// ###
//
{6, {0x3c, 0x42, 0x82, 0x42, 0x3c, }}, // Û
// #
// # #
// # #
// # #
// # #
// # #
// ###
//
{6, {0x3c, 0x82, 0x2, 0x82, 0x3c, }}, // Ü
// # #
//
// # #
// # #
// # #
// # #
// ###
//
{6, {0x3, 0x88, 0x46, 0x8, 0x3, }}, // Ý
// #
// #
// # #
// # #
// # #
// #
// #
//
{4, {0, 0x18, 0x18,}}, // Þ
{4, {0, 0x18, 0x18,}}, // ß
{6, {0x4, 0xaa, 0x6a, 0x1c, 0x2,}}, // à
// #
// #
// ##
// #
// ###
// # #
// ## #
//
{6, {0x4, 0x2a, 0x6a, 0x9c, 0x2,}}, // á
// #
// #
// ##
// #
// ###
// # #
// ## #
//
{6, {0x4, 0x6a, 0xaa, 0x5c, 0x2,}}, // â
// #
// # #
// ##
// #
// ###
// # #
// ## #
//
{6, {0x4, 0x6a, 0xaa, 0x5c, 0x82,}}, // ã
// # #
// # #
// ##
// #
// ###
// # #
// ## #
//
{6, {0x4, 0xaa, 0x2a, 0x9c, 0x2}}, // ä
// # #
//
// ##
// #
// ###
// # #
// ## #
//
{6, {0x4, 0x6a, 0xaa, 0x5c, 0x2,}}, // å
// #
// # #
// ##
// #
// ###
// # #
// ## #
//
{7, {0x24, 0x2a, 0x1e, 0x2a, 0x2a, 0x10,}},// æ
//
//
// ## ##
// # #
// ####
// # #
// ####
//
{5, {0x1c, 0x22, 0x23, 0x22,}}, // ç
//
//
// ###
// #
// #
// #
// ###
// #
{5, {0x1c, 0xaa, 0x6a, 0x10,}}, // è
// #
// #
// ##
// # #
// ###
// #
// ##
//
{5, {0x1c, 0x6a, 0xaa, 0x10,}}, // é
// #
// #
// ##
// # #
// ###
// #
// ##
//
{5, {0x1c, 0x6a, 0xaa, 0x50,}}, // ê
// #
// # #
// ##
// # #
// ###
// #
// ##
//
{5, {0x1c, 0xaa, 0x2a, 0x90,}}, // ë
// # #
//
// ##
// # #
// ###
// #
// ##
//
{4, {0xa2, 0x7e, 0x2,}}, // ì
// #
// #
// ##
// #
// #
// #
// ###
//
{4, {0x22, 0x7e, 0x82,}}, // í
// #
// #
// ##
// #
// #
// #
// ###
//
{4, {0x62, 0xde, 0x42,}}, // î
// #
// # #
// ##
// #
// #
// #
// ###
//
{4, {0xa2, 0x3e, 0x82,}}, // ï
// # #
//
// ##
// #
// #
// #
// ###
//
{5, {0x5c, 0xa2, 0x62, 0x9c,}}, // �
// # #
// # #
// ##
// # #
// # #
// # #
// ##
//
{5, {0x7e, 0x90, 0x60, 0x9e,}}, // ñ
// # #
// # #
// # #
// ## #
// # #
// # #
// # #
//
{5, {0x1c, 0xa2, 0x62, 0x1c,}}, // ò
// #
// #
// ##
// # #
// # #
// # #
// ##
//
{5, {0x1c, 0x62, 0xa2, 0x1c,}}, // ó
// #
// #
// ##
// # #
// # #
// # #
// ##
//
{5, {0x5c, 0xa2, 0x62, 0x1c,}}, // ô
// #
// # #
// ##
// # #
// # #
// # #
// ##
//
{5, {0x5c, 0xa2, 0x62, 0x9c,}}, // õ
// # #
// # #
// ##
// # #
// # #
// # #
// ##
//
{5, {0x1c, 0xa2, 0x22, 0x9c,}}, // ö
// # #
//
// ##
// # #
// # #
// # #
// ##
//
{6, {0x10, 0x10, 0x38, 0x10, 0x10,}}, // ÷
//
//
// #
// #####
// #
//
//
//
{5, {0,}}, // �
{5, {0x3c, 0x82, 0x44, 0x3e,}}, // ù
// #
// #
// # #
// # #
// # #
// # ##
// # #
//
{5, {0x3c, 0x42, 0x84, 0x3e,}}, // ú
// #
// #
// # #
// # #
// # #
// # ##
// # #
//
{5, {0x3c, 0x42, 0x84, 0x7e,}}, // û
// #
// # #
// # #
// # #
// # #
// # ##
// # #
//
{5, {0xbc, 0x2, 0x4, 0xbe,}}, // ü
// # #
//
// # #
// # #
// # #
// # ##
// # #
//
{5, {0x39, 0x45, 0x85, 0x3e,}}, // ý
// #
// #
// # #
// # #
// # #
// ###
// #
// ###
{4, {0, 0x18, 0x18,}}, // þ
{5, {0xb9, 0x5, 0x5, 0xbe,}}, // ÿ
// # #
//
// # #
// # #
// # #
// ###
// #
// ###
};
const int g_FontBitmapSize PROGMEM = sizeof(g_FontBitmap)/sizeof(LEDMXFONT_BITMAP);
| bsd-3-clause |
ecoal95/angle | src/libANGLE/ResourceManager_unittest.cpp | 1 | 1959 | //
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Unit tests for ResourceManager.
//
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "libANGLE/ResourceManager.h"
#include "tests/angle_unittests_utils.h"
using namespace rx;
using namespace gl;
using ::testing::_;
namespace
{
class ResourceManagerTest : public testing::Test
{
protected:
void SetUp() override
{
mTextureManager = new TextureManager();
mBufferManager = new BufferManager();
mRenderbuffermanager = new RenderbufferManager();
}
void TearDown() override
{
mTextureManager->release(nullptr);
mBufferManager->release(nullptr);
mRenderbuffermanager->release(nullptr);
}
MockGLFactory mMockFactory;
TextureManager *mTextureManager;
BufferManager *mBufferManager;
RenderbufferManager *mRenderbuffermanager;
};
TEST_F(ResourceManagerTest, ReallocateBoundTexture)
{
EXPECT_CALL(mMockFactory, createTexture(_)).Times(1).RetiresOnSaturation();
mTextureManager->checkTextureAllocation(&mMockFactory, 1, GL_TEXTURE_2D);
GLuint newTexture = mTextureManager->createTexture();
EXPECT_NE(1u, newTexture);
}
TEST_F(ResourceManagerTest, ReallocateBoundBuffer)
{
EXPECT_CALL(mMockFactory, createBuffer(_)).Times(1).RetiresOnSaturation();
mBufferManager->checkBufferAllocation(&mMockFactory, 1);
GLuint newBuffer = mBufferManager->createBuffer();
EXPECT_NE(1u, newBuffer);
}
TEST_F(ResourceManagerTest, ReallocateBoundRenderbuffer)
{
EXPECT_CALL(mMockFactory, createRenderbuffer()).Times(1).RetiresOnSaturation();
mRenderbuffermanager->checkRenderbufferAllocation(&mMockFactory, 1);
GLuint newRenderbuffer = mRenderbuffermanager->createRenderbuffer();
EXPECT_NE(1u, newRenderbuffer);
}
} // anonymous namespace
| bsd-3-clause |
scpeters/chrono | src/unit_COSIMULATION/ChSocket.cpp | 1 | 45558 | #include "ChSocket.h"
#include "ChExceptionSocket.h"
using namespace std;
using namespace chrono;
using namespace chrono::cosimul;
const int MSG_HEADER_LEN = 6;
ChSocket::ChSocket(int pNumber)
{
portNumber = pNumber;
blocking = 1;
try
{
if ( (socketId=socket(AF_INET,SOCK_STREAM,0)) == -1)
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "";
detectErrorOpenWinSocket(&errorCode,errorMsg);
ChExceptionSocket* openWinSocketException = new ChExceptionSocket(errorCode,errorMsg);
throw openWinSocketException;
#endif
#ifdef UNIX
ChExceptionSocket* openUnixSocketException = new ChExceptionSocket(0,"unix: error getting host by name");
throw openUnixSocketException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
/*
set the initial address of client that shall be communicated with to
any address as long as they are using the same port number.
The clientAddr structure is used in the future for storing the actual
address of client applications with which communication is going
to start
*/
clientAddr.sin_family = AF_INET;
clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);
clientAddr.sin_port = htons(portNumber);
}
ChSocket::~ChSocket()
{
#ifdef WINDOWS_XP
closesocket(socketId);
#else
close(socketId);
#endif
}
void ChSocket::setDebug(int debugToggle)
{
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_DEBUG,(char *)&debugToggle,sizeof(debugToggle)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "DEBUG option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setReuseAddr(int reuseToggle)
{
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_REUSEADDR,(char *)&reuseToggle,sizeof(reuseToggle)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "REUSEADDR option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setKeepAlive(int aliveToggle)
{
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_KEEPALIVE,(char *)&aliveToggle,sizeof(aliveToggle)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "ALIVE option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setLingerSeconds(int seconds)
{
struct linger lingerOption;
if ( seconds > 0 )
{
lingerOption.l_linger = seconds;
lingerOption.l_onoff = 1;
}
else lingerOption.l_onoff = 0;
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_LINGER,(char *)&lingerOption,sizeof(struct linger)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "LINGER option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setLingerOnOff(bool lingerOn)
{
struct linger lingerOption;
if ( lingerOn ) lingerOption.l_onoff = 1;
else lingerOption.l_onoff = 0;
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_LINGER,(char *)&lingerOption,sizeof(struct linger)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "LINGER option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setSendBufSize(int sendBufSize)
{
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_SNDBUF,(char *)&sendBufSize,sizeof(sendBufSize)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "SENDBUFSIZE option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setReceiveBufSize(int receiveBufSize)
{
try
{
if ( setsockopt(socketId,SOL_SOCKET,SO_RCVBUF,(char *)&receiveBufSize,sizeof(receiveBufSize)) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "RCVBUF option:";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
void ChSocket::setSocketBlocking(int blockingToggle)
{
if (blockingToggle)
{
if (getSocketBlocking()) return;
else blocking = 1;
}
else
{
if (!getSocketBlocking()) return;
else blocking = 0;
}
try
{
#ifdef WINDOWS_XP
if (ioctlsocket(socketId,FIONBIO,(unsigned long *)blocking) == -1)
{
int errorCode;
string errorMsg = "Blocking option: ";
detectErrorSetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
}
#endif
#ifdef UNIX
if (ioctl(socketId,FIONBIO,(char *)&blocking) == -1)
{
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
}
#endif
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
int ChSocket::getDebug()
{
int myOption;
int myOptionLen = sizeof(myOption);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_DEBUG,(char *)&myOption,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get DEBUG option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return myOption;
}
int ChSocket::getReuseAddr()
{
int myOption;
int myOptionLen = sizeof(myOption);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_REUSEADDR,(char *)&myOption,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get REUSEADDR option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return myOption;
}
int ChSocket::getKeepAlive()
{
int myOption;
int myOptionLen = sizeof(myOption);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_KEEPALIVE,(char *)&myOption,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get KEEPALIVE option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return myOption;
}
int ChSocket::getLingerSeconds()
{
struct linger lingerOption;
int myOptionLen = sizeof(struct linger);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_LINGER,(char *)&lingerOption,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get LINER option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return lingerOption.l_linger;
}
bool ChSocket::getLingerOnOff()
{
struct linger lingerOption;
int myOptionLen = sizeof(struct linger);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_LINGER,(char *)&lingerOption,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get LINER option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
if ( lingerOption.l_onoff == 1 ) return true;
else return false;
}
int ChSocket::getSendBufSize()
{
int sendBuf;
int myOptionLen = sizeof(sendBuf);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_SNDBUF,(char *)&sendBuf,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get SNDBUF option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return sendBuf;
}
int ChSocket::getReceiveBufSize()
{
int rcvBuf;
int myOptionLen = sizeof(rcvBuf);
try
{
if ( getsockopt(socketId,SOL_SOCKET,SO_RCVBUF,(char *)&rcvBuf,&myOptionLen) == -1 )
{
#ifdef WINDOWS_XP
int errorCode;
string errorMsg = "get RCVBUF option: ";
detectErrorGetSocketOption(&errorCode,errorMsg);
ChExceptionSocket* socketOptionException = new ChExceptionSocket(errorCode,errorMsg);
throw socketOptionException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketOptionException = new ChExceptionSocket(0,"unix: error getting host by name");
throw unixSocketOptionException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return rcvBuf;
}
#ifdef WINDOWS_XP
void ChSocket::detectErrorOpenWinSocket(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("Successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem or the associated service provider has failed.");
else if ( *errCode == WSAEAFNOSUPPORT )
errMsg.append("The specified address family is not supported.");
else if ( *errCode == WSAEINPROGRESS )
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.");
else if ( *errCode == WSAEMFILE )
errMsg.append("No more socket descriptors are available.");
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available. The socket cannot be created.");
else if ( *errCode == WSAEPROTONOSUPPORT )
errMsg.append("The specified protocol is not supported.");
else if ( *errCode == WSAEPROTOTYPE )
errMsg.append("The specified protocol is the wrong type for this socket.");
else if ( *errCode == WSAESOCKTNOSUPPORT )
errMsg.append("The specified socket type is not supported in this address family.");
else errMsg.append("unknown problems!");
}
void ChSocket::detectErrorSetSocketOption(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEFAULT )
errMsg.append("optval is not in a valid part of the process address space or optlen parameter is too small.");
else if ( *errCode == WSAEINPROGRESS )
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.");
else if ( *errCode == WSAEINVAL )
errMsg.append("level is not valid, or the information in optval is not valid.");
else if ( *errCode == WSAENETRESET )
errMsg.append("Connection has timed out when SO_KEEPALIVE is set.");
else if ( *errCode == WSAENOPROTOOPT )
errMsg.append("The option is unknown or unsupported for the specified provider or socket (see SO_GROUP_PRIORITY limitations).");
else if ( *errCode == WSAENOTCONN )
errMsg.append("Connection has been reset when SO_KEEPALIVE is set.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else errMsg.append("unknown problem!");
}
void ChSocket::detectErrorGetSocketOption(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEFAULT )
errMsg.append("One of the optval or the optlen parameters is not a valid part of the user address space, or the optlen parameter is too small.");
else if ( *errCode == WSAEINPROGRESS )
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.");
else if ( *errCode == WSAEINVAL )
errMsg.append("The level parameter is unknown or invalid.");
else if ( *errCode == WSAENOPROTOOPT )
errMsg.append("The option is unknown or unsupported by the indicated protocol family.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else errMsg.append("unknown problems!");
}
#endif
ostream& operator<<(ostream& io,ChSocket& s)
{
string flagStr = "";
io << "--------------- Summary of socket settings -------------------" << endl;
io << " Socket Id: " << s.getSocketId() << endl;
io << " port #: " << s.getPortNumber() << endl;
io << " debug: " << (flagStr = s.getDebug()? "true":"false" ) << endl;
io << " reuse addr: " << (flagStr = s.getReuseAddr()? "true":"false" ) << endl;
io << " keep alive: " << (flagStr = s.getKeepAlive()? "true":"false" ) << endl;
io << " send buf size: " << s.getSendBufSize() << endl;
io << " recv bug size: " << s.getReceiveBufSize() << endl;
io << " blocking: " << (flagStr = s.getSocketBlocking()? "true":"false" ) << endl;
io << " linger on: " << (flagStr = s.getLingerOnOff()? "true":"false" ) << endl;
io << " linger seconds: " << s.getLingerSeconds() << endl;
io << "----------- End of Summary of socket settings ----------------" << endl;
return io;
}
void ChSocketTCP::bindSocket()
{
try
{
if (bind(socketId,(struct sockaddr *)&clientAddr,sizeof(struct sockaddr_in))==-1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling bind(): \n";
detectErrorBind(&errorCode,errorMsg);
ChExceptionSocket* socketBindException = new ChExceptionSocket(errorCode,errorMsg);
throw socketBindException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketBindException = new ChExceptionSocket(0,"unix: error calling bind()");
throw unixSocketBindException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
#ifdef WINDOWS_XP
void ChSocketTCP::detectErrorBind(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEADDRINUSE )
{
errMsg.append("A process on the machine is already bound to the same\n");
errMsg.append("fully-qualified address and the socket has not been marked\n");
errMsg.append("to allow address re-use with SO_REUSEADDR. For example,\n");
errMsg.append("IP address and port are bound in the af_inet case");
}
else if ( *errCode == WSAEADDRNOTAVAIL )
errMsg.append("The specified address is not a valid address for this machine.");
else if ( *errCode == WSAEFAULT )
{
errMsg.append("The name or the namelen parameter is not a valid part of\n");
errMsg.append("the user address space, the namelen parameter is too small,\n");
errMsg.append("the name parameter contains incorrect address format for the\n");
errMsg.append("associated address family, or the first two bytes of the memory\n");
errMsg.append("block specified by name does not match the address family\n");
errMsg.append("associated with the socket descriptor s.");
}
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n");
errMsg.append("service provider is still processing a callback function.");
}
else if ( *errCode == WSAEINVAL )
errMsg.append("The socket is already bound to an address. ");
else if ( *errCode == WSAENOBUFS )
errMsg.append("Not enough buffers available, too many connections.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else errMsg.append("unknown problems!");
}
void ChSocketTCP::detectErrorRecv(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEFAULT )
errMsg.append("The buf parameter is not completely contained in a valid part of the user address space.");
else if ( *errCode == WSAENOTCONN )
errMsg.append("The socket is not connected.");
else if ( *errCode == WSAEINTR )
errMsg.append("The (blocking) call was canceled through WSACancelBlockingCall.");
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n");
errMsg.append("service provider is still processing a callback function.");
}
else if ( *errCode == WSAENETRESET )
{
errMsg.append("The connection has been broken due to the keep-alive activity\n");
errMsg.append("detecting a failure while the operation was in progress.");
}
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAEOPNOTSUPP )
{
errMsg.append("MSG_OOB was specified, but the socket is not stream-style\n");
errMsg.append("such as type SOCK_STREAM, out-of-band data is not supported\n");
errMsg.append("in the communication domain associated with this socket, or\n");
errMsg.append("the socket is unidirectional and supports only send operations.");
}
else if ( *errCode == WSAESHUTDOWN )
{
errMsg.append("The socket has been shut down; it is not possible to recv on a\n");
errMsg.append("socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH.");
}
else if ( *errCode == WSAEWOULDBLOCK )
errMsg.append("The socket is marked as nonblocking and the receive operation would block.");
else if ( *errCode == WSAEMSGSIZE )
errMsg.append("The message was too large to fit into the specified buffer and was truncated.");
else if ( *errCode == WSAEINVAL )
{
errMsg.append("The socket has not been bound with bind, or an unknown flag\n");
errMsg.append("was specified, or MSG_OOB was specified for a socket with\n");
errMsg.append("SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative.");
}
else if ( *errCode == WSAECONNABORTED )
{
errMsg.append("The virtual circuit was terminated due to a time-out or\n");
errMsg.append("other failure. The application should close the socket as it is no longer usable.");
}
else if ( *errCode == WSAETIMEDOUT )
{
errMsg.append("The connection has been dropped because of a network\n");
errMsg.append("failure or because the peer system failed to respond.");
}
else if ( *errCode == WSAECONNRESET )
{
errMsg.append("The virtual circuit was reset by the remote side executing a\n");
errMsg.append("\"hard\" or \"abortive\" close. The application should close\n");
errMsg.append("the socket as it is no longer usable. On a UDP datagram socket\n");
errMsg.append("this error would indicate that a previous send operation\n");
errMsg.append("resulted in an ICMP \"Port Unreachable\" message.");
}
else errMsg.append("unknown problems!");
}
void ChSocketTCP::detectErrorConnect(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEADDRINUSE )
{
errMsg.append("The socket's local address is already in use and the socket\n");
errMsg.append("was not marked to allow address reuse with SO_REUSEADDR. This\n");
errMsg.append("error usually occurs when executing bind, but could be delayed\n");
errMsg.append("until this function if the bind was to a partially wild-card\n");
errMsg.append("address (involving ADDR_ANY) and if a specific address needs\n");
errMsg.append("to be committed at the time of this function.");
}
else if ( *errCode == WSAEINTR )
errMsg.append("The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall.");
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or\n");
errMsg.append("the service provider is still processing a callback function.");
}
else if ( *errCode == WSAEALREADY )
{
errMsg.append("A nonblocking connect call is in progress on the specified socket.\n");
errMsg.append("Note In order to preserve backward compatibility, this error is\n");
errMsg.append("reported as WSAEINVAL to Windows Sockets 1.1 applications that\n");
errMsg.append("link to either WINSOCK.DLL or WSOCK32.DLL.");
}
else if ( *errCode == WSAEADDRNOTAVAIL )
errMsg.append("The remote address is not a valid address (such as ADDR_ANY).");
else if ( *errCode == WSAEAFNOSUPPORT )
errMsg.append("Addresses in the specified family cannot be used with this socket.");
else if ( *errCode == WSAECONNREFUSED )
errMsg.append("The attempt to connect was forcefully rejected.");
else if ( *errCode == WSAEFAULT )
{
errMsg.append("The name or the namelen parameter is not a valid part of\n");
errMsg.append("the user address space, the namelen parameter is too small,\n");
errMsg.append("or the name parameter contains incorrect address format for\n");
errMsg.append("the associated address family.");
}
else if ( *errCode == WSAEINVAL )
{
errMsg.append("The parameter s is a listening socket, or the destination\n");
errMsg.append("address specified is not consistent with that of the constrained\n");
errMsg.append("group the socket belongs to.");
}
else if ( *errCode == WSAEISCONN )
errMsg.append("The socket is already connected (connection-oriented sockets only).");
else if ( *errCode == WSAENETUNREACH )
errMsg.append("The network cannot be reached from this host at this time.");
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available. The socket cannot be connected.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAETIMEDOUT )
errMsg.append("Attempt to connect timed out without establishing a connection.");
else if ( *errCode == WSAEWOULDBLOCK )
{
errMsg.append("The socket is marked as nonblocking and the connection\n");
errMsg.append("cannot be completed immediately.");
}
else if ( *errCode == WSAEACCES )
{
errMsg.append("Attempt to connect datagram socket to broadcast address failed\n");
errMsg.append("because setsockopt option SO_BROADCAST is not enabled.");
}
else errMsg.append("unknown problems!");
}
void ChSocketTCP::detectErrorAccept(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this FUNCTION.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEFAULT )
errMsg.append("The addrlen parameter is too small or addr is not a valid part of the user address space.");
else if ( *errCode == WSAEINTR )
errMsg.append("A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.");
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n");
errMsg.append("service provider is still processing a callback function.");
}
else if ( *errCode == WSAEINVAL )
errMsg.append("The listen function was not invoked prior to accept.");
else if ( *errCode == WSAEMFILE )
errMsg.append("The queue is nonempty upon entry to accept and there are no descriptors available.");
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAEOPNOTSUPP )
errMsg.append("The referenced socket is not a type that supports connection-oriented service.");
else if ( *errCode == WSAEWOULDBLOCK )
errMsg.append("The socket is marked as nonblocking and no connections are present to be accepted.");
else errMsg.append("unknown problems!");
}
void ChSocketTCP::detectErrorListen(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEADDRINUSE )
{
errMsg.append("The socket's local address is already in use and the socket was\n");
errMsg.append("not marked to allow address reuse with SO_REUSEADDR. This error\n");
errMsg.append("usually occurs during execution of the bind function, but could\n");
errMsg.append("be delayed until this function if the bind was to a partially\n");
errMsg.append("wild-card address (involving ADDR_ANY) and if a specific address\n");
errMsg.append("needs to be \"committed\" at the time of this function.");
}
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the service\n");
errMsg.append("provider is still processing a callback function.");
}
else if ( *errCode == WSAEINVAL )
errMsg.append("The socket has not been bound with bind.");
else if ( *errCode == WSAEISCONN )
errMsg.append("The socket is already connected.");
else if ( *errCode == WSAEMFILE )
errMsg.append("No more socket descriptors are available.");
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAEOPNOTSUPP )
errMsg.append("The referenced socket is not of a type that supports the listen operation.");
else errMsg.append("unknown problems!");
}
void ChSocketTCP::detectErrorSend(int* errCode,string& errMsg)
{
*errCode = WSAGetLastError();
if ( *errCode == WSANOTINITIALISED )
errMsg.append("A successful WSAStartup must occur before using this function.");
else if ( *errCode == WSAENETDOWN )
errMsg.append("The network subsystem has failed.");
else if ( *errCode == WSAEACCES )
{
errMsg.append("The requested address is a broadcast address,\n");
errMsg.append("but the appropriate flag was not set. Call setsockopt\n");
errMsg.append("with the SO_BROADCAST parameter to allow the use of the broadcast address.");
}
else if ( *errCode == WSAEINTR )
{
errMsg.append("A blocking Windows Sockets 1.1 call was canceled\n");
errMsg.append("through WSACancelBlockingCall.");
}
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress,\n");
errMsg.append("or the service provider is still processing a callback function.");
}
else if ( *errCode == WSAEFAULT )
{
errMsg.append("The buf parameter is not completely contained in a\n");
errMsg.append("valid part of the user address space.");
}
else if ( *errCode == WSAENETRESET )
{
errMsg.append("The connection has been broken due to the keep-alive\n");
errMsg.append("activity detecting a failure while the operation was in progress.");
}
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available.");
else if ( *errCode == WSAENOTCONN )
errMsg.append("The socket is not connected.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAEOPNOTSUPP )
{
errMsg.append("MSG_OOB was specified, but the socket is not stream-style\n");
errMsg.append("such as type SOCK_STREAM, out-of-band data is not supported\n");
errMsg.append("in the communication domain associated with this socket,\n");
errMsg.append("or the socket is unidirectional and supports only receive operations.");
}
else if ( *errCode == WSAESHUTDOWN )
{
errMsg.append("The socket has been shut down; it is not possible to send\n");
errMsg.append("on a socket after shutdown has been invoked with how set\n");
errMsg.append("to SD_SEND or SD_BOTH.");
}
else if ( *errCode == WSAEWOULDBLOCK )
errMsg.append("The socket is marked as nonblocking and the requested operation would block.\n");
else if ( *errCode == WSAEMSGSIZE )
{
errMsg.append("The socket is message oriented, and the message is larger\n");
errMsg.append("than the maximum supported by the underlying transport.");
}
else if ( *errCode == WSAEHOSTUNREACH )
errMsg.append("The remote host cannot be reached from this host at this time.");
else if ( *errCode == WSAEINVAL )
{
errMsg.append("The socket has not been bound with bind, or an unknown flag\n");
errMsg.append("was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.");
}
else if ( *errCode == WSAECONNABORTED )
{
errMsg.append("The virtual circuit was terminated due to a time-out or \n");
errMsg.append("other failure. The application should close the socket as it is no longer usable.");
}
else if ( *errCode == WSAECONNRESET )
{
errMsg.append("The virtual circuit was reset by the remote side executing a \"hard\" \n");
errMsg.append("or \"abortive\" close. For UPD sockets, the remote host was unable to\n");
errMsg.append("deliver a previously sent UDP datagram and responded with a\n");
errMsg.append("\"Port Unreachable\" ICMP packet. The application should close\n");
errMsg.append("the socket as it is no longer usable.");
}
else if ( *errCode == WSAETIMEDOUT )
{
errMsg.append("The connection has been dropped, because of a network failure\n");
errMsg.append("or because the system on the other end went down without notice.");
}
else errMsg.append("unknown problems!");
}
#endif
void ChSocketTCP::connectToServer(string& serverNameOrAddr,hostType hType)
{
/*
when this method is called, a client socket has been built already,
so we have the socketId and portNumber ready.
a ChHostInfo instance is created, no matter how the server's name is
given (such as www.yuchen.net) or the server's address is given (such
as 169.56.32.35), we can use this ChHostInfo instance to get the
IP address of the server
*/
ChHostInfo serverInfo(serverNameOrAddr,hType);
// Store the IP address and socket port number
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(serverInfo.getHostIPAddress());
serverAddress.sin_port = htons(portNumber);
// Connect to the given address
try
{
if (connect(socketId,(struct sockaddr *)&serverAddress,sizeof(serverAddress)) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling connect():\n";
detectErrorConnect(&errorCode,errorMsg);
ChExceptionSocket* socketConnectException = new ChExceptionSocket(errorCode,errorMsg);
throw socketConnectException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketConnectException = new ChExceptionSocket(0,"unix: error calling connect()");
throw unixSocketConnectException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
ChSocketTCP* ChSocketTCP::acceptClient(string& clientHost)
{
int newSocket; // the new socket file descriptor returned by the accept systme call
// the length of the client's address
int clientAddressLen = sizeof(struct sockaddr_in);
struct sockaddr_in clientAddress; // Address of the client that sent data
// Accepts a new client connection and stores its socket file descriptor
try
{
if ((newSocket = accept(socketId, (struct sockaddr *)&clientAddress,&clientAddressLen)) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling accept(): \n";
detectErrorAccept(&errorCode,errorMsg);
ChExceptionSocket* socketAcceptException = new ChExceptionSocket(errorCode,errorMsg);
throw socketAcceptException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketAcceptException = new ChExceptionSocket(0,"unix: error calling accept()");
throw unixSocketAcceptException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
return NULL;
}
// Get the host name given the address
char *sAddress = inet_ntoa((struct in_addr)clientAddress.sin_addr);
ChHostInfo clientInfo(string(sAddress),ADDRESS);
char* hostName = clientInfo.getHostName();
clientHost += string(hostName);
// Create and return the new ChSocketTCP object
ChSocketTCP* retSocket = new ChSocketTCP();
retSocket->setSocketId(newSocket);
return retSocket;
}
void ChSocketTCP::listenToClient(int totalNumPorts)
{
try
{
if (listen(socketId,totalNumPorts) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling listen():\n";
detectErrorListen(&errorCode,errorMsg);
ChExceptionSocket* socketListenException = new ChExceptionSocket(errorCode,errorMsg);
throw socketListenException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketListenException = new ChExceptionSocket(0,"unix: error calling listen()");
throw unixSocketListenException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
}
/*
int ChSocketTCP::sendMessage(string& message)
{
int numBytes; // the number of bytes sent
char msgLength[MSG_HEADER_LEN+1];
sprintf(msgLength,"%6d",message.size());
string sendMsg = string(msgLength);
sendMsg += message;
// Sends the message to the connected host
try
{
if (numBytes = send(socketId,sendMsg.c_str(),sendMsg.size(),0) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling send():\n";
detectErrorSend(&errorCode,errorMsg);
ChExceptionSocket* socketSendException = new ChExceptionSocket(errorCode,errorMsg);
throw socketSendException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketSendException = new ChExceptionSocket(0,"unix: error calling send()");
throw unixSocketSendException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return numBytes;
}
*/
int ChSocketTCP::sendMessage(string& message)
{
int numBytes; // the number of bytes sent
/*
for each message to be sent, add a header which shows how long this message
is. This header, regardless how long the real message is, will always be
of the length MSG_HEADER_LEN.
*/
char msgLength[MSG_HEADER_LEN+1];
sprintf(msgLength,"%6d",message.size());
string sendMsg = string(msgLength);
sendMsg += message;
// Sends the message to the connected host
try
{
if (numBytes = send(socketId,sendMsg.c_str(),sendMsg.size(),0) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling send():\n";
detectErrorSend(&errorCode,errorMsg);
ChExceptionSocket* socketSendException = new ChExceptionSocket(errorCode,errorMsg);
throw socketSendException;
#endif
#ifdef UNIX
ChExceptionSocket* unixSocketSendException = new ChExceptionSocket(0,"unix: error calling send()");
throw unixSocketSendException;
#endif
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return numBytes;
}
#ifdef WINDOWS_XP
/*
int ChSocketTCP::XPrecieveMessage(string& message)
{
int numBytes = 0; // The number of bytes received
int currentSize = MSG_HEADER_LEN; // The number of bytes wanted to receive
int offsetSize = 0; // The number of bytes currently recieved
// retrieve the length of the message received
char msgLength[MSG_HEADER_LEN+1];
memset(msgLength,0,sizeof(msgLength));
try
{
while ( numBytes < currentSize )
{
numBytes = recv(socketId,msgLength+offsetSize,currentSize,MSG_PEEK);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
ChExceptionSocket* socketRecvException = new ChExceptionSocket(errorCode,errorMsg);
throw socketRecvException;
}
else if ( numBytes < currentSize )
{
offsetSize += numBytes;
currentSize -= numBytes;
}
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
// recieve the real message
currentSize = atoi(msgLength);
offsetSize = 0;
cout << "[RECV:message length] " << msgLength << endl;
winLog << "[RECV:message length] " << msgLength << endl;
try
{
while ( numBytes < currentSize )
{
numBytes = recv(socketId,(char*)(message.c_str())+offsetSize,currentSize,0);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
ChExceptionSocket* socketRecvException = new ChExceptionSocket(errorCode,errorMsg);
throw socketRecvException;
}
else if ( numBytes < currentSize )
{
offsetSize += numBytes;
currentSize -= numBytes;
}
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
cout << "[RECV:message] " << message << endl;
winLog << "[RECV:message] " << message << endl;
return atoi(msgLength);
}
*/
int ChSocketTCP::XPrecieveMessage(string& message)
{
int received = 0; // The number of bytes received
int msgSize = MAX_RECV_LEN; // The number of bytes wanted to receive
int numBytes = 0; // The number of bytes currently recieved
int totalRecvNum = 0;
bool headerFinished = false;
char charMsg[MAX_RECV_LEN+1];
char msgLength[MSG_HEADER_LEN+1];
memset(charMsg,0,sizeof(charMsg));
memset(msgLength,0,sizeof(msgLength));
try
{
while ( received < msgSize )
{
numBytes = recv(socketId,charMsg+received,1,0);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
ChExceptionSocket* socketRecvException = new ChExceptionSocket(errorCode,errorMsg);
throw socketRecvException;
}
if ( !headerFinished )
{
msgLength[received] = *(charMsg+received);
received ++;
if ( received == MSG_HEADER_LEN )
{
headerFinished = true;
received = 0;
memset(charMsg,0,sizeof(charMsg));
msgSize = atoi(msgLength);
}
}
else
received ++;
}
}
catch(ChExceptionSocket* excp)
{
if ( excp->getErrCode() == WSAECONNRESET )
{
cout << "!! your party has shut down the connection... \n";
//winLog << "!! your party has shut down the connection... \n";
return -99;
}
excp->response();
delete excp;
exit(1);
}
message.append(string(charMsg));
return msgSize;
}
#endif
int ChSocketTCP::receiveMessage(string& message)
{
int numBytes; // The number of bytes recieved
#ifdef WINDOWS_XP
return XPrecieveMessage(message);
#endif
// retrieve the length of the message received
char msgLength[MSG_HEADER_LEN+1];
memset(msgLength,0,sizeof(msgLength));
try
{
numBytes = recv(socketId,msgLength,MSG_HEADER_LEN,0);
if (numBytes == -1)
{
ChExceptionSocket* unixSocketRecvException = new ChExceptionSocket(0,"unix: error calling recv()");
throw unixSocketRecvException;
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
// receive the real message
try
{
numBytes = recv(socketId,(char*)(message.c_str()),atoi(msgLength),0);
if (numBytes == -1)
{
ChExceptionSocket* unixSocketRecvException = new ChExceptionSocket(0,"unix: error calling recv()");
throw unixSocketRecvException;
}
}
catch(ChExceptionSocket* excp)
{
excp->response();
delete excp;
exit(1);
}
return numBytes;
}
int ChSocketTCP::SendBuffer( std::vector<char>& source_buf)
{
int nbytes = source_buf.size();
char* data;
if (nbytes)
data = (char*)&(source_buf[0]); // stl vectors are assured to be sequential
else
data = ""; // stub, in case null length messages, stl vector has no [0] element address
int sentBytes = 0;
// Sends the message to the connected host
if (sentBytes = send(socketId,data,nbytes,0) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling send():\n";
detectErrorRecv(&errorCode,errorMsg);
throw ChExceptionSocket(errorCode,errorMsg);
#endif
#ifdef UNIX
throw ChExceptionSocket(0,"unix: error calling send()");
#endif
}
return sentBytes;
}
int ChSocketTCP::ReceiveBuffer(std::vector<char>& dest_buf,
int bsize
)
{
int nbytes = bsize;
dest_buf.resize(nbytes);
void* data;
if (nbytes)
data = (char*)&(dest_buf[0]); // stl vectors are assured to be sequential. // should not access directly std::vector data, but this is efficient!
else
data = (char*)""; // stub, in case null length messages, stl vector has no [0] element address
int receivedBytes = recv(socketId,(char*)data,nbytes,0);
if (receivedBytes == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
throw ChExceptionSocket(errorCode,errorMsg);
#endif
#ifdef UNIX
throw ChExceptionSocket(0,"Error calling recv() in buffer receive:");
#endif
}
return receivedBytes;
}
| bsd-3-clause |
iPlantCollaborativeOpenSource/irods-3.3.1-iplant | server/api/src/rsDataObjGet.c | 2 | 10221 | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* This is script-generated code (for the most part). */
/* See dataObjGet.h for a description of this API call.*/
#include "dataObjGet.h"
#include "rodsLog.h"
#include "dataGet.h"
#include "fileGet.h"
#include "dataObjOpen.h"
#include "rsGlobalExtern.h"
#include "rcGlobalExtern.h"
#include "rsApiHandler.h"
#include "objMetaOpr.h"
#include "physPath.h"
#include "specColl.h"
#include "subStructFileGet.h"
#include "getRemoteZoneResc.h"
int
rsDataObjGet (rsComm_t *rsComm, dataObjInp_t *dataObjInp,
portalOprOut_t **portalOprOut, bytesBuf_t *dataObjOutBBuf)
{
int status;
int remoteFlag;
rodsServerHost_t *rodsServerHost;
specCollCache_t *specCollCache = NULL;
resolveLinkedPath (rsComm, dataObjInp->objPath, &specCollCache,
&dataObjInp->condInput);
remoteFlag = getAndConnRemoteZone (rsComm, dataObjInp, &rodsServerHost,
REMOTE_OPEN);
if (remoteFlag < 0) {
return (remoteFlag);
} else if (remoteFlag == LOCAL_HOST) {
status = _rsDataObjGet (rsComm, dataObjInp, portalOprOut,
dataObjOutBBuf, BRANCH_MSG);
} else {
int l1descInx;
status = _rcDataObjGet (rodsServerHost->conn, dataObjInp, portalOprOut,
dataObjOutBBuf);
if (status < 0) {
return (status);
}
if (status == 0 ||
(dataObjOutBBuf != NULL && dataObjOutBBuf->len > 0)) {
/* data included in buf */
return status;
} else {
/* have to allocate a local l1descInx to keep track of things
* since the file is in remote zone. It sets remoteL1descInx,
* oprType = REMOTE_ZONE_OPR and remoteZoneHost so that
* rsComplete knows what to do */
l1descInx = allocAndSetL1descForZoneOpr (
(*portalOprOut)->l1descInx, dataObjInp, rodsServerHost, NULL);
if (l1descInx < 0) return l1descInx;
(*portalOprOut)->l1descInx = l1descInx;
return status;
}
}
return (status);
}
int
_rsDataObjGet (rsComm_t *rsComm, dataObjInp_t *dataObjInp,
portalOprOut_t **portalOprOut, bytesBuf_t *dataObjOutBBuf, int handlerFlag)
{
int status;
dataObjInfo_t *dataObjInfo;
int l1descInx;
char *chksumStr = NULL;
int retval;
openedDataObjInp_t dataObjCloseInp;
/* PHYOPEN_BY_SIZE ask it to check whether "dataInclude" should be done */
addKeyVal (&dataObjInp->condInput, PHYOPEN_BY_SIZE_KW, "");
l1descInx = _rsDataObjOpen (rsComm, dataObjInp);
if (l1descInx < 0)
return l1descInx;
L1desc[l1descInx].oprType = GET_OPR;
dataObjInfo = L1desc[l1descInx].dataObjInfo;
if (getStructFileType (dataObjInfo->specColl) >= 0 &&
L1desc[l1descInx].l3descInx > 0) {
/* l3descInx == 0 if included */
*portalOprOut = (portalOprOut_t *) malloc (sizeof (portalOprOut_t));
bzero (*portalOprOut, sizeof (portalOprOut_t));
(*portalOprOut)->l1descInx = l1descInx;
return l1descInx;
}
if (getValByKey (&dataObjInp->condInput, VERIFY_CHKSUM_KW) != NULL) {
if (strlen (dataObjInfo->chksum) > 0) {
/* a chksum already exists */
chksumStr = strdup (dataObjInfo->chksum);
} else {
status = dataObjChksumAndReg (rsComm, dataObjInfo, &chksumStr);
if (status < 0) {
return status;
}
rstrcpy (dataObjInfo->chksum, chksumStr, CHKSUM_LEN);
}
}
if (L1desc[l1descInx].l3descInx <= 2) {
/* no physical file was opened */
status = l3DataGetSingleBuf (rsComm, l1descInx, dataObjOutBBuf,
portalOprOut);
if (status >= 0) {
int status2;
/** since the object is read here, we apply post procesing RAJA
* Dec 2 2010 **/
status2 = applyRuleForPostProcForRead(rsComm, dataObjOutBBuf,
dataObjInp->objPath);
if (status2 >= 0) {
status = 0;
} else {
status = status2;
}
/** since the object is read here, we apply post procesing
* RAJA Dec 2 2010 **/
if (chksumStr != NULL) {
rstrcpy ((*portalOprOut)->chksum, chksumStr, CHKSUM_LEN);
free (chksumStr);
}
}
return (status);
}
status = preProcParaGet (rsComm, l1descInx, portalOprOut);
if (status < 0) {
memset (&dataObjCloseInp, 0, sizeof (dataObjCloseInp));
dataObjCloseInp.l1descInx = l1descInx;
rsDataObjClose (rsComm, &dataObjCloseInp);
if (chksumStr != NULL) {
free (chksumStr);
}
return (status);
}
status = l1descInx; /* means file not included */
if (chksumStr != NULL) {
rstrcpy ((*portalOprOut)->chksum, chksumStr, CHKSUM_LEN);
free (chksumStr);
}
/* return portalOprOut to the client and wait for the rcOprComplete
* call. That is when the parallel I/O is done */
retval = sendAndRecvBranchMsg (rsComm, rsComm->apiInx, status,
(void *) *portalOprOut, dataObjOutBBuf);
if (retval < 0) {
memset (&dataObjCloseInp, 0, sizeof (dataObjCloseInp));
dataObjCloseInp.l1descInx = l1descInx;
rsDataObjClose (rsComm, &dataObjCloseInp);
}
if (handlerFlag & INTERNAL_SVR_CALL) {
/* internal call. want to know the real status */
return (retval);
} else {
/* already send the client the status */
return (SYS_NO_HANDLER_REPLY_MSG);
}
}
/* preProcParaGet - preprocessing for parallel get. Basically it calls
* rsDataGet to setup portalOprOut with the resource server.
*/
int
preProcParaGet (rsComm_t *rsComm, int l1descInx, portalOprOut_t **portalOprOut)
{
int l3descInx;
int status;
dataOprInp_t dataOprInp;
l3descInx = L1desc[l1descInx].l3descInx;
initDataOprInp (&dataOprInp, l1descInx, GET_OPR);
/* add RESC_NAME_KW for getNumThreads */
if (L1desc[l1descInx].dataObjInfo != NULL &&
L1desc[l1descInx].dataObjInfo->rescInfo != NULL) {
addKeyVal (&dataOprInp.condInput, RESC_NAME_KW,
L1desc[l1descInx].dataObjInfo->rescInfo->rescName);
}
if (L1desc[l1descInx].remoteZoneHost != NULL) {
status = remoteDataGet (rsComm, &dataOprInp, portalOprOut,
L1desc[l1descInx].remoteZoneHost);
} else {
status = rsDataGet (rsComm, &dataOprInp, portalOprOut);
}
if (status >= 0) {
(*portalOprOut)->l1descInx = l1descInx;
}
clearKeyVal (&dataOprInp.condInput);
return (status);
}
int
l3DataGetSingleBuf (rsComm_t *rsComm, int l1descInx,
bytesBuf_t *dataObjOutBBuf, portalOprOut_t **portalOprOut)
{
int status = 0;
int bytesRead;
openedDataObjInp_t dataObjCloseInp;
dataObjInfo_t *dataObjInfo;
/* just malloc an empty portalOprOut */
*portalOprOut = (portalOprOut_t*)malloc (sizeof (portalOprOut_t));
memset (*portalOprOut, 0, sizeof (portalOprOut_t));
dataObjInfo = L1desc[l1descInx].dataObjInfo;
if (dataObjInfo->dataSize > 0) {
dataObjOutBBuf->buf = malloc (dataObjInfo->dataSize);
bytesRead = l3FileGetSingleBuf (rsComm, l1descInx, dataObjOutBBuf);
} else {
bytesRead = 0;
}
#if 0 /* tested in _rsFileGet. don't need to go it again */
if (bytesRead != dataObjInfo->dataSize) {
free (dataObjOutBBuf->buf);
memset (dataObjOutBBuf, 0, sizeof (bytesBuf_t));
if (bytesRead >= 0) {
rodsLog (LOG_NOTICE,
"l3DataGetSingleBuf:Bytes toread %d don't match read %d",
dataObjInfo->dataSize, bytesRead);
bytesRead = SYS_COPY_LEN_ERR - errno;
}
}
#endif
memset (&dataObjCloseInp, 0, sizeof (dataObjCloseInp));
dataObjCloseInp.l1descInx = l1descInx;
status = rsDataObjClose (rsComm, &dataObjCloseInp);
if (status < 0) {
rodsLog (LOG_NOTICE,
"l3DataGetSingleBuf: rsDataObjClose of %d error, status = %d",
l1descInx, status);
}
if (bytesRead < 0)
return (bytesRead);
else
return status;
}
/* l3FileGetSingleBuf - Get the content of a small file into a single buffer
* in dataObjOutBBuf->buf for an opened data obj in l1descInx.
* Return value - int - number of bytes read.
*/
int
l3FileGetSingleBuf (rsComm_t *rsComm, int l1descInx,
bytesBuf_t *dataObjOutBBuf)
{
dataObjInfo_t *dataObjInfo;
int rescTypeInx;
fileOpenInp_t fileGetInp;
int bytesRead;
dataObjInp_t *dataObjInp;
dataObjInfo = L1desc[l1descInx].dataObjInfo;
if (getStructFileType (dataObjInfo->specColl) >= 0) {
subFile_t subFile;
memset (&subFile, 0, sizeof (subFile));
rstrcpy (subFile.subFilePath, dataObjInfo->subPath,
MAX_NAME_LEN);
rstrcpy (subFile.addr.hostAddr, dataObjInfo->rescInfo->rescLoc,
NAME_LEN);
subFile.specColl = dataObjInfo->specColl;
subFile.mode = getFileMode (L1desc[l1descInx].dataObjInp);
subFile.flags = O_RDONLY;
subFile.offset = dataObjInfo->dataSize;
bytesRead = rsSubStructFileGet (rsComm, &subFile, dataObjOutBBuf);
return (bytesRead);
}
rescTypeInx = dataObjInfo->rescInfo->rescTypeInx;
switch (RescTypeDef[rescTypeInx].rescCat) {
case FILE_CAT:
memset (&fileGetInp, 0, sizeof (fileGetInp));
dataObjInp = L1desc[l1descInx].dataObjInp;
fileGetInp.fileType = (fileDriverType_t)RescTypeDef[rescTypeInx].driverType;
rstrcpy (fileGetInp.addr.hostAddr, dataObjInfo->rescInfo->rescLoc,
NAME_LEN);
rstrcpy (fileGetInp.fileName, dataObjInfo->filePath, MAX_NAME_LEN);
fileGetInp.mode = getFileMode (dataObjInp);
fileGetInp.flags = O_RDONLY;
fileGetInp.dataSize = dataObjInfo->dataSize;
/* XXXXX need to be able to handle structured file */
bytesRead = rsFileGet (rsComm, &fileGetInp, dataObjOutBBuf);
break;
default:
rodsLog (LOG_NOTICE,
"l3Open: rescCat type %d is not recognized",
RescTypeDef[rescTypeInx].rescCat);
bytesRead = SYS_INVALID_RESC_TYPE;
break;
}
return (bytesRead);
}
| bsd-3-clause |
coreboot/chrome-ec | zephyr/drivers/cros_flash/cros_flash_xec.c | 2 | 14153 | /* Copyright 2022 The ChromiumOS Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#define DT_DRV_COMPAT microchip_xec_cros_flash
#include "../drivers/flash/spi_nor.h"
#include "flash.h"
#include "spi_flash_reg.h"
#include "write_protect.h"
#include <zephyr/drivers/flash.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/spi.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <drivers/cros_flash.h>
#include <soc.h>
LOG_MODULE_REGISTER(cros_flash, LOG_LEVEL_ERR);
static int all_protected;
static int addr_prot_start;
static int addr_prot_length;
static uint8_t saved_sr1;
/* Device data */
struct cros_flash_xec_data {
const struct device *flash_dev;
const struct device *spi_ctrl_dev;
};
static struct spi_config spi_cfg;
#define FLASH_DEV DT_NODELABEL(int_flash)
#define SPI_CONTROLLER_DEV DT_NODELABEL(spi0)
/* cros ec flash local functions */
static int cros_flash_xec_get_status_reg(const struct device *dev,
uint8_t cmd_code, uint8_t *data)
{
uint8_t opcode;
struct cros_flash_xec_data *dev_data = dev->data;
struct spi_buf spi_buf[2] = {
[0] = {
.buf = &opcode,
.len = 1,
},
[1] = {
.buf = data,
.len = 1,
}
};
const struct spi_buf_set tx_set = {
.buffers = spi_buf,
.count = 2,
};
const struct spi_buf_set rx_set = {
.buffers = spi_buf,
.count = 2,
};
if (data == 0)
return -EINVAL;
opcode = cmd_code;
return spi_transceive(dev_data->spi_ctrl_dev, &spi_cfg, &tx_set,
&rx_set);
}
static int cros_flash_xec_wait_ready(const struct device *dev)
{
int wait_period = 10; /* 10 us period t0 check status register */
int timeout = (10 * USEC_PER_SEC) / wait_period; /* 10 seconds */
do {
uint8_t reg;
cros_flash_xec_get_status_reg(dev, SPI_NOR_CMD_RDSR, ®);
if ((reg & SPI_NOR_WIP_BIT) == 0)
break;
k_usleep(wait_period);
} while (--timeout); /* Wait for busy bit clear */
if (timeout)
return 0;
else
return -ETIMEDOUT;
}
/* Check the BUSY bit is cleared and WE bit is set */
static int cros_flash_xec_wait_ready_and_we(const struct device *dev)
{
int wait_period = 10; /* 10 us period t0 check status register */
int timeout = (10 * USEC_PER_SEC) / wait_period; /* 10 seconds */
do {
uint8_t reg;
cros_flash_xec_get_status_reg(dev, SPI_NOR_CMD_RDSR, ®);
if ((reg & SPI_NOR_WIP_BIT) == 0 &&
(reg & SPI_NOR_WEL_BIT) != 0) {
break;
}
k_usleep(wait_period);
} while (--timeout); /* Wait for busy bit clear */
if (timeout)
return 0;
else
return -ETIMEDOUT;
}
static int cros_flash_xec_set_write_enable(const struct device *dev)
{
int ret;
uint8_t opcode = SPI_NOR_CMD_WREN;
struct cros_flash_xec_data *data = dev->data;
struct spi_buf spi_buf = {
.buf = &opcode,
.len = 1,
};
const struct spi_buf_set tx_set = {
.buffers = &spi_buf,
.count = 1,
};
/* Wait for previous operation to complete */
ret = cros_flash_xec_wait_ready(dev);
if (ret != 0)
return ret;
/* Write enable command */
ret = spi_transceive(data->spi_ctrl_dev, &spi_cfg, &tx_set, NULL);
if (ret != 0)
return ret;
/* Wait for flash is not busy */
return cros_flash_xec_wait_ready_and_we(dev);
}
static int cros_flash_xec_set_status_reg(const struct device *dev,
uint8_t *data)
{
uint8_t opcode = SPI_NOR_CMD_WRSR;
int ret = 0;
struct cros_flash_xec_data *dev_data = dev->data;
struct spi_buf spi_buf[2] = {
[0] = {
.buf = &opcode,
.len = 1,
},
[1] = {
.buf = data,
.len = 1,
}
};
const struct spi_buf_set tx_set = {
.buffers = spi_buf,
.count = 2,
};
if (data == 0)
return -EINVAL;
/* Enable write */
ret = cros_flash_xec_set_write_enable(dev);
if (ret != 0)
return ret;
ret = spi_transceive(dev_data->spi_ctrl_dev, &spi_cfg, &tx_set, NULL);
if (ret != 0)
return ret;
return cros_flash_xec_wait_ready(dev);
}
static int cros_flash_xec_write_protection_set(const struct device *dev,
bool enable)
{
int ret = 0;
/* Write protection can be cleared only by core domain reset */
if (!enable) {
LOG_ERR("WP can be disabled only via core domain reset ");
return -ENOTSUP;
}
/* MCHP TODO need API call to set flash WP# pin active: GPIO driver? */
return ret;
}
static int cros_flash_xec_write_protection_is_set(const struct device *dev)
{
/* MCHP TODO - Read WP# pin state: GPIO driver? */
return 0;
}
static int cros_flash_xec_uma_lock(const struct device *dev, bool enable)
{
struct cros_flash_xec_data *data = dev->data;
if (enable)
spi_cfg.operation |= SPI_LOCK_ON;
else
spi_cfg.operation &= ~SPI_LOCK_ON;
return spi_transceive(data->spi_ctrl_dev, &spi_cfg, NULL, NULL);
}
static void flash_get_status(const struct device *dev, uint8_t *sr1)
{
if (all_protected) {
*sr1 = saved_sr1;
return;
}
/* Lock physical flash operations */
crec_flash_lock_mapped_storage(1);
/* Read status register1 */
cros_flash_xec_get_status_reg(dev, SPI_NOR_CMD_RDSR, sr1);
/* Unlock physical flash operations */
crec_flash_lock_mapped_storage(0);
}
static int flash_set_status(const struct device *dev, uint8_t sr1)
{
int rv;
uint8_t regs[2];
regs[0] = sr1;
regs[1] = 0;
/* Lock physical flash operations */
crec_flash_lock_mapped_storage(1);
rv = cros_flash_xec_set_status_reg(dev, regs);
/* Unlock physical flash operations */
crec_flash_lock_mapped_storage(0);
return rv;
}
static int is_int_flash_protected(const struct device *dev)
{
return cros_flash_xec_write_protection_is_set(dev);
}
static void flash_protect_int_flash(const struct device *dev, int enable)
{
/*
* Please notice the type of WP_IF bit is R/W1S. Once it's set,
* only rebooting EC can clear it.
*/
if (enable)
cros_flash_xec_write_protection_set(dev, enable);
}
static void flash_uma_lock(const struct device *dev, int enable)
{
if (enable && !all_protected) {
/*
* Store SR1 for later use since we're about to lock
* out all access (including read access) to these regs.
*/
flash_get_status(dev, &saved_sr1);
}
cros_flash_xec_uma_lock(dev, enable);
all_protected = enable;
}
static int flash_set_status_for_prot(const struct device *dev, int reg1)
{
/*
* Writing SR regs will fail if our UMA lock is enabled. If WP
* is deasserted then remove the lock and allow the write.
*/
if (all_protected) {
if (is_int_flash_protected(dev))
return EC_ERROR_ACCESS_DENIED;
if (crec_flash_get_protect() & EC_FLASH_PROTECT_GPIO_ASSERTED)
return EC_ERROR_ACCESS_DENIED;
flash_uma_lock(dev, 0);
}
/*
* If WP# is active and ec doesn't protect the status registers of
* internal spi-flash, protect it now before setting them.
*/
flash_protect_int_flash(dev, write_protect_is_asserted());
flash_set_status(dev, reg1);
spi_flash_reg_to_protect(reg1, 0, &addr_prot_start, &addr_prot_length);
return EC_SUCCESS;
}
static int flash_check_prot_reg(const struct device *dev, unsigned int offset,
unsigned int bytes)
{
unsigned int start;
unsigned int len;
uint8_t sr1;
int rv = EC_SUCCESS;
/*
* If WP# is active and ec doesn't protect the status registers of
* internal spi-flash, protect it now.
*/
flash_protect_int_flash(dev, write_protect_is_asserted());
/* Invalid value */
if (offset + bytes > CONFIG_FLASH_SIZE_BYTES)
return EC_ERROR_INVAL;
/* Compute current protect range */
flash_get_status(dev, &sr1);
rv = spi_flash_reg_to_protect(sr1, 0, &start, &len);
if (rv)
return rv;
/* Check if ranges overlap */
if (MAX(start, offset) < MIN(start + len, offset + bytes))
return EC_ERROR_ACCESS_DENIED;
return EC_SUCCESS;
}
static int flash_write_prot_reg(const struct device *dev, unsigned int offset,
unsigned int bytes, int hw_protect)
{
int rv;
uint8_t sr1;
/* Invalid values */
if (offset + bytes > CONFIG_FLASH_SIZE_BYTES)
return EC_ERROR_INVAL;
/* Compute desired protect range */
flash_get_status(dev, &sr1);
rv = spi_flash_protect_to_reg(offset, bytes, &sr1, 0);
if (rv)
return rv;
if (hw_protect)
sr1 |= SPI_FLASH_SR1_SRP0;
return flash_set_status_for_prot(dev, sr1);
}
static int flash_check_prot_range(unsigned int offset, unsigned int bytes)
{
/* Invalid value */
if (offset + bytes > CONFIG_FLASH_SIZE_BYTES)
return EC_ERROR_INVAL;
/* Check if ranges overlap */
if (MAX(addr_prot_start, offset) <
MIN(addr_prot_start + addr_prot_length, offset + bytes)) {
return EC_ERROR_ACCESS_DENIED;
}
return EC_SUCCESS;
}
/* cros ec flash api functions */
static int cros_flash_xec_init(const struct device *dev)
{
/* Initialize UMA to unlocked */
flash_uma_lock(dev, 0);
/*
* Protect status registers of internal spi-flash if WP# is active
* during ec initialization.
*/
flash_protect_int_flash(dev, write_protect_is_asserted());
return 0;
}
static int cros_flash_xec_write(const struct device *dev, int offset, int size,
const char *src_data)
{
int ret = 0;
struct cros_flash_xec_data *data = dev->data;
/* check protection */
if (all_protected)
return EC_ERROR_ACCESS_DENIED;
/* check protection */
if (flash_check_prot_range(offset, size))
return EC_ERROR_ACCESS_DENIED;
/* Invalid data pointer? */
if (src_data == 0)
return -EINVAL;
ret = flash_write(data->flash_dev, offset, src_data, size);
return ret;
}
static int cros_flash_xec_erase(const struct device *dev, int offset, int size)
{
int ret = 0;
struct cros_flash_xec_data *data = dev->data;
/* check protection */
if (all_protected)
return EC_ERROR_ACCESS_DENIED;
/* check protection */
if (flash_check_prot_range(offset, size))
return EC_ERROR_ACCESS_DENIED;
/* address must be aligned to erase size */
if ((offset % CONFIG_FLASH_ERASE_SIZE) != 0)
return -EINVAL;
/* Erase size must be a non-zero multiple of sectors */
if ((size == 0) || (size % CONFIG_FLASH_ERASE_SIZE) != 0)
return -EINVAL;
ret = flash_erase(data->flash_dev, offset, size);
return ret;
}
static int cros_flash_xec_get_protect(const struct device *dev, int bank)
{
uint32_t addr = bank * CONFIG_FLASH_BANK_SIZE;
return flash_check_prot_reg(dev, addr, CONFIG_FLASH_BANK_SIZE);
}
static uint32_t cros_flash_xec_get_protect_flags(const struct device *dev)
{
uint32_t flags = 0;
int rv;
uint8_t sr1;
unsigned int start, len;
/* Check if WP region is protected in status register */
rv = flash_check_prot_reg(dev, WP_BANK_OFFSET * CONFIG_FLASH_BANK_SIZE,
WP_BANK_COUNT * CONFIG_FLASH_BANK_SIZE);
if (rv == EC_ERROR_ACCESS_DENIED)
flags |= EC_FLASH_PROTECT_RO_AT_BOOT;
else if (rv)
return EC_FLASH_PROTECT_ERROR_UNKNOWN;
/*
* If the status register protects a range, but SRP0 is not set,
* or Quad Enable (QE) is set,
* flags should indicate EC_FLASH_PROTECT_ERROR_INCONSISTENT.
*/
flash_get_status(dev, &sr1);
rv = spi_flash_reg_to_protect(sr1, 0, &start, &len);
if (rv)
return EC_FLASH_PROTECT_ERROR_UNKNOWN;
if (len && (!(sr1 & SPI_FLASH_SR1_SRP0)))
flags |= EC_FLASH_PROTECT_ERROR_INCONSISTENT;
/* Read all-protected state from our shadow copy */
if (all_protected)
flags |= EC_FLASH_PROTECT_ALL_NOW;
return flags;
}
static int cros_flash_xec_protect_at_boot(const struct device *dev,
uint32_t new_flags)
{
int ret;
if ((new_flags & (EC_FLASH_PROTECT_RO_AT_BOOT |
EC_FLASH_PROTECT_ALL_AT_BOOT)) == 0) {
/* Clear protection bits in status register */
return flash_set_status_for_prot(dev, 0);
}
ret = flash_write_prot_reg(dev, CONFIG_WP_STORAGE_OFF,
CONFIG_WP_STORAGE_SIZE, 1);
/*
* Set UMA_LOCK bit for locking all UMA transaction.
* But we still can read directly from flash mapping address
*/
if (new_flags & EC_FLASH_PROTECT_ALL_AT_BOOT)
flash_uma_lock(dev, 1);
return ret;
}
static int cros_flash_xec_protect_now(const struct device *dev, int all)
{
if (all) {
/*
* Set UMA_LOCK bit for locking all UMA transaction.
* But we still can read directly from flash mapping address
*/
flash_uma_lock(dev, 1);
} else {
/* TODO: Implement RO "now" protection */
}
return EC_SUCCESS;
}
static int cros_flash_xec_get_jedec_id(const struct device *dev,
uint8_t *manufacturer, uint16_t *device)
{
int ret;
uint8_t jedec_id[3];
struct cros_flash_xec_data *data = dev->data;
/* Lock physical flash operations */
crec_flash_lock_mapped_storage(1);
ret = flash_read_jedec_id(data->flash_dev, jedec_id);
if (ret == 0) {
*manufacturer = jedec_id[0];
*device = (jedec_id[1] << 8) | jedec_id[2];
}
/* Unlock physical flash operations */
crec_flash_lock_mapped_storage(0);
return ret;
}
static int cros_flash_xec_get_status(const struct device *dev, uint8_t *sr1,
uint8_t *sr2)
{
flash_get_status(dev, sr1);
*sr2 = 0;
return EC_SUCCESS;
}
/* cros ec flash driver registration */
static const struct cros_flash_driver_api cros_flash_xec_driver_api = {
.init = cros_flash_xec_init,
.physical_write = cros_flash_xec_write,
.physical_erase = cros_flash_xec_erase,
.physical_get_protect = cros_flash_xec_get_protect,
.physical_get_protect_flags = cros_flash_xec_get_protect_flags,
.physical_protect_at_boot = cros_flash_xec_protect_at_boot,
.physical_protect_now = cros_flash_xec_protect_now,
.physical_get_jedec_id = cros_flash_xec_get_jedec_id,
.physical_get_status = cros_flash_xec_get_status,
};
static int flash_xec_init(const struct device *dev)
{
struct cros_flash_xec_data *data = dev->data;
data->flash_dev = DEVICE_DT_GET(FLASH_DEV);
if (!device_is_ready(data->flash_dev)) {
LOG_ERR("%s device not ready", data->flash_dev->name);
return -ENODEV;
}
data->spi_ctrl_dev = DEVICE_DT_GET(SPI_CONTROLLER_DEV);
if (!device_is_ready(data->spi_ctrl_dev)) {
LOG_ERR("%s device not ready", data->spi_ctrl_dev->name);
return -ENODEV;
}
return EC_SUCCESS;
}
#if CONFIG_CROS_FLASH_XEC_INIT_PRIORITY <= CONFIG_SPI_NOR_INIT_PRIORITY
#error "CONFIG_CROS_FLASH_XEC_INIT_PRIORITY must be greater than" \
"CONFIG_SPI_NOR_INIT_PRIORITY."
#endif
static struct cros_flash_xec_data cros_flash_data;
DEVICE_DT_INST_DEFINE(0, flash_xec_init, NULL, &cros_flash_data, NULL,
POST_KERNEL, CONFIG_CROS_FLASH_XEC_INIT_PRIORITY,
&cros_flash_xec_driver_api);
| bsd-3-clause |
youtube/cobalt | third_party/icu/source/i18n/units_converter.cpp | 3 | 19303 | // © 2020 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "charstr.h"
#include "cmemory.h"
#include "double-conversion-string-to-double.h"
#include "measunit_impl.h"
#include "uassert.h"
#include "unicode/errorcode.h"
#include "unicode/localpointer.h"
#include "unicode/stringpiece.h"
#include "units_converter.h"
#include <algorithm>
#include <cmath>
#include <stdlib.h>
#include <utility>
U_NAMESPACE_BEGIN
namespace units {
void U_I18N_API Factor::multiplyBy(const Factor &rhs) {
factorNum *= rhs.factorNum;
factorDen *= rhs.factorDen;
for (int i = 0; i < CONSTANTS_COUNT; i++) {
constants[i] += rhs.constants[i];
}
// NOTE
// We need the offset when the source and the target are simple units. e.g. the source is
// celsius and the target is Fahrenheit. Therefore, we just keep the value using `std::max`.
offset = std::max(rhs.offset, offset);
}
void U_I18N_API Factor::divideBy(const Factor &rhs) {
factorNum *= rhs.factorDen;
factorDen *= rhs.factorNum;
for (int i = 0; i < CONSTANTS_COUNT; i++) {
constants[i] -= rhs.constants[i];
}
// NOTE
// We need the offset when the source and the target are simple units. e.g. the source is
// celsius and the target is Fahrenheit. Therefore, we just keep the value using `std::max`.
offset = std::max(rhs.offset, offset);
}
void U_I18N_API Factor::power(int32_t power) {
// multiply all the constant by the power.
for (int i = 0; i < CONSTANTS_COUNT; i++) {
constants[i] *= power;
}
bool shouldFlip = power < 0; // This means that after applying the absolute power, we should flip
// the Numerator and Denominator.
factorNum = std::pow(factorNum, std::abs(power));
factorDen = std::pow(factorDen, std::abs(power));
if (shouldFlip) {
// Flip Numerator and Denominator.
std::swap(factorNum, factorDen);
}
}
void U_I18N_API Factor::flip() {
std::swap(factorNum, factorDen);
for (int i = 0; i < CONSTANTS_COUNT; i++) {
constants[i] *= -1;
}
}
void U_I18N_API Factor::applySiPrefix(UMeasureSIPrefix siPrefix) {
if (siPrefix == UMeasureSIPrefix::UMEASURE_SI_PREFIX_ONE) return; // No need to do anything
double siApplied = std::pow(10.0, std::abs(siPrefix));
if (siPrefix < 0) {
factorDen *= siApplied;
return;
}
factorNum *= siApplied;
}
void U_I18N_API Factor::substituteConstants() {
for (int i = 0; i < CONSTANTS_COUNT; i++) {
if (this->constants[i] == 0) {
continue;
}
auto absPower = std::abs(this->constants[i]);
Signum powerSig = this->constants[i] < 0 ? Signum::NEGATIVE : Signum::POSITIVE;
double absConstantValue = std::pow(constantsValues[i], absPower);
if (powerSig == Signum::NEGATIVE) {
this->factorDen *= absConstantValue;
} else {
this->factorNum *= absConstantValue;
}
this->constants[i] = 0;
}
}
namespace {
/* Helpers */
using icu::double_conversion::StringToDoubleConverter;
// TODO: Make this a shared-utility function.
// Returns `double` from a scientific number(i.e. "1", "2.01" or "3.09E+4")
double strToDouble(StringPiece strNum, UErrorCode &status) {
// We are processing well-formed input, so we don't need any special options to
// StringToDoubleConverter.
StringToDoubleConverter converter(0, 0, 0, "", "");
int32_t count;
double result = converter.StringToDouble(strNum.data(), strNum.length(), &count);
if (count != strNum.length()) {
status = U_INVALID_FORMAT_ERROR;
}
return result;
}
// Returns `double` from a scientific number that could has a division sign (i.e. "1", "2.01", "3.09E+4"
// or "2E+2/3")
double strHasDivideSignToDouble(StringPiece strWithDivide, UErrorCode &status) {
int divisionSignInd = -1;
for (int i = 0, n = strWithDivide.length(); i < n; ++i) {
if (strWithDivide.data()[i] == '/') {
divisionSignInd = i;
break;
}
}
if (divisionSignInd >= 0) {
return strToDouble(strWithDivide.substr(0, divisionSignInd), status) /
strToDouble(strWithDivide.substr(divisionSignInd + 1), status);
}
return strToDouble(strWithDivide, status);
}
/*
Adds single factor to a `Factor` object. Single factor means "23^2", "23.3333", "ft2m^3" ...etc.
However, complex factor are not included, such as "ft2m^3*200/3"
*/
void addFactorElement(Factor &factor, StringPiece elementStr, Signum signum, UErrorCode &status) {
StringPiece baseStr;
StringPiece powerStr;
int32_t power =
1; // In case the power is not written, then, the power is equal 1 ==> `ft2m^1` == `ft2m`
// Search for the power part
int32_t powerInd = -1;
for (int32_t i = 0, n = elementStr.length(); i < n; ++i) {
if (elementStr.data()[i] == '^') {
powerInd = i;
break;
}
}
if (powerInd > -1) {
// There is power
baseStr = elementStr.substr(0, powerInd);
powerStr = elementStr.substr(powerInd + 1);
power = static_cast<int32_t>(strToDouble(powerStr, status));
} else {
baseStr = elementStr;
}
addSingleFactorConstant(baseStr, power, signum, factor, status);
}
/*
* Extracts `Factor` from a complete string factor. e.g. "ft2m^3*1007/cup2m3*3"
*/
Factor extractFactorConversions(StringPiece stringFactor, UErrorCode &status) {
Factor result;
Signum signum = Signum::POSITIVE;
auto factorData = stringFactor.data();
for (int32_t i = 0, start = 0, n = stringFactor.length(); i < n; i++) {
if (factorData[i] == '*' || factorData[i] == '/') {
StringPiece factorElement = stringFactor.substr(start, i - start);
addFactorElement(result, factorElement, signum, status);
start = i + 1; // Set `start` to point to the start of the new element.
} else if (i == n - 1) {
// Last element
addFactorElement(result, stringFactor.substr(start, i + 1), signum, status);
}
if (factorData[i] == '/') {
signum = Signum::NEGATIVE; // Change the signum because we reached the Denominator.
}
}
return result;
}
// Load factor for a single source
Factor loadSingleFactor(StringPiece source, const ConversionRates &ratesInfo, UErrorCode &status) {
const auto conversionUnit = ratesInfo.extractConversionInfo(source, status);
if (U_FAILURE(status)) return Factor();
if (conversionUnit == nullptr) {
status = U_INTERNAL_PROGRAM_ERROR;
return Factor();
}
Factor result = extractFactorConversions(conversionUnit->factor.toStringPiece(), status);
result.offset = strHasDivideSignToDouble(conversionUnit->offset.toStringPiece(), status);
return result;
}
// Load Factor of a compound source unit.
Factor loadCompoundFactor(const MeasureUnitImpl &source, const ConversionRates &ratesInfo,
UErrorCode &status) {
Factor result;
for (int32_t i = 0, n = source.units.length(); i < n; i++) {
SingleUnitImpl singleUnit = *source.units[i];
Factor singleFactor = loadSingleFactor(singleUnit.getSimpleUnitID(), ratesInfo, status);
if (U_FAILURE(status)) return result;
// Apply SiPrefix before the power, because the power may be will flip the factor.
singleFactor.applySiPrefix(singleUnit.siPrefix);
// Apply the power of the `dimensionality`
singleFactor.power(singleUnit.dimensionality);
result.multiplyBy(singleFactor);
}
return result;
}
/**
* Checks if the source unit and the target unit are simple. For example celsius or fahrenheit. But not
* square-celsius or square-fahrenheit.
*
* NOTE:
* Empty unit means simple unit.
*/
UBool checkSimpleUnit(const MeasureUnitImpl &unit, UErrorCode &status) {
if (U_FAILURE(status)) return false;
if (unit.complexity != UMEASURE_UNIT_SINGLE) {
return false;
}
if (unit.units.length() == 0) {
// Empty units means simple unit.
return true;
}
auto singleUnit = *(unit.units[0]);
if (singleUnit.dimensionality != 1 || singleUnit.siPrefix != UMEASURE_SI_PREFIX_ONE) {
return false;
}
return true;
}
/**
* Extract conversion rate from `source` to `target`
*/
void loadConversionRate(ConversionRate &conversionRate, const MeasureUnitImpl &source,
const MeasureUnitImpl &target, Convertibility unitsState,
const ConversionRates &ratesInfo, UErrorCode &status) {
// Represents the conversion factor from the source to the target.
Factor finalFactor;
// Represents the conversion factor from the source to the base unit that specified in the conversion
// data which is considered as the root of the source and the target.
Factor sourceToBase = loadCompoundFactor(source, ratesInfo, status);
Factor targetToBase = loadCompoundFactor(target, ratesInfo, status);
// Merger Factors
finalFactor.multiplyBy(sourceToBase);
if (unitsState == Convertibility::CONVERTIBLE) {
finalFactor.divideBy(targetToBase);
} else if (unitsState == Convertibility::RECIPROCAL) {
finalFactor.multiplyBy(targetToBase);
} else {
status = UErrorCode::U_ARGUMENT_TYPE_MISMATCH;
return;
}
finalFactor.substituteConstants();
conversionRate.factorNum = finalFactor.factorNum;
conversionRate.factorDen = finalFactor.factorDen;
// In case of simple units (such as: celsius or fahrenheit), offsets are considered.
if (checkSimpleUnit(source, status) && checkSimpleUnit(target, status)) {
conversionRate.sourceOffset =
sourceToBase.offset * sourceToBase.factorDen / sourceToBase.factorNum;
conversionRate.targetOffset =
targetToBase.offset * targetToBase.factorDen / targetToBase.factorNum;
}
conversionRate.reciprocal = unitsState == Convertibility::RECIPROCAL;
}
struct UnitIndexAndDimension : UMemory {
int32_t index = 0;
int32_t dimensionality = 0;
UnitIndexAndDimension(const SingleUnitImpl &singleUnit, int32_t multiplier) {
index = singleUnit.index;
dimensionality = singleUnit.dimensionality * multiplier;
}
};
void mergeSingleUnitWithDimension(MaybeStackVector<UnitIndexAndDimension> &unitIndicesWithDimension,
const SingleUnitImpl &shouldBeMerged, int32_t multiplier) {
for (int32_t i = 0; i < unitIndicesWithDimension.length(); i++) {
auto &unitWithIndex = *unitIndicesWithDimension[i];
if (unitWithIndex.index == shouldBeMerged.index) {
unitWithIndex.dimensionality += shouldBeMerged.dimensionality * multiplier;
return;
}
}
unitIndicesWithDimension.emplaceBack(shouldBeMerged, multiplier);
}
void mergeUnitsAndDimensions(MaybeStackVector<UnitIndexAndDimension> &unitIndicesWithDimension,
const MeasureUnitImpl &shouldBeMerged, int32_t multiplier) {
for (int32_t unit_i = 0; unit_i < shouldBeMerged.units.length(); unit_i++) {
auto singleUnit = *shouldBeMerged.units[unit_i];
mergeSingleUnitWithDimension(unitIndicesWithDimension, singleUnit, multiplier);
}
}
UBool checkAllDimensionsAreZeros(const MaybeStackVector<UnitIndexAndDimension> &dimensionVector) {
for (int32_t i = 0; i < dimensionVector.length(); i++) {
if (dimensionVector[i]->dimensionality != 0) {
return false;
}
}
return true;
}
} // namespace
// Conceptually, this modifies factor: factor *= baseStr^(signum*power).
//
// baseStr must be a known constant or a value that strToDouble() is able to
// parse.
void U_I18N_API addSingleFactorConstant(StringPiece baseStr, int32_t power, Signum signum,
Factor &factor, UErrorCode &status) {
if (baseStr == "ft_to_m") {
factor.constants[CONSTANT_FT2M] += power * signum;
} else if (baseStr == "ft2_to_m2") {
factor.constants[CONSTANT_FT2M] += 2 * power * signum;
} else if (baseStr == "ft3_to_m3") {
factor.constants[CONSTANT_FT2M] += 3 * power * signum;
} else if (baseStr == "in3_to_m3") {
factor.constants[CONSTANT_FT2M] += 3 * power * signum;
factor.factorDen *= 12 * 12 * 12;
} else if (baseStr == "gal_to_m3") {
factor.factorNum *= 231;
factor.constants[CONSTANT_FT2M] += 3 * power * signum;
factor.factorDen *= 12 * 12 * 12;
} else if (baseStr == "gal_imp_to_m3") {
factor.constants[CONSTANT_GAL_IMP2M3] += power * signum;
} else if (baseStr == "G") {
factor.constants[CONSTANT_G] += power * signum;
} else if (baseStr == "gravity") {
factor.constants[CONSTANT_GRAVITY] += power * signum;
} else if (baseStr == "lb_to_kg") {
factor.constants[CONSTANT_LB2KG] += power * signum;
} else if (baseStr == "PI") {
factor.constants[CONSTANT_PI] += power * signum;
} else {
if (signum == Signum::NEGATIVE) {
factor.factorDen *= std::pow(strToDouble(baseStr, status), power);
} else {
factor.factorNum *= std::pow(strToDouble(baseStr, status), power);
}
}
}
/**
* Extracts the compound base unit of a compound unit (`source`). For example, if the source unit is
* `square-mile-per-hour`, the compound base unit will be `square-meter-per-second`
*/
MeasureUnitImpl U_I18N_API extractCompoundBaseUnit(const MeasureUnitImpl &source,
const ConversionRates &conversionRates,
UErrorCode &status) {
MeasureUnitImpl result;
if (U_FAILURE(status)) return result;
const auto &singleUnits = source.units;
for (int i = 0, count = singleUnits.length(); i < count; ++i) {
const auto &singleUnit = *singleUnits[i];
// Extract `ConversionRateInfo` using the absolute unit. For example: in case of `square-meter`,
// we will use `meter`
const auto rateInfo =
conversionRates.extractConversionInfo(singleUnit.getSimpleUnitID(), status);
if (U_FAILURE(status)) {
return result;
}
if (rateInfo == nullptr) {
status = U_INTERNAL_PROGRAM_ERROR;
return result;
}
// Multiply the power of the singleUnit by the power of the baseUnit. For example, square-hectare
// must be pow4-meter. (NOTE: hectare --> square-meter)
auto baseUnits =
MeasureUnitImpl::forIdentifier(rateInfo->baseUnit.toStringPiece(), status).units;
for (int32_t i = 0, baseUnitsCount = baseUnits.length(); i < baseUnitsCount; i++) {
baseUnits[i]->dimensionality *= singleUnit.dimensionality;
// TODO: Deal with SI-prefix
result.append(*baseUnits[i], status);
if (U_FAILURE(status)) {
return result;
}
}
}
return result;
}
/**
* Determine the convertibility between `source` and `target`.
* For example:
* `meter` and `foot` are `CONVERTIBLE`.
* `meter-per-second` and `second-per-meter` are `RECIPROCAL`.
* `meter` and `pound` are `UNCONVERTIBLE`.
*
* NOTE:
* Only works with SINGLE and COMPOUND units. If one of the units is a
* MIXED unit, an error will occur. For more information, see UMeasureUnitComplexity.
*/
Convertibility U_I18N_API extractConvertibility(const MeasureUnitImpl &source,
const MeasureUnitImpl &target,
const ConversionRates &conversionRates,
UErrorCode &status) {
if (source.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED ||
target.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
status = U_INTERNAL_PROGRAM_ERROR;
return UNCONVERTIBLE;
}
MeasureUnitImpl sourceBaseUnit = extractCompoundBaseUnit(source, conversionRates, status);
MeasureUnitImpl targetBaseUnit = extractCompoundBaseUnit(target, conversionRates, status);
if (U_FAILURE(status)) return UNCONVERTIBLE;
MaybeStackVector<UnitIndexAndDimension> convertible;
MaybeStackVector<UnitIndexAndDimension> reciprocal;
mergeUnitsAndDimensions(convertible, sourceBaseUnit, 1);
mergeUnitsAndDimensions(reciprocal, sourceBaseUnit, 1);
mergeUnitsAndDimensions(convertible, targetBaseUnit, -1);
mergeUnitsAndDimensions(reciprocal, targetBaseUnit, 1);
if (checkAllDimensionsAreZeros(convertible)) {
return CONVERTIBLE;
}
if (checkAllDimensionsAreZeros(reciprocal)) {
return RECIPROCAL;
}
return UNCONVERTIBLE;
}
UnitConverter::UnitConverter(const MeasureUnitImpl &source, const MeasureUnitImpl &target,
const ConversionRates &ratesInfo, UErrorCode &status)
: conversionRate_(source.copy(status), target.copy(status)) {
if (source.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED ||
target.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
status = U_INTERNAL_PROGRAM_ERROR;
return;
}
Convertibility unitsState = extractConvertibility(source, target, ratesInfo, status);
if (U_FAILURE(status)) return;
if (unitsState == Convertibility::UNCONVERTIBLE) {
status = U_INTERNAL_PROGRAM_ERROR;
return;
}
loadConversionRate(conversionRate_, conversionRate_.source, conversionRate_.target, unitsState,
ratesInfo, status);
}
double UnitConverter::convert(double inputValue) const {
double result =
inputValue + conversionRate_.sourceOffset; // Reset the input to the target zero index.
// Convert the quantity to from the source scale to the target scale.
result *= conversionRate_.factorNum / conversionRate_.factorDen;
result -= conversionRate_.targetOffset; // Set the result to its index.
if (conversionRate_.reciprocal) {
if (result == 0) {
// TODO: demonstrate the resulting behaviour in tests... and figure
// out desired behaviour. (Theoretical result should be infinity,
// not 0.)
return 0.0;
}
result = 1.0 / result;
}
return result;
}
double UnitConverter::convertInverse(double inputValue) const {
double result = inputValue;
if (conversionRate_.reciprocal) {
if (result == 0) {
// TODO: demonstrate the resulting behaviour in tests... and figure
// out desired behaviour. (Theoretical result should be infinity,
// not 0.)
return 0.0;
}
result = 1.0 / result;
}
result += conversionRate_.targetOffset;
result *= conversionRate_.factorDen / conversionRate_.factorNum;
result -= conversionRate_.sourceOffset;
return result;
}
} // namespace units
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
| bsd-3-clause |
JohanMabille/xtensor | test/test_xscalar_semantic.cpp | 3 | 9959 | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "test_common_macros.hpp"
#include "xtensor/xnoalias.hpp"
#include "test_xsemantic.hpp"
namespace xt
{
template <class T1, class T2>
inline bool full_equal(const T1& a1, const T2& a2)
{
return (a1.strides() == a2.strides()) && (a1 == a2);
}
template <class C>
class scalar_semantic : public ::testing::Test
{
public:
using storage_type = C;
};
#define SCALAR_SEMANTIC_TEST_TYPES xarray_dynamic, xtensor_dynamic
TEST_SUITE("scalar_semantic")
{
TEST_CASE_TEMPLATE("a_plus_equal_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::plus<>, TypeParam> tester;
SUBCASE("row_major += scalar")
{
TypeParam a = tester.ra;
a += tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major += scalar")
{
TypeParam a = tester.ca;
a += tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major += scalar")
{
TypeParam a = tester.cta;
a += tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major += scalar")
{
TypeParam a = tester.ua;
a += tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("a_minus_equal_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::minus<>, TypeParam> tester;
SUBCASE("row_major -= scalar")
{
TypeParam a = tester.ra;
a -= tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major -= scalar")
{
TypeParam a = tester.ca;
a -= tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major -= scalar")
{
TypeParam a = tester.cta;
a -= tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major -= scalar")
{
TypeParam a = tester.ua;
a -= tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("a_times_equal_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::multiplies<>, TypeParam> tester;
SUBCASE("row_major *= scalar")
{
TypeParam a = tester.ra;
a *= tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major *= scalar")
{
TypeParam a = tester.ca;
a *= tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major *= scalar")
{
TypeParam a = tester.cta;
a *= tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major *= scalar")
{
TypeParam a = tester.ua;
a *= tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("a_divide_by_equal_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::divides<>, TypeParam> tester;
SUBCASE("row_major /= scalar")
{
TypeParam a = tester.ra;
a /= tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major /= scalar")
{
TypeParam a = tester.ca;
a /= tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major /= scalar")
{
TypeParam a = tester.cta;
a /= tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major /= scalar")
{
TypeParam a = tester.ua;
a /= tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("assign_a_plus_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::plus<>, TypeParam> tester;
SUBCASE("row_major + scalar")
{
TypeParam a(tester.ra.shape(), tester.ra.strides(), 0);
noalias(a) = tester.ra + tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major + scalar")
{
TypeParam a(tester.ca.shape(), tester.ca.strides(), 0);
noalias(a) = tester.ca + tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major + scalar")
{
TypeParam a(tester.cta.shape(), tester.cta.strides(), 0);
noalias(a) = tester.cta + tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major + scalar")
{
TypeParam a(tester.ua.shape(), tester.ua.strides(), 0);
noalias(a) = tester.ua + tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("assign_a_minus_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::minus<>, TypeParam> tester;
SUBCASE("row_major - scalar")
{
TypeParam a(tester.ra.shape(), tester.ra.strides(), 0);
noalias(a) = tester.ra - tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major - scalar")
{
TypeParam a(tester.ca.shape(), tester.ca.strides(), 0);
noalias(a) = tester.ca - tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major - scalar")
{
TypeParam a(tester.cta.shape(), tester.cta.strides(), 0);
noalias(a) = tester.cta - tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major - scalar")
{
TypeParam a(tester.ua.shape(), tester.ua.strides(), 0);
noalias(a) = tester.ua - tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("assign_a_times_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::multiplies<>, TypeParam> tester;
SUBCASE("row_major * scalar")
{
TypeParam a(tester.ra.shape(), tester.ra.strides(), 0);
noalias(a) = tester.ra * tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major * scalar")
{
TypeParam a(tester.ca.shape(), tester.ca.strides(), 0);
noalias(a) = tester.ca * tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major * scalar")
{
TypeParam a(tester.cta.shape(), tester.cta.strides(), 0);
noalias(a) = tester.cta * tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major * scalar")
{
TypeParam a(tester.ua.shape(), tester.ua.strides(), 0);
noalias(a) = tester.ua * tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
TEST_CASE_TEMPLATE("assign_a_divide_by_b", TypeParam, SCALAR_SEMANTIC_TEST_TYPES)
{
scalar_operation_tester<std::divides<>, TypeParam> tester;
SUBCASE("row_major / scalar")
{
TypeParam a(tester.ra.shape(), tester.ra.strides(), 0);
noalias(a) = tester.ra / tester.b;
EXPECT_TRUE(full_equal(tester.res_r, a));
}
SUBCASE("column_major / scalar")
{
TypeParam a(tester.ca.shape(), tester.ca.strides(), 0);
noalias(a) = tester.ca / tester.b;
EXPECT_TRUE(full_equal(tester.res_c, a));
}
SUBCASE("central_major / scalar")
{
TypeParam a(tester.cta.shape(), tester.cta.strides(), 0);
noalias(a) = tester.cta / tester.b;
EXPECT_TRUE(full_equal(tester.res_ct, a));
}
SUBCASE("unit_major / scalar")
{
TypeParam a(tester.ua.shape(), tester.ua.strides(), 0);
noalias(a) = tester.ua / tester.b;
EXPECT_TRUE(full_equal(tester.res_u, a));
}
}
}
#undef SCALAR_SEMANTIC_TEST_TYPES
}
| bsd-3-clause |
FabianRepository/SinusProject | Code/include/igl/polyvector_field_comb_from_matchings_and_cuts.cpp | 3 | 5273 | #include <igl/colon.h>
#include <algorithm>
#include <deque>
#include <igl/polyvector_field_comb_from_matchings_and_cuts.h>
#include <igl/edge_topology.h>
#include <igl/triangle_triangle_adjacency.h>
template <typename DerivedV, typename DerivedF, typename DerivedTT, typename DerivedS, typename DerivedM, typename DerivedC>
IGL_INLINE void igl::polyvector_field_comb_from_matchings_and_cuts(
const Eigen::PlainObjectBase<DerivedV> &V,
const Eigen::PlainObjectBase<DerivedF> &F,
const Eigen::PlainObjectBase<DerivedTT> &TT,
const Eigen::MatrixXi &E2F,
const Eigen::MatrixXi &F2E,
const Eigen::PlainObjectBase<DerivedS> &sol3D,
const Eigen::PlainObjectBase<DerivedM> &match_ab,
const Eigen::PlainObjectBase<DerivedM> &match_ba,
const Eigen::PlainObjectBase<DerivedC> &cuts,
Eigen::PlainObjectBase<DerivedS> &sol3D_combed)
{
int half_degree = sol3D.cols()/3;
int full_degree = 2*half_degree;
Eigen::MatrixXi used; used.setConstant(F.rows(),half_degree,-1);
// Eigen::VectorXi mark;
std::deque<int> d;
sol3D_combed.setZero(sol3D.rows(), sol3D.cols());
int start = 0;
d.push_back(start);
used.row(start) = igl::colon<int>(0, half_degree-1);
sol3D_combed.row(start) = sol3D.row(start);
while (!d.empty())
{
int f0 = d.at(0);
d.pop_front();
for (int k=0; k<3; k++)
{
int f1 = TT(f0,k);
if (f1==-1) continue;
//do not comb across cuts
if ((used.row(f1).array()!=-1).any()||cuts(f0,k))
continue;
// look at the edge between the two faces
const int ¤t_edge = F2E(f0,k);
// check its orientation to determine whether match_ab or match_ba should be used
if ((E2F(current_edge,0) == f0) &&
(E2F(current_edge,1) == f1) )
{
//look at match_ab
for(int i=0; i<half_degree; ++i)
{
int ii = used(f0,i);
used(f1,i) = (match_ab(current_edge,ii%half_degree) + (ii>=half_degree)*half_degree)%full_degree;
}
}
else
{
assert((E2F(current_edge,1) == f0) &&
(E2F(current_edge,0) == f1));
//look at match_ba
for(int i=0; i<half_degree; ++i)
{
int ii = used(f0,i);
used(f1,i) = (match_ba(current_edge,ii%half_degree)+ (ii>=half_degree)*half_degree)%full_degree;
}
}
for (int i = 0; i<half_degree; ++i)
{
int sign = (used(f1,i)<half_degree)?1:-1;
sol3D_combed.block(f1,i*3,1,3) = sign*sol3D.block(f1,(used(f1,i)%half_degree)*3,1,3);
}
d.push_back(f1);
}
}
// everything should be marked
assert((used.rowwise().minCoeff().array()>=0).all());
}
template <typename DerivedV, typename DerivedF, typename DerivedS, typename DerivedM, typename DerivedC>
IGL_INLINE void igl::polyvector_field_comb_from_matchings_and_cuts(
const Eigen::PlainObjectBase<DerivedV> &V,
const Eigen::PlainObjectBase<DerivedF> &F,
const Eigen::PlainObjectBase<DerivedS> &sol3D,
const Eigen::PlainObjectBase<DerivedM> &match_ab,
const Eigen::PlainObjectBase<DerivedM> &match_ba,
const Eigen::PlainObjectBase<DerivedC> &cuts,
Eigen::PlainObjectBase<DerivedS> &sol3D_combed)
{
Eigen::MatrixXi TT, TTi;
igl::triangle_triangle_adjacency(V,F,TT,TTi);
Eigen::MatrixXi E, E2F, F2E;
igl::edge_topology(V,F,E,F2E,E2F);
igl::polyvector_field_comb_from_matchings_and_cuts(V, F, TT, E2F, F2E, sol3D, match_ab, match_ba, cuts, sol3D_combed);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template void igl::polyvector_field_comb_from_matchings_and_cuts<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template void igl::polyvector_field_comb_from_matchings_and_cuts<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif
| bsd-3-clause |
igor-m/retrobsd-with-double-precison | src/games/backgammon/move.c | 5 | 11113 | /*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#include "back.h"
#include <unistd.h>
#ifdef DEBUG
#ifdef CROSS
# include </usr/include/stdio.h>
#else
# include <stdio.h>
#endif
FILE *trace;
static char tests[20];
#endif
struct BOARD { /* structure of game position */
int b_board[26]; /* board position */
int b_in[2]; /* men in */
int b_off[2]; /* men off */
int b_st[4], b_fn[4]; /* moves */
struct BOARD *b_next; /* forward queue pointer */
};
struct BOARD *freeq = (struct BOARD *) -1;
struct BOARD *checkq = (struct BOARD *) -1;
struct BOARD *bsave();
struct BOARD *nextfree();
/* these variables are values for the
* candidate move */
static int ch; /* chance of being hit */
static int op; /* computer's open men */
static int pt; /* comp's protected points */
static int em; /* farthest man back */
static int frc; /* chance to free comp's men */
static int frp; /* chance to free pl's men */
/* these values are the values for the
* move chosen (so far) */
static int chance; /* chance of being hit */
static int openmen; /* computer's open men */
static int points; /* comp's protected points */
static int endman; /* farthest man back */
static int barmen; /* men on bar */
static int menin; /* men in inner table */
static int menoff; /* men off board */
static int oldfrc; /* chance to free comp's men */
static int oldfrp; /* chance to free pl's men */
static int cp[5]; /* candidate start position */
static int cg[5]; /* candidate finish position */
static int race; /* game reduced to a race */
static int
bcomp (a, b)
struct BOARD *a;
struct BOARD *b;
{
register int *aloc = a->b_board; /* pointer to board a */
register int *bloc = b->b_board; /* pointer to board b */
register int i; /* index */
int result; /* comparison result */
for (i = 0; i < 26; i++) { /* compare boards */
result = cturn*(aloc[i]-bloc[i]);
if (result)
return (result); /* found inequality */
}
return (0); /* same position */
}
static void
mvcheck (incumbent, candidate)
register struct BOARD *incumbent;
register struct BOARD *candidate;
{
register int i;
register int result;
for (i = 0; i < mvlim; i++) {
result = cturn*(candidate->b_st[i]-incumbent->b_st[i]);
if (result > 0)
return;
if (result < 0)
break;
}
if (i == mvlim)
return;
for (i = 0; i < mvlim; i++) {
incumbent->b_st[i] = candidate->b_st[i];
incumbent->b_fn[i] = candidate->b_fn[i];
}
}
static void
makefree (dead)
struct BOARD *dead; /* dead position */
{
dead->b_next = freeq; /* add to freeq */
freeq = dead;
}
static void
binsert (new)
struct BOARD *new; /* item to insert */
{
register struct BOARD *p = checkq; /* queue pointer */
register int result; /* comparison result */
if (p == (struct BOARD*) -1) { /* check if queue empty */
checkq = p = new;
p->b_next = (struct BOARD*) -1;
return;
}
result = bcomp (new, p); /* compare to first element */
if (result < 0) { /* insert in front */
new->b_next = p;
checkq = new;
return;
}
if (result == 0) { /* duplicate entry */
mvcheck (p,new);
makefree (new);
return;
}
while (p->b_next != (struct BOARD*) -1) { /* traverse queue */
result = bcomp (new,p->b_next);
if (result < 0) { /* found place */
new->b_next = p->b_next;
p->b_next = new;
return;
}
if (result == 0) { /* duplicate entry */
mvcheck (p->b_next,new);
makefree (new);
return;
}
p = p->b_next;
}
/* place at end of queue */
p->b_next = new;
new->b_next = (struct BOARD*) -1;
}
static void
trymove (mvnum, swapped)
register int mvnum; /* number of move (rel zero) */
int swapped; /* see if swapped also tested */
{
register int pos; /* position on board */
register int rval; /* value of roll */
/* if recursed through all dice
* values, compare move */
if (mvnum == mvlim) {
binsert (bsave());
return;
}
/* make sure dice in always
* same order */
if (d0 == swapped)
swap;
/* choose value for this move */
rval = dice[mvnum != 0];
/* find all legitimate moves */
for (pos = bar; pos != home; pos += cturn) {
/* fix order of dice */
if (d0 == swapped)
swap;
/* break if stuck on bar */
if (board[bar] != 0 && pos != bar)
break;
/* on to next if not occupied */
if (board[pos]*cturn <= 0)
continue;
/* set up arrays for move */
p[mvnum] = pos;
g[mvnum] = pos+rval*cturn;
if (g[mvnum]*cturn >= home) {
if (*offptr < 0)
break;
g[mvnum] = home;
}
/* try to move */
if (makmove (mvnum))
continue;
else
trymove (mvnum+1,2);
/* undo move to try another */
backone (mvnum);
}
/* swap dice and try again */
if ((!swapped) && D0 != D1)
trymove (0,1);
}
static void
brcopy (s)
register struct BOARD *s; /* game situation */
{
register int i; /* index */
for (i = 0; i < 26; i++)
board[i] = s->b_board[i];
for (i = 0; i < 2; i++) {
in[i] = s->b_in[i];
off[i] = s->b_off[i];
}
for (i = 0; i < mvlim; i++) {
p[i] = s->b_st[i];
g[i] = s->b_fn[i];
}
}
static int
movegood ()
{
register int n;
if (*offptr == 15)
return (1);
if (menoff == 15)
return (0);
if (race) {
#ifdef DEBUG
strcat (tests,"o");
#endif
if (*offptr-menoff)
return (*offptr > menoff);
#ifdef DEBUG
strcat (tests,"e");
#endif
if (endman-em)
return (endman > em);
#ifdef DEBUG
strcat (tests,"i");
#endif
if (menin == 15)
return (0);
if (*inptr == 15)
return (1);
#ifdef DEBUG
strcat (tests,"i");
#endif
if (*inptr-menin)
return (*inptr > menin);
return (rnum(2));
} else {
n = barmen-abs(board[home]);
#ifdef DEBUG
strcat (tests,"c");
#endif
if (abs(chance-ch)+25*n > rnum(150))
return (n? (n < 0): (ch < chance));
#ifdef DEBUG
strcat (tests,"o");
#endif
if (*offptr-menoff)
return (*offptr > menoff);
#ifdef DEBUG
strcat (tests,"o");
#endif
if (abs(openmen-op) > 7+rnum(12))
return (openmen > op);
#ifdef DEBUG
strcat (tests,"b");
#endif
if (n)
return (n < 0);
#ifdef DEBUG
strcat (tests,"e");
#endif
if (abs(endman-em) > rnum(2))
return (endman > em);
#ifdef DEBUG
strcat (tests,"f");
#endif
if (abs(frc-oldfrc) > rnum(2))
return (frc < oldfrc);
#ifdef DEBUG
strcat (tests,"p");
#endif
if (abs(n = pt-points) > rnum(4))
return (n > 0);
#ifdef DEBUG
strcat (tests,"i");
#endif
if (*inptr-menin)
return (*inptr > menin);
#ifdef DEBUG
strcat (tests,"f");
#endif
if (abs(frp-oldfrp) > rnum(2))
return (frp > oldfrp);
return (rnum(2));
}
}
static void
movcmp ()
{
register int i;
#ifdef DEBUG
if (trace == NULL)
trace = fopen ("bgtrace","w");
#endif
odds (0,0,0);
if (!race) {
ch = op = pt = 0;
for (i = 1; i < 25; i++) {
if (board[i] == cturn)
ch = canhit (i,1);
op += abs (bar-i);
}
for (i = bar+cturn; i != home; i += cturn)
if (board[i]*cturn > 1)
pt += abs(bar-i);
frc = freemen (bar)+trapped (bar,cturn);
frp = freemen (home)+trapped (home,-cturn);
}
for (em = bar; em != home; em += cturn)
if (board[em]*cturn > 0)
break;
em = abs(home-em);
#ifdef DEBUG
fputs ("Board: ",trace);
for (i = 0; i < 26; i++)
fprintf (trace, " %d",board[i]);
if (race)
fprintf (trace,"\n\tem = %d\n",em);
else
fprintf (trace,
"\n\tch = %d, pt = %d, em = %d, frc = %d, frp = %d\n",
ch,pt,em,frc,frp);
fputs ("\tMove: ",trace);
for (i = 0; i < mvlim; i++)
fprintf (trace," %d-%d",p[i],g[i]);
fputs ("\n",trace);
fflush (trace);
strcpy (tests,"");
#endif
if ((cp[0] == 0 && cg[0] == 0) || movegood()) {
#ifdef DEBUG
fprintf (trace,"\t[%s] ... wins.\n",tests);
fflush (trace);
#endif
for (i = 0; i < mvlim; i++) {
cp[i] = p[i];
cg[i] = g[i];
}
if (!race) {
chance = ch;
openmen = op;
points = pt;
endman = em;
barmen = abs(board[home]);
oldfrc = frc;
oldfrp = frp;
}
menin = *inptr;
menoff = *offptr;
}
#ifdef DEBUG
else {
fprintf (trace,"\t[%s] ... loses.\n",tests);
fflush (trace);
}
#endif
}
static void
pickmove ()
{
/* current game position */
register struct BOARD *now = bsave();
register struct BOARD *next; /* next move */
#ifdef DEBUG
if (trace == NULL)
trace = fopen ("bgtrace","w");
fprintf (trace,"\nRoll: %d %d%s\n",D0,D1,race? " (race)": "");
fflush (trace);
#endif
do { /* compare moves */
brcopy (checkq);
next = checkq->b_next;
makefree (checkq);
checkq = next;
movcmp();
} while (checkq != (struct BOARD*) -1);
brcopy (now);
}
void
move (okay)
int okay; /* zero if first move */
{
register int i; /* index */
register int l = 0; /* last man */
if (okay) {
/* see if comp should double */
if (gvalue < 64 && dlast != cturn && dblgood()) {
writel (*Colorptr);
dble(); /* double */
/* return if declined */
if (cturn != 1 && cturn != -1)
return;
}
roll();
}
race = 0;
for (i = 0; i < 26; i++) {
if (board[i] < 0)
l = i;
}
for (i = 0; i < l; i++) {
if (board[i] > 0)
break;
}
if (i == l)
race = 1;
/* print roll */
if (tflag)
curmove (cturn == -1? 18: 19,0);
writel (*Colorptr);
writel (" rolls ");
writec (D0+'0');
writec (' ');
writec (D1+'0');
/* make tty interruptable
* while thinking */
if (tflag)
cline();
fixtty (noech);
/* find out how many moves */
mvlim = movallow();
if (mvlim == 0) {
writel (" but cannot use it.\n");
nexturn();
fixtty (raw);
return;
}
/* initialize */
for (i = 0; i < 4; i++)
cp[i] = cg[i] = 0;
/* strategize */
trymove (0,0);
pickmove();
/* print move */
writel (" and moves ");
for (i = 0; i < mvlim; i++) {
if (i > 0)
writec (',');
wrint (p[i] = cp[i]);
writec ('-');
wrint (g[i] = cg[i]);
makmove (i);
}
writec ('.');
/* print blots hit */
if (tflag)
curmove (20,0);
else
writec ('\n');
for (i = 0; i < mvlim; i++)
if (h[i])
wrhit(g[i]);
/* get ready for next move */
nexturn();
if (!okay) {
buflush();
sleep (3);
}
fixtty (raw); /* no more tty interrupt */
}
struct BOARD *
bsave ()
{
register int i; /* index */
struct BOARD *now; /* current position */
now = nextfree (); /* get free BOARD */
/* store position */
for (i = 0; i < 26; i++)
now->b_board[i] = board[i];
now->b_in[0] = in[0];
now->b_in[1] = in[1];
now->b_off[0] = off[0];
now->b_off[1] = off[1];
for (i = 0; i < mvlim; i++) {
now->b_st[i] = p[i];
now->b_fn[i] = g[i];
}
return (now);
}
struct BOARD *
nextfree ()
{
struct BOARD *new;
if (freeq == (struct BOARD*) -1) {
new = calloc (1,sizeof (struct BOARD));
if (new == 0) {
writel ("\nOut of memory\n");
getout (0);
}
new->b_next = (struct BOARD*) -1;
return (new);
}
new = freeq;
freeq = freeq->b_next;
return new;
}
| bsd-3-clause |
cooljeanius/trousers-0.3.11.2 | src/tcs/rpc/tcstp/rpc_context.c | 5 | 2003 |
/*
* Licensed Materials - Property of IBM
*
* trousers - An open source TCG Software Stack
*
* (C) Copyright International Business Machines Corp. 2004-2006
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <netdb.h>
#include "trousers/tss.h"
#include "trousers_types.h"
#include "tcs_tsp.h"
#include "tcs_utils.h"
#include "tcs_int_literals.h"
#include "capabilities.h"
#include "tcslog.h"
#include "tcsd_wrap.h"
#include "tcsd.h"
#include "tcs_utils.h"
#include "rpc_tcstp_tcs.h"
TSS_RESULT
tcs_wrap_OpenContext(struct tcsd_thread_data *data)
{
TCS_CONTEXT_HANDLE hContext;
TSS_RESULT result;
UINT32 tpm_version = tpm_metrics.version.minor;
LogDebugFn("thread %ld", THREAD_ID);
result = TCS_OpenContext_Internal(&hContext);
if (result == TSS_SUCCESS) {
initData(&data->comm, 2);
if (setData(TCSD_PACKET_TYPE_UINT32, 0, &hContext, 0, &data->comm))
return TCSERR(TSS_E_INTERNAL_ERROR);
if (setData(TCSD_PACKET_TYPE_UINT32, 1, &tpm_version, 0, &data->comm))
return TCSERR(TSS_E_INTERNAL_ERROR);
/* Set the context in the thread's object. Later, if something goes wrong
* and the connection can't be closed cleanly, we'll still have a reference
* to what resources need to be freed. */
data->context = hContext;
LogDebug("New context is 0x%x", hContext);
} else
initData(&data->comm, 0);
data->comm.hdr.u.result = result;
return TSS_SUCCESS;
}
TSS_RESULT
tcs_wrap_CloseContext(struct tcsd_thread_data *data)
{
TCS_CONTEXT_HANDLE hContext;
TSS_RESULT result;
if (getData(TCSD_PACKET_TYPE_UINT32, 0, &hContext, 0, &data->comm))
return TCSERR(TSS_E_INTERNAL_ERROR);
LogDebugFn("thread %ld context %x", THREAD_ID, hContext);
result = TCS_CloseContext_Internal(hContext);
/* This will signal the thread that the connection has been closed cleanly */
if (result == TSS_SUCCESS)
data->context = NULL_TCS_HANDLE;
initData(&data->comm, 0);
data->comm.hdr.u.result = result;
return TSS_SUCCESS;
}
| bsd-3-clause |
herloct/FrameworkBenchmarks | frameworks/C++/cutelyst/src/cutelyst-benchmarks.cpp | 5 | 2661 | #include "cutelyst-benchmarks.h"
#include <Cutelyst/Plugins/StaticSimple/staticsimple.h>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QMutexLocker>
#include "root.h"
#include "jsontest.h"
#include "singledatabasequerytest.h"
#include "multipledatabasequeriestest.h"
#include "databaseupdatestest.h"
#include "fortunetest.h"
#include "plaintexttest.h"
using namespace Cutelyst;
static QMutex mutex;
cutelyst_benchmarks::cutelyst_benchmarks(QObject *parent) : Application(parent)
{
}
cutelyst_benchmarks::~cutelyst_benchmarks()
{
}
bool cutelyst_benchmarks::init()
{
if (config(QLatin1String("SendDate")).value<bool>()) {
qDebug() << "Manually send date";
new Root(this);
}
new JsonTest(this);
new SingleDatabaseQueryTest(this);
new MultipleDatabaseQueriesTest(this);
new DatabaseUpdatesTest(this);
new FortuneTest(this);
new PlaintextTest(this);
defaultHeaders().setServer(QLatin1String("Cutelyst"));
defaultHeaders().removeHeader(QLatin1String("X-Cutelyst"));
return true;
}
bool cutelyst_benchmarks::postFork()
{
QMutexLocker locker(&mutex);
QSqlDatabase db;
db = QSqlDatabase::addDatabase(QLatin1String("QPSQL"), QLatin1String("postgres-") + QThread::currentThread()->objectName());
db.setDatabaseName(QLatin1String("hello_world"));
db.setUserName(QLatin1String("benchmarkdbuser"));
db.setPassword(QLatin1String("benchmarkdbpass"));
db.setHostName(config(QLatin1String("DatabaseHostName")).toString());
if (!db.open()) {
qDebug() << "Error opening PostgreSQL db:" << db << db.connectionName() << db.lastError().databaseText();
return false;
}
db = QSqlDatabase::addDatabase(QLatin1String("QMYSQL"), QLatin1String("mysql-") + QThread::currentThread()->objectName());
db.setDatabaseName(QLatin1String("hello_world"));
db.setUserName(QLatin1String("benchmarkdbuser"));
db.setPassword(QLatin1String("benchmarkdbpass"));
db.setHostName(config(QLatin1String("DatabaseHostName")).toString());
if (!db.open()) {
qDebug() << "Error opening MySQL db:" << db << db.connectionName() << db.lastError().databaseText();
return false;
}
qDebug() << "Connections" << QCoreApplication::applicationPid() << QThread::currentThread() << QSqlDatabase::connectionNames();
// db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("sqlite"));
// if (!db.open()) {
// qDebug() << "Error opening db:" << db << db.lastError().databaseText();
// return false;
// }
return true;
}
| bsd-3-clause |
ylow/SFrame | oss_test/fault/pub_test.cpp | 5 | 1693 | /*
* Copyright (C) 2016 Turi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <string>
#include <cassert>
#include <fault/sockets/socket_errors.hpp>
#include <fault/sockets/publish_socket.hpp>
#include <fault/sockets/socket_receive_pollset.hpp>
using namespace libfault;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Usage: pub_test [listen_addr] \n";
return 0;
}
std::string listen_addr = argv[1];
void* zmq_ctx = zmq_ctx_new();
zmq_ctx_set(zmq_ctx, ZMQ_IO_THREADS, 4);
publish_socket pubsock(zmq_ctx,
NULL,
listen_addr);
std::cout << "Publish server running. Empty message to quit\n";
while(1) {
std::string msg;
std::cout << "Message to Publish: ";
std::getline(std::cin, msg);
if (msg.size() == 0) break;
else {
zmq_msg_vector v;
zmq_msg_t* zmsg = v.insert_back();
zmq_msg_init_size(zmsg, msg.size());
memcpy(zmq_msg_data(zmsg), msg.c_str(), msg.length());
pubsock.send(v);
}
}
pubsock.close();
}
| bsd-3-clause |
the-nightling/cudpp | apps/cudpp_testrig/cudpp_testrig_options.cpp | 6 | 3514 | // -------------------------------------------------------------
// cuDPP -- CUDA Data Parallel Primitives library
// -------------------------------------------------------------
// $Revision$
// $Date$
// -------------------------------------------------------------
// This source code is distributed under the terms of license.txt
// in the root directory of this source distribution.
// -------------------------------------------------------------
#include "cudpp_testrig_options.h"
#define CUDPP_APP_COMMON_IMPL
#include "commandline.h"
using namespace cudpp_app;
/**
* Sets "global" options in testOptions given command line
* -debug: sets bool <var>debug</var>. Usage is application-dependent.
* -op=OP: sets char * <var>op</var> to OP
* -iterations=#: sets int <var>numIterations</var> to #
* -dir=<path>: sets the search path for cudppRand test inputs
*/
void setOptions(int argc, const char **argv, testrigOptions &testOptions)
{
testOptions.debug = false;
commandLineArg(testOptions.debug, argc, argv, "debug");
if (checkCommandLineFlag(argc, argv, "multiscan"))
testOptions.algorithm = "multiscan";
else if (checkCommandLineFlag(argc, argv, "scan"))
testOptions.algorithm = "scan";
else if (checkCommandLineFlag(argc, argv, "segscan"))
testOptions.algorithm = "segscan";
else if (checkCommandLineFlag(argc, argv, "compact"))
testOptions.algorithm = "compact";
else if (checkCommandLineFlag(argc, argv, "sort"))
testOptions.algorithm = "sort";
else if (checkCommandLineFlag(argc, argv, "reduce"))
testOptions.algorithm = "reduce";
else if (checkCommandLineFlag(argc, argv, "spmv"))
testOptions.algorithm = "spmv";
else if (checkCommandLineFlag(argc, argv, "rand"))
testOptions.algorithm = "rand";
else if (checkCommandLineFlag(argc, argv, "tridiagonal"))
testOptions.algorithm = "tridiagonal";
else if (checkCommandLineFlag(argc, argv, "mtf"))
testOptions.algorithm = "mtf";
else if (checkCommandLineFlag(argc, argv, "bwt"))
testOptions.algorithm = "bwt";
else if (checkCommandLineFlag(argc, argv, "compress"))
testOptions.algorithm = "compress";
testOptions.op = "sum";
commandLineArg(testOptions.op, argc, argv, "op");
testOptions.numIterations = numTestIterations;
commandLineArg(testOptions.numIterations, argc, argv, "iterations");
testOptions.dir = "";
commandLineArg(testOptions.dir, argc, argv, "dir");
}
bool hasOptions(int argc, const char**argv)
{
std::string temp;
if (commandLineArg(temp, argc, argv, "op") ||
checkCommandLineFlag(argc, argv, "float") ||
checkCommandLineFlag(argc, argv, "int") ||
checkCommandLineFlag(argc, argv, "uint") ||
checkCommandLineFlag(argc, argv, "double") ||
checkCommandLineFlag(argc, argv, "longlong") ||
checkCommandLineFlag(argc, argv, "ulonglong") ||
checkCommandLineFlag(argc, argv, "char") ||
checkCommandLineFlag(argc, argv, "uchar") ||
checkCommandLineFlag(argc, argv, "backward") ||
checkCommandLineFlag(argc, argv, "forward") ||
checkCommandLineFlag(argc, argv, "inclusive") ||
checkCommandLineFlag(argc, argv, "exclusive") ||
checkCommandLineFlag(argc, argv, "keysonly"))
return true;
return false;
}
// Leave this at the end of the file
// Local Variables:
// mode:c++
// c-file-style: "NVIDIA"
// End:
| bsd-3-clause |
shelsonjava/TeaJS | deps/v8/third_party/icu/source/common/dictbe.cpp | 6 | 44986 | /**
*******************************************************************************
* Copyright (C) 2006-2013, International Business Machines Corporation
* and others. All Rights Reserved.
*******************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_BREAK_ITERATION
#include "brkeng.h"
#include "dictbe.h"
#include "unicode/uniset.h"
#include "unicode/chariter.h"
#include "unicode/ubrk.h"
#include "uvector.h"
#include "uassert.h"
#include "unicode/normlzr.h"
#include "cmemory.h"
#include "dictionarydata.h"
U_NAMESPACE_BEGIN
/*
******************************************************************
*/
DictionaryBreakEngine::DictionaryBreakEngine(uint32_t breakTypes) {
fTypes = breakTypes;
}
DictionaryBreakEngine::~DictionaryBreakEngine() {
}
UBool
DictionaryBreakEngine::handles(UChar32 c, int32_t breakType) const {
return (breakType >= 0 && breakType < 32 && (((uint32_t)1 << breakType) & fTypes)
&& fSet.contains(c));
}
int32_t
DictionaryBreakEngine::findBreaks( UText *text,
int32_t startPos,
int32_t endPos,
UBool reverse,
int32_t breakType,
UStack &foundBreaks ) const {
int32_t result = 0;
// Find the span of characters included in the set.
int32_t start = (int32_t)utext_getNativeIndex(text);
int32_t current;
int32_t rangeStart;
int32_t rangeEnd;
UChar32 c = utext_current32(text);
if (reverse) {
UBool isDict = fSet.contains(c);
while((current = (int32_t)utext_getNativeIndex(text)) > startPos && isDict) {
c = utext_previous32(text);
isDict = fSet.contains(c);
}
rangeStart = (current < startPos) ? startPos : current+(isDict ? 0 : 1);
rangeEnd = start + 1;
}
else {
while((current = (int32_t)utext_getNativeIndex(text)) < endPos && fSet.contains(c)) {
utext_next32(text); // TODO: recast loop for postincrement
c = utext_current32(text);
}
rangeStart = start;
rangeEnd = current;
}
if (breakType >= 0 && breakType < 32 && (((uint32_t)1 << breakType) & fTypes)) {
result = divideUpDictionaryRange(text, rangeStart, rangeEnd, foundBreaks);
utext_setNativeIndex(text, current);
}
return result;
}
void
DictionaryBreakEngine::setCharacters( const UnicodeSet &set ) {
fSet = set;
// Compact for caching
fSet.compact();
}
/*
******************************************************************
* PossibleWord
*/
// Helper class for improving readability of the Thai/Lao/Khmer word break
// algorithm. The implementation is completely inline.
// List size, limited by the maximum number of words in the dictionary
// that form a nested sequence.
#define POSSIBLE_WORD_LIST_MAX 20
class PossibleWord {
private:
// list of word candidate lengths, in increasing length order
int32_t lengths[POSSIBLE_WORD_LIST_MAX];
int32_t count; // Count of candidates
int32_t prefix; // The longest match with a dictionary word
int32_t offset; // Offset in the text of these candidates
int mark; // The preferred candidate's offset
int current; // The candidate we're currently looking at
public:
PossibleWord();
~PossibleWord();
// Fill the list of candidates if needed, select the longest, and return the number found
int candidates( UText *text, DictionaryMatcher *dict, int32_t rangeEnd );
// Select the currently marked candidate, point after it in the text, and invalidate self
int32_t acceptMarked( UText *text );
// Back up from the current candidate to the next shorter one; return TRUE if that exists
// and point the text after it
UBool backUp( UText *text );
// Return the longest prefix this candidate location shares with a dictionary word
int32_t longestPrefix();
// Mark the current candidate as the one we like
void markCurrent();
};
inline
PossibleWord::PossibleWord() {
offset = -1;
}
inline
PossibleWord::~PossibleWord() {
}
inline int
PossibleWord::candidates( UText *text, DictionaryMatcher *dict, int32_t rangeEnd ) {
// TODO: If getIndex is too slow, use offset < 0 and add discardAll()
int32_t start = (int32_t)utext_getNativeIndex(text);
if (start != offset) {
offset = start;
prefix = dict->matches(text, rangeEnd-start, lengths, count, sizeof(lengths)/sizeof(lengths[0]));
// Dictionary leaves text after longest prefix, not longest word. Back up.
if (count <= 0) {
utext_setNativeIndex(text, start);
}
}
if (count > 0) {
utext_setNativeIndex(text, start+lengths[count-1]);
}
current = count-1;
mark = current;
return count;
}
inline int32_t
PossibleWord::acceptMarked( UText *text ) {
utext_setNativeIndex(text, offset + lengths[mark]);
return lengths[mark];
}
inline UBool
PossibleWord::backUp( UText *text ) {
if (current > 0) {
utext_setNativeIndex(text, offset + lengths[--current]);
return TRUE;
}
return FALSE;
}
inline int32_t
PossibleWord::longestPrefix() {
return prefix;
}
inline void
PossibleWord::markCurrent() {
mark = current;
}
/*
******************************************************************
* ThaiBreakEngine
*/
// How many words in a row are "good enough"?
#define THAI_LOOKAHEAD 3
// Will not combine a non-word with a preceding dictionary word longer than this
#define THAI_ROOT_COMBINE_THRESHOLD 3
// Will not combine a non-word that shares at least this much prefix with a
// dictionary word, with a preceding word
#define THAI_PREFIX_COMBINE_THRESHOLD 3
// Ellision character
#define THAI_PAIYANNOI 0x0E2F
// Repeat character
#define THAI_MAIYAMOK 0x0E46
// Minimum word size
#define THAI_MIN_WORD 2
// Minimum number of characters for two words
#define THAI_MIN_WORD_SPAN (THAI_MIN_WORD * 2)
ThaiBreakEngine::ThaiBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
: DictionaryBreakEngine((1<<UBRK_WORD) | (1<<UBRK_LINE)),
fDictionary(adoptDictionary)
{
fThaiWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Thai:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fThaiWordSet);
}
fMarkSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Thai:]&[:LineBreak=SA:]&[:M:]]"), status);
fMarkSet.add(0x0020);
fEndWordSet = fThaiWordSet;
fEndWordSet.remove(0x0E31); // MAI HAN-AKAT
fEndWordSet.remove(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
fBeginWordSet.add(0x0E01, 0x0E2E); // KO KAI through HO NOKHUK
fBeginWordSet.add(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
fSuffixSet.add(THAI_PAIYANNOI);
fSuffixSet.add(THAI_MAIYAMOK);
// Compact for caching.
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
fSuffixSet.compact();
}
ThaiBreakEngine::~ThaiBreakEngine() {
delete fDictionary;
}
int32_t
ThaiBreakEngine::divideUpDictionaryRange( UText *text,
int32_t rangeStart,
int32_t rangeEnd,
UStack &foundBreaks ) const {
if ((rangeEnd - rangeStart) < THAI_MIN_WORD_SPAN) {
return 0; // Not enough characters for two words
}
uint32_t wordsFound = 0;
int32_t wordLength;
int32_t current;
UErrorCode status = U_ZERO_ERROR;
PossibleWord words[THAI_LOOKAHEAD];
UChar32 uc;
utext_setNativeIndex(text, rangeStart);
while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
wordLength = 0;
// Look for candidate words at the current position
int candidates = words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
// If we found exactly one, use that
if (candidates == 1) {
wordLength = words[wordsFound % THAI_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// If there was more than one, see which one can take us forward the most words
else if (candidates > 1) {
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
do {
int wordsMatched = 1;
if (words[(wordsFound + 1) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
if (wordsMatched < 2) {
// Followed by another dictionary word; mark first word as a good candidate
words[wordsFound%THAI_LOOKAHEAD].markCurrent();
wordsMatched = 2;
}
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
// See if any of the possible second words is followed by a third word
do {
// If we find a third word, stop right away
if (words[(wordsFound + 2) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
words[wordsFound % THAI_LOOKAHEAD].markCurrent();
goto foundBest;
}
}
while (words[(wordsFound + 1) % THAI_LOOKAHEAD].backUp(text));
}
}
while (words[wordsFound % THAI_LOOKAHEAD].backUp(text));
foundBest:
wordLength = words[wordsFound % THAI_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// We come here after having either found a word or not. We look ahead to the
// next word. If it's not a dictionary word, we will combine it withe the word we
// just found (if there is one), but only if the preceding word does not exceed
// the threshold.
// The text iterator should now be positioned at the end of the word we found.
if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength < THAI_ROOT_COMBINE_THRESHOLD) {
// if it is a dictionary word, do nothing. If it isn't, then if there is
// no preceding word, or the non-word shares less than the minimum threshold
// of characters with a dictionary word, then scan to resynchronize
if (words[wordsFound % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
&& (wordLength == 0
|| words[wordsFound%THAI_LOOKAHEAD].longestPrefix() < THAI_PREFIX_COMBINE_THRESHOLD)) {
// Look for a plausible word boundary
//TODO: This section will need a rework for UText.
int32_t remaining = rangeEnd - (current+wordLength);
UChar32 pc = utext_current32(text);
int32_t chars = 0;
for (;;) {
utext_next32(text);
uc = utext_current32(text);
// TODO: Here we're counting on the fact that the SA languages are all
// in the BMP. This should get fixed with the UText rework.
chars += 1;
if (--remaining <= 0) {
break;
}
if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
// Maybe. See if it's in the dictionary.
// NOTE: In the original Apple code, checked that the next
// two characters after uc were not 0x0E4C THANTHAKHAT before
// checking the dictionary. That is just a performance filter,
// but it's not clear it's faster than checking the trie.
int candidates = words[(wordsFound + 1) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
utext_setNativeIndex(text, current + wordLength + chars);
if (candidates > 0) {
break;
}
}
pc = uc;
}
// Bump the word count if there wasn't already one
if (wordLength <= 0) {
wordsFound += 1;
}
// Update the length with the passed-over characters
wordLength += chars;
}
else {
// Back up to where we were for next iteration
utext_setNativeIndex(text, current+wordLength);
}
}
// Never stop before a combining mark.
int32_t currPos;
while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
utext_next32(text);
wordLength += (int32_t)utext_getNativeIndex(text) - currPos;
}
// Look ahead for possible suffixes if a dictionary word does not follow.
// We do this in code rather than using a rule so that the heuristic
// resynch continues to function. For example, one of the suffix characters
// could be a typo in the middle of a word.
if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength > 0) {
if (words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
&& fSuffixSet.contains(uc = utext_current32(text))) {
if (uc == THAI_PAIYANNOI) {
if (!fSuffixSet.contains(utext_previous32(text))) {
// Skip over previous end and PAIYANNOI
utext_next32(text);
utext_next32(text);
wordLength += 1; // Add PAIYANNOI to word
uc = utext_current32(text); // Fetch next character
}
else {
// Restore prior position
utext_next32(text);
}
}
if (uc == THAI_MAIYAMOK) {
if (utext_previous32(text) != THAI_MAIYAMOK) {
// Skip over previous end and MAIYAMOK
utext_next32(text);
utext_next32(text);
wordLength += 1; // Add MAIYAMOK to word
}
else {
// Restore prior position
utext_next32(text);
}
}
}
else {
utext_setNativeIndex(text, current+wordLength);
}
}
// Did we find a word on this iteration? If so, push it on the break stack
if (wordLength > 0) {
foundBreaks.push((current+wordLength), status);
}
}
// Don't return a break for the end of the dictionary range if there is one there.
if (foundBreaks.peeki() >= rangeEnd) {
(void) foundBreaks.popi();
wordsFound -= 1;
}
return wordsFound;
}
/*
******************************************************************
* LaoBreakEngine
*/
// How many words in a row are "good enough"?
#define LAO_LOOKAHEAD 3
// Will not combine a non-word with a preceding dictionary word longer than this
#define LAO_ROOT_COMBINE_THRESHOLD 3
// Will not combine a non-word that shares at least this much prefix with a
// dictionary word, with a preceding word
#define LAO_PREFIX_COMBINE_THRESHOLD 3
// Minimum word size
#define LAO_MIN_WORD 2
// Minimum number of characters for two words
#define LAO_MIN_WORD_SPAN (LAO_MIN_WORD * 2)
LaoBreakEngine::LaoBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
: DictionaryBreakEngine((1<<UBRK_WORD) | (1<<UBRK_LINE)),
fDictionary(adoptDictionary)
{
fLaoWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Laoo:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fLaoWordSet);
}
fMarkSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Laoo:]&[:LineBreak=SA:]&[:M:]]"), status);
fMarkSet.add(0x0020);
fEndWordSet = fLaoWordSet;
fEndWordSet.remove(0x0EC0, 0x0EC4); // prefix vowels
fBeginWordSet.add(0x0E81, 0x0EAE); // basic consonants (including holes for corresponding Thai characters)
fBeginWordSet.add(0x0EDC, 0x0EDD); // digraph consonants (no Thai equivalent)
fBeginWordSet.add(0x0EC0, 0x0EC4); // prefix vowels
// Compact for caching.
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
}
LaoBreakEngine::~LaoBreakEngine() {
delete fDictionary;
}
int32_t
LaoBreakEngine::divideUpDictionaryRange( UText *text,
int32_t rangeStart,
int32_t rangeEnd,
UStack &foundBreaks ) const {
if ((rangeEnd - rangeStart) < LAO_MIN_WORD_SPAN) {
return 0; // Not enough characters for two words
}
uint32_t wordsFound = 0;
int32_t wordLength;
int32_t current;
UErrorCode status = U_ZERO_ERROR;
PossibleWord words[LAO_LOOKAHEAD];
UChar32 uc;
utext_setNativeIndex(text, rangeStart);
while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
wordLength = 0;
// Look for candidate words at the current position
int candidates = words[wordsFound%LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
// If we found exactly one, use that
if (candidates == 1) {
wordLength = words[wordsFound % LAO_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// If there was more than one, see which one can take us forward the most words
else if (candidates > 1) {
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
do {
int wordsMatched = 1;
if (words[(wordsFound + 1) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
if (wordsMatched < 2) {
// Followed by another dictionary word; mark first word as a good candidate
words[wordsFound%LAO_LOOKAHEAD].markCurrent();
wordsMatched = 2;
}
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
// See if any of the possible second words is followed by a third word
do {
// If we find a third word, stop right away
if (words[(wordsFound + 2) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
words[wordsFound % LAO_LOOKAHEAD].markCurrent();
goto foundBest;
}
}
while (words[(wordsFound + 1) % LAO_LOOKAHEAD].backUp(text));
}
}
while (words[wordsFound % LAO_LOOKAHEAD].backUp(text));
foundBest:
wordLength = words[wordsFound % LAO_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// We come here after having either found a word or not. We look ahead to the
// next word. If it's not a dictionary word, we will combine it withe the word we
// just found (if there is one), but only if the preceding word does not exceed
// the threshold.
// The text iterator should now be positioned at the end of the word we found.
if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength < LAO_ROOT_COMBINE_THRESHOLD) {
// if it is a dictionary word, do nothing. If it isn't, then if there is
// no preceding word, or the non-word shares less than the minimum threshold
// of characters with a dictionary word, then scan to resynchronize
if (words[wordsFound % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
&& (wordLength == 0
|| words[wordsFound%LAO_LOOKAHEAD].longestPrefix() < LAO_PREFIX_COMBINE_THRESHOLD)) {
// Look for a plausible word boundary
//TODO: This section will need a rework for UText.
int32_t remaining = rangeEnd - (current+wordLength);
UChar32 pc = utext_current32(text);
int32_t chars = 0;
for (;;) {
utext_next32(text);
uc = utext_current32(text);
// TODO: Here we're counting on the fact that the SA languages are all
// in the BMP. This should get fixed with the UText rework.
chars += 1;
if (--remaining <= 0) {
break;
}
if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
// Maybe. See if it's in the dictionary.
int candidates = words[(wordsFound + 1) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
utext_setNativeIndex(text, current + wordLength + chars);
if (candidates > 0) {
break;
}
}
pc = uc;
}
// Bump the word count if there wasn't already one
if (wordLength <= 0) {
wordsFound += 1;
}
// Update the length with the passed-over characters
wordLength += chars;
}
else {
// Back up to where we were for next iteration
utext_setNativeIndex(text, current+wordLength);
}
}
// Never stop before a combining mark.
int32_t currPos;
while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
utext_next32(text);
wordLength += (int32_t)utext_getNativeIndex(text) - currPos;
}
// Look ahead for possible suffixes if a dictionary word does not follow.
// We do this in code rather than using a rule so that the heuristic
// resynch continues to function. For example, one of the suffix characters
// could be a typo in the middle of a word.
// NOT CURRENTLY APPLICABLE TO LAO
// Did we find a word on this iteration? If so, push it on the break stack
if (wordLength > 0) {
foundBreaks.push((current+wordLength), status);
}
}
// Don't return a break for the end of the dictionary range if there is one there.
if (foundBreaks.peeki() >= rangeEnd) {
(void) foundBreaks.popi();
wordsFound -= 1;
}
return wordsFound;
}
/*
******************************************************************
* KhmerBreakEngine
*/
// How many words in a row are "good enough"?
#define KHMER_LOOKAHEAD 3
// Will not combine a non-word with a preceding dictionary word longer than this
#define KHMER_ROOT_COMBINE_THRESHOLD 10
// Will not combine a non-word that shares at least this much prefix with a
// dictionary word, with a preceding word
#define KHMER_PREFIX_COMBINE_THRESHOLD 5
// Minimum word size
#define KHMER_MIN_WORD 2
// Minimum number of characters for two words
#define KHMER_MIN_WORD_SPAN (KHMER_MIN_WORD * 2)
KhmerBreakEngine::KhmerBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
: DictionaryBreakEngine((1 << UBRK_WORD) | (1 << UBRK_LINE)),
fDictionary(adoptDictionary)
{
fKhmerWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Khmr:]&[:LineBreak=SA:]]"), status);
if (U_SUCCESS(status)) {
setCharacters(fKhmerWordSet);
}
fMarkSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Khmr:]&[:LineBreak=SA:]&[:M:]]"), status);
fMarkSet.add(0x0020);
fEndWordSet = fKhmerWordSet;
fBeginWordSet.add(0x1780, 0x17B3);
//fBeginWordSet.add(0x17A3, 0x17A4); // deprecated vowels
//fEndWordSet.remove(0x17A5, 0x17A9); // Khmer independent vowels that can't end a word
//fEndWordSet.remove(0x17B2); // Khmer independent vowel that can't end a word
fEndWordSet.remove(0x17D2); // KHMER SIGN COENG that combines some following characters
//fEndWordSet.remove(0x17B6, 0x17C5); // Remove dependent vowels
// fEndWordSet.remove(0x0E31); // MAI HAN-AKAT
// fEndWordSet.remove(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
// fBeginWordSet.add(0x0E01, 0x0E2E); // KO KAI through HO NOKHUK
// fBeginWordSet.add(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
// fSuffixSet.add(THAI_PAIYANNOI);
// fSuffixSet.add(THAI_MAIYAMOK);
// Compact for caching.
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
// fSuffixSet.compact();
}
KhmerBreakEngine::~KhmerBreakEngine() {
delete fDictionary;
}
int32_t
KhmerBreakEngine::divideUpDictionaryRange( UText *text,
int32_t rangeStart,
int32_t rangeEnd,
UStack &foundBreaks ) const {
if ((rangeEnd - rangeStart) < KHMER_MIN_WORD_SPAN) {
return 0; // Not enough characters for two words
}
uint32_t wordsFound = 0;
int32_t wordLength;
int32_t current;
UErrorCode status = U_ZERO_ERROR;
PossibleWord words[KHMER_LOOKAHEAD];
UChar32 uc;
utext_setNativeIndex(text, rangeStart);
while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
wordLength = 0;
// Look for candidate words at the current position
int candidates = words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
// If we found exactly one, use that
if (candidates == 1) {
wordLength = words[wordsFound%KHMER_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// If there was more than one, see which one can take us forward the most words
else if (candidates > 1) {
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
do {
int wordsMatched = 1;
if (words[(wordsFound + 1) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
if (wordsMatched < 2) {
// Followed by another dictionary word; mark first word as a good candidate
words[wordsFound % KHMER_LOOKAHEAD].markCurrent();
wordsMatched = 2;
}
// If we're already at the end of the range, we're done
if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
goto foundBest;
}
// See if any of the possible second words is followed by a third word
do {
// If we find a third word, stop right away
if (words[(wordsFound + 2) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
words[wordsFound % KHMER_LOOKAHEAD].markCurrent();
goto foundBest;
}
}
while (words[(wordsFound + 1) % KHMER_LOOKAHEAD].backUp(text));
}
}
while (words[wordsFound % KHMER_LOOKAHEAD].backUp(text));
foundBest:
wordLength = words[wordsFound % KHMER_LOOKAHEAD].acceptMarked(text);
wordsFound += 1;
}
// We come here after having either found a word or not. We look ahead to the
// next word. If it's not a dictionary word, we will combine it with the word we
// just found (if there is one), but only if the preceding word does not exceed
// the threshold.
// The text iterator should now be positioned at the end of the word we found.
if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength < KHMER_ROOT_COMBINE_THRESHOLD) {
// if it is a dictionary word, do nothing. If it isn't, then if there is
// no preceding word, or the non-word shares less than the minimum threshold
// of characters with a dictionary word, then scan to resynchronize
if (words[wordsFound % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
&& (wordLength == 0
|| words[wordsFound % KHMER_LOOKAHEAD].longestPrefix() < KHMER_PREFIX_COMBINE_THRESHOLD)) {
// Look for a plausible word boundary
//TODO: This section will need a rework for UText.
int32_t remaining = rangeEnd - (current+wordLength);
UChar32 pc = utext_current32(text);
int32_t chars = 0;
for (;;) {
utext_next32(text);
uc = utext_current32(text);
// TODO: Here we're counting on the fact that the SA languages are all
// in the BMP. This should get fixed with the UText rework.
chars += 1;
if (--remaining <= 0) {
break;
}
if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
// Maybe. See if it's in the dictionary.
int candidates = words[(wordsFound + 1) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
utext_setNativeIndex(text, current+wordLength+chars);
if (candidates > 0) {
break;
}
}
pc = uc;
}
// Bump the word count if there wasn't already one
if (wordLength <= 0) {
wordsFound += 1;
}
// Update the length with the passed-over characters
wordLength += chars;
}
else {
// Back up to where we were for next iteration
utext_setNativeIndex(text, current+wordLength);
}
}
// Never stop before a combining mark.
int32_t currPos;
while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
utext_next32(text);
wordLength += (int32_t)utext_getNativeIndex(text) - currPos;
}
// Look ahead for possible suffixes if a dictionary word does not follow.
// We do this in code rather than using a rule so that the heuristic
// resynch continues to function. For example, one of the suffix characters
// could be a typo in the middle of a word.
// if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength > 0) {
// if (words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
// && fSuffixSet.contains(uc = utext_current32(text))) {
// if (uc == KHMER_PAIYANNOI) {
// if (!fSuffixSet.contains(utext_previous32(text))) {
// // Skip over previous end and PAIYANNOI
// utext_next32(text);
// utext_next32(text);
// wordLength += 1; // Add PAIYANNOI to word
// uc = utext_current32(text); // Fetch next character
// }
// else {
// // Restore prior position
// utext_next32(text);
// }
// }
// if (uc == KHMER_MAIYAMOK) {
// if (utext_previous32(text) != KHMER_MAIYAMOK) {
// // Skip over previous end and MAIYAMOK
// utext_next32(text);
// utext_next32(text);
// wordLength += 1; // Add MAIYAMOK to word
// }
// else {
// // Restore prior position
// utext_next32(text);
// }
// }
// }
// else {
// utext_setNativeIndex(text, current+wordLength);
// }
// }
// Did we find a word on this iteration? If so, push it on the break stack
if (wordLength > 0) {
foundBreaks.push((current+wordLength), status);
}
}
// Don't return a break for the end of the dictionary range if there is one there.
if (foundBreaks.peeki() >= rangeEnd) {
(void) foundBreaks.popi();
wordsFound -= 1;
}
return wordsFound;
}
#if !UCONFIG_NO_NORMALIZATION
/*
******************************************************************
* CjkBreakEngine
*/
static const uint32_t kuint32max = 0xFFFFFFFF;
CjkBreakEngine::CjkBreakEngine(DictionaryMatcher *adoptDictionary, LanguageType type, UErrorCode &status)
: DictionaryBreakEngine(1 << UBRK_WORD), fDictionary(adoptDictionary) {
// Korean dictionary only includes Hangul syllables
fHangulWordSet.applyPattern(UNICODE_STRING_SIMPLE("[\\uac00-\\ud7a3]"), status);
fHanWordSet.applyPattern(UNICODE_STRING_SIMPLE("[:Han:]"), status);
fKatakanaWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Katakana:]\\uff9e\\uff9f]"), status);
fHiraganaWordSet.applyPattern(UNICODE_STRING_SIMPLE("[:Hiragana:]"), status);
if (U_SUCCESS(status)) {
// handle Korean and Japanese/Chinese using different dictionaries
if (type == kKorean) {
setCharacters(fHangulWordSet);
} else { //Chinese and Japanese
UnicodeSet cjSet;
cjSet.addAll(fHanWordSet);
cjSet.addAll(fKatakanaWordSet);
cjSet.addAll(fHiraganaWordSet);
cjSet.add(0xFF70); // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK
cjSet.add(0x30FC); // KATAKANA-HIRAGANA PROLONGED SOUND MARK
setCharacters(cjSet);
}
}
}
CjkBreakEngine::~CjkBreakEngine(){
delete fDictionary;
}
// The katakanaCost values below are based on the length frequencies of all
// katakana phrases in the dictionary
static const int kMaxKatakanaLength = 8;
static const int kMaxKatakanaGroupLength = 20;
static const uint32_t maxSnlp = 255;
static inline uint32_t getKatakanaCost(int wordLength){
//TODO: fill array with actual values from dictionary!
static const uint32_t katakanaCost[kMaxKatakanaLength + 1]
= {8192, 984, 408, 240, 204, 252, 300, 372, 480};
return (wordLength > kMaxKatakanaLength) ? 8192 : katakanaCost[wordLength];
}
static inline bool isKatakana(uint16_t value) {
return (value >= 0x30A1u && value <= 0x30FEu && value != 0x30FBu) ||
(value >= 0xFF66u && value <= 0xFF9fu);
}
// A very simple helper class to streamline the buffer handling in
// divideUpDictionaryRange.
template<class T, size_t N>
class AutoBuffer {
public:
AutoBuffer(size_t size) : buffer(stackBuffer), capacity(N) {
if (size > N) {
buffer = reinterpret_cast<T*>(uprv_malloc(sizeof(T)*size));
capacity = size;
}
}
~AutoBuffer() {
if (buffer != stackBuffer)
uprv_free(buffer);
}
T* elems() {
return buffer;
}
const T& operator[] (size_t i) const {
return buffer[i];
}
T& operator[] (size_t i) {
return buffer[i];
}
// resize without copy
void resize(size_t size) {
if (size <= capacity)
return;
if (buffer != stackBuffer)
uprv_free(buffer);
buffer = reinterpret_cast<T*>(uprv_malloc(sizeof(T)*size));
capacity = size;
}
private:
T stackBuffer[N];
T* buffer;
AutoBuffer();
size_t capacity;
};
/*
* @param text A UText representing the text
* @param rangeStart The start of the range of dictionary characters
* @param rangeEnd The end of the range of dictionary characters
* @param foundBreaks Output of C array of int32_t break positions, or 0
* @return The number of breaks found
*/
int32_t
CjkBreakEngine::divideUpDictionaryRange( UText *text,
int32_t rangeStart,
int32_t rangeEnd,
UStack &foundBreaks ) const {
if (rangeStart >= rangeEnd) {
return 0;
}
const size_t defaultInputLength = 80;
size_t inputLength = rangeEnd - rangeStart;
// TODO: Replace by UnicodeString.
AutoBuffer<UChar, defaultInputLength> charString(inputLength);
// Normalize the input string and put it in normalizedText.
// The map from the indices of the normalized input to the raw
// input is kept in charPositions.
UErrorCode status = U_ZERO_ERROR;
utext_extract(text, rangeStart, rangeEnd, charString.elems(), inputLength, &status);
if (U_FAILURE(status)) {
return 0;
}
UnicodeString inputString(charString.elems(), inputLength);
// TODO: Use Normalizer2.
UNormalizationMode norm_mode = UNORM_NFKC;
UBool isNormalized =
Normalizer::quickCheck(inputString, norm_mode, status) == UNORM_YES ||
Normalizer::isNormalized(inputString, norm_mode, status);
// TODO: Replace by UVector32.
AutoBuffer<int32_t, defaultInputLength> charPositions(inputLength + 1);
int numChars = 0;
UText normalizedText = UTEXT_INITIALIZER;
// Needs to be declared here because normalizedText holds onto its buffer.
UnicodeString normalizedString;
if (isNormalized) {
int32_t index = 0;
charPositions[0] = 0;
while(index < inputString.length()) {
index = inputString.moveIndex32(index, 1);
charPositions[++numChars] = index;
}
utext_openUnicodeString(&normalizedText, &inputString, &status);
}
else {
Normalizer::normalize(inputString, norm_mode, 0, normalizedString, status);
if (U_FAILURE(status)) {
return 0;
}
charPositions.resize(normalizedString.length() + 1);
Normalizer normalizer(charString.elems(), inputLength, norm_mode);
int32_t index = 0;
charPositions[0] = 0;
while(index < normalizer.endIndex()){
/* UChar32 uc = */ normalizer.next();
charPositions[++numChars] = index = normalizer.getIndex();
}
utext_openUnicodeString(&normalizedText, &normalizedString, &status);
}
if (U_FAILURE(status)) {
return 0;
}
// From this point on, all the indices refer to the indices of
// the normalized input string.
// bestSnlp[i] is the snlp of the best segmentation of the first i
// characters in the range to be matched.
// TODO: Replace by UVector32.
AutoBuffer<uint32_t, defaultInputLength> bestSnlp(numChars + 1);
bestSnlp[0] = 0;
for(int i = 1; i <= numChars; i++) {
bestSnlp[i] = kuint32max;
}
// prev[i] is the index of the last CJK character in the previous word in
// the best segmentation of the first i characters.
// TODO: Replace by UVector32.
AutoBuffer<int, defaultInputLength> prev(numChars + 1);
for(int i = 0; i <= numChars; i++){
prev[i] = -1;
}
const size_t maxWordSize = 20;
// TODO: Replace both with UVector32.
AutoBuffer<int32_t, maxWordSize> values(numChars);
AutoBuffer<int32_t, maxWordSize> lengths(numChars);
// Dynamic programming to find the best segmentation.
bool is_prev_katakana = false;
for (int32_t i = 0; i < numChars; ++i) {
//utext_setNativeIndex(text, rangeStart + i);
utext_setNativeIndex(&normalizedText, i);
if (bestSnlp[i] == kuint32max)
continue;
int32_t count;
// limit maximum word length matched to size of current substring
int32_t maxSearchLength = (i + maxWordSize < (size_t) numChars)? maxWordSize : (numChars - i);
fDictionary->matches(&normalizedText, maxSearchLength, lengths.elems(), count, maxSearchLength, values.elems());
// if there are no single character matches found in the dictionary
// starting with this charcter, treat character as a 1-character word
// with the highest value possible, i.e. the least likely to occur.
// Exclude Korean characters from this treatment, as they should be left
// together by default.
if((count == 0 || lengths[0] != 1) &&
!fHangulWordSet.contains(utext_current32(&normalizedText))) {
values[count] = maxSnlp;
lengths[count++] = 1;
}
for (int j = 0; j < count; j++) {
uint32_t newSnlp = bestSnlp[i] + values[j];
if (newSnlp < bestSnlp[lengths[j] + i]) {
bestSnlp[lengths[j] + i] = newSnlp;
prev[lengths[j] + i] = i;
}
}
// In Japanese,
// Katakana word in single character is pretty rare. So we apply
// the following heuristic to Katakana: any continuous run of Katakana
// characters is considered a candidate word with a default cost
// specified in the katakanaCost table according to its length.
//utext_setNativeIndex(text, rangeStart + i);
utext_setNativeIndex(&normalizedText, i);
bool is_katakana = isKatakana(utext_current32(&normalizedText));
if (!is_prev_katakana && is_katakana) {
int j = i + 1;
utext_next32(&normalizedText);
// Find the end of the continuous run of Katakana characters
while (j < numChars && (j - i) < kMaxKatakanaGroupLength &&
isKatakana(utext_current32(&normalizedText))) {
utext_next32(&normalizedText);
++j;
}
if ((j - i) < kMaxKatakanaGroupLength) {
uint32_t newSnlp = bestSnlp[i] + getKatakanaCost(j - i);
if (newSnlp < bestSnlp[j]) {
bestSnlp[j] = newSnlp;
prev[j] = i;
}
}
}
is_prev_katakana = is_katakana;
}
// Start pushing the optimal offset index into t_boundary (t for tentative).
// prev[numChars] is guaranteed to be meaningful.
// We'll first push in the reverse order, i.e.,
// t_boundary[0] = numChars, and afterwards do a swap.
// TODO: Replace by UVector32.
AutoBuffer<int, maxWordSize> t_boundary(numChars + 1);
int numBreaks = 0;
// No segmentation found, set boundary to end of range
if (bestSnlp[numChars] == kuint32max) {
t_boundary[numBreaks++] = numChars;
} else {
for (int i = numChars; i > 0; i = prev[i]) {
t_boundary[numBreaks++] = i;
}
U_ASSERT(prev[t_boundary[numBreaks - 1]] == 0);
}
// Reverse offset index in t_boundary.
// Don't add a break for the start of the dictionary range if there is one
// there already.
if (foundBreaks.size() == 0 || foundBreaks.peeki() < rangeStart) {
t_boundary[numBreaks++] = 0;
}
// Now that we're done, convert positions in t_bdry[] (indices in
// the normalized input string) back to indices in the raw input string
// while reversing t_bdry and pushing values to foundBreaks.
for (int i = numBreaks-1; i >= 0; i--) {
foundBreaks.push(charPositions[t_boundary[i]] + rangeStart, status);
}
utext_close(&normalizedText);
return numBreaks;
}
#endif
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
| bsd-3-clause |
larrybradley/astropy | astropy/wcs/src/str_list_proxy.c | 11 | 6271 | /*
Author: Michael Droettboom
mdroe@stsci.edu
*/
#define NO_IMPORT_ARRAY
#include "astropy_wcs/pyutil.h"
/***************************************************************************
* List-of-strings proxy object
***************************************************************************/
static PyTypeObject PyStrListProxyType;
typedef struct {
PyObject_HEAD
/*@null@*/ /*@shared@*/ PyObject* pyobject;
Py_ssize_t size;
Py_ssize_t maxsize;
char (*array)[72];
} PyStrListProxy;
static void
PyStrListProxy_dealloc(
PyStrListProxy* self) {
PyObject_GC_UnTrack(self);
Py_XDECREF(self->pyobject);
Py_TYPE(self)->tp_free((PyObject*)self);
}
/*@null@*/ static PyObject *
PyStrListProxy_new(
PyTypeObject* type,
/*@unused@*/ PyObject* args,
/*@unused@*/ PyObject* kwds) {
PyStrListProxy* self = NULL;
self = (PyStrListProxy*)type->tp_alloc(type, 0);
if (self != NULL) {
self->pyobject = NULL;
}
return (PyObject*)self;
}
static int
PyStrListProxy_traverse(
PyStrListProxy* self,
visitproc visit,
void *arg) {
Py_VISIT(self->pyobject);
return 0;
}
static int
PyStrListProxy_clear(
PyStrListProxy *self) {
Py_CLEAR(self->pyobject);
return 0;
}
/*@null@*/ PyObject *
PyStrListProxy_New(
/*@shared@*/ PyObject* owner,
Py_ssize_t size,
Py_ssize_t maxsize,
char (*array)[72]) {
PyStrListProxy* self = NULL;
if (maxsize == 0) {
maxsize = 68;
}
self = (PyStrListProxy*)PyStrListProxyType.tp_alloc(&PyStrListProxyType, 0);
if (self == NULL) {
return NULL;
}
Py_XINCREF(owner);
self->pyobject = owner;
self->size = size;
self->maxsize = maxsize;
self->array = array;
return (PyObject*)self;
}
static Py_ssize_t
PyStrListProxy_len(
PyStrListProxy* self) {
return self->size;
}
/*@null@*/ static PyObject*
PyStrListProxy_getitem(
PyStrListProxy* self,
Py_ssize_t index) {
if (index >= self->size || index < 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
return get_string("string", self->array[index]);
}
static int
PyStrListProxy_setitem(
PyStrListProxy* self,
Py_ssize_t index,
PyObject* arg) {
if (index >= self->size || index < 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
return set_string("string", arg, self->array[index], self->maxsize);
}
/*@null@*/ PyObject*
str_list_proxy_repr(
char (*array)[72],
Py_ssize_t size,
Py_ssize_t maxsize) {
char* buffer = NULL;
char* wp = NULL;
char* rp = NULL;
Py_ssize_t i = 0;
Py_ssize_t j = 0;
PyObject* result = NULL;
/* These are in descending order, so we can exit the loop quickly. They
are in pairs: (char_to_escape, char_escaped) */
const char* escapes = "\\\\''\rr\ff\vv\nn\tt\bb\aa";
const char* e = NULL;
char next_char = '\0';
/* Overallocating to allow for escaped characters */
buffer = malloc((size_t)size*maxsize*2 + 2);
if (buffer == NULL) {
PyErr_SetString(PyExc_MemoryError, "Could not allocate memory.");
return NULL;
}
wp = buffer;
*wp++ = '[';
for (i = 0; i < size; ++i) {
*wp++ = '\'';
rp = array[i];
for (j = 0; j < maxsize && *rp != '\0'; ++j) {
/* Check if this character should be escaped */
e = escapes;
next_char = *rp++;
do {
if (next_char > *e) {
break;
} else if (next_char == *e) {
*wp++ = '\\';
next_char = *(++e);
break;
} else {
e += 2;
}
} while (*e != '\0');
*wp++ = next_char;
}
*wp++ = '\'';
/* Add a comma for all but the last one */
if (i != size - 1) {
*wp++ = ',';
*wp++ = ' ';
}
}
*wp++ = ']';
*wp++ = '\0';
result = PyUnicode_FromString(buffer);
free(buffer);
return result;
}
/*@null@*/ static PyObject*
PyStrListProxy_repr(
PyStrListProxy* self) {
return str_list_proxy_repr(self->array, self->size, self->maxsize);
}
static PySequenceMethods PyStrListProxy_sequence_methods = {
(lenfunc)PyStrListProxy_len,
NULL,
NULL,
(ssizeargfunc)PyStrListProxy_getitem,
NULL,
(ssizeobjargproc)PyStrListProxy_setitem,
NULL,
NULL,
NULL,
NULL
};
static PyTypeObject PyStrListProxyType = {
PyVarObject_HEAD_INIT(NULL, 0)
"astropy.wcs.StrListProxy", /*tp_name*/
sizeof(PyStrListProxy), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyStrListProxy_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
(reprfunc)PyStrListProxy_repr, /*tp_repr*/
0, /*tp_as_number*/
&PyStrListProxy_sequence_methods, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
(reprfunc)PyStrListProxy_repr, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
0, /* tp_doc */
(traverseproc)PyStrListProxy_traverse, /* tp_traverse */
(inquiry)PyStrListProxy_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyStrListProxy_new, /* tp_new */
};
int
_setup_str_list_proxy_type(
/*@unused@*/ PyObject* m) {
if (PyType_Ready(&PyStrListProxyType) < 0) {
return 1;
}
return 0;
}
| bsd-3-clause |
guorendong/iridium-browser-ubuntu | third_party/mesa/src/src/gallium/drivers/svga/svga_pipe_query.c | 12 | 8675 | /**********************************************************
* Copyright 2008-2009 VMware, Inc. 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.
*
**********************************************************/
#include "pipe/p_state.h"
#include "pipe/p_context.h"
#include "util/u_memory.h"
#include "svga_cmd.h"
#include "svga_context.h"
#include "svga_screen.h"
#include "svga_resource_buffer.h"
#include "svga_winsys.h"
#include "svga_debug.h"
/* Fixme: want a public base class for all pipe structs, even if there
* isn't much in them.
*/
struct pipe_query {
int dummy;
};
struct svga_query {
struct pipe_query base;
SVGA3dQueryType type;
struct svga_winsys_buffer *hwbuf;
volatile SVGA3dQueryResult *queryResult;
struct pipe_fence_handle *fence;
};
/***********************************************************************
* Inline conversion functions. These are better-typed than the
* macros used previously:
*/
static INLINE struct svga_query *
svga_query( struct pipe_query *q )
{
return (struct svga_query *)q;
}
static boolean svga_get_query_result(struct pipe_context *pipe,
struct pipe_query *q,
boolean wait,
union pipe_query_result *result);
static struct pipe_query *svga_create_query( struct pipe_context *pipe,
unsigned query_type )
{
struct svga_context *svga = svga_context( pipe );
struct svga_screen *svgascreen = svga_screen(pipe->screen);
struct svga_winsys_screen *sws = svgascreen->sws;
struct svga_query *sq;
SVGA_DBG(DEBUG_QUERY, "%s\n", __FUNCTION__);
sq = CALLOC_STRUCT(svga_query);
if (!sq)
goto no_sq;
sq->type = SVGA3D_QUERYTYPE_OCCLUSION;
sq->hwbuf = svga_winsys_buffer_create(svga,
1,
SVGA_BUFFER_USAGE_PINNED,
sizeof *sq->queryResult);
if(!sq->hwbuf)
goto no_hwbuf;
sq->queryResult = (SVGA3dQueryResult *)sws->buffer_map(sws,
sq->hwbuf,
PIPE_TRANSFER_WRITE);
if(!sq->queryResult)
goto no_query_result;
sq->queryResult->totalSize = sizeof *sq->queryResult;
sq->queryResult->state = SVGA3D_QUERYSTATE_NEW;
/*
* We request the buffer to be pinned and assume it is always mapped.
*
* The reason is that we don't want to wait for fences when checking the
* query status.
*/
sws->buffer_unmap(sws, sq->hwbuf);
return &sq->base;
no_query_result:
sws->buffer_destroy(sws, sq->hwbuf);
no_hwbuf:
FREE(sq);
no_sq:
return NULL;
}
static void svga_destroy_query(struct pipe_context *pipe,
struct pipe_query *q)
{
struct svga_screen *svgascreen = svga_screen(pipe->screen);
struct svga_winsys_screen *sws = svgascreen->sws;
struct svga_query *sq = svga_query( q );
SVGA_DBG(DEBUG_QUERY, "%s\n", __FUNCTION__);
sws->buffer_destroy(sws, sq->hwbuf);
sws->fence_reference(sws, &sq->fence, NULL);
FREE(sq);
}
static void svga_begin_query(struct pipe_context *pipe,
struct pipe_query *q)
{
struct svga_screen *svgascreen = svga_screen(pipe->screen);
struct svga_winsys_screen *sws = svgascreen->sws;
struct svga_context *svga = svga_context( pipe );
struct svga_query *sq = svga_query( q );
enum pipe_error ret;
SVGA_DBG(DEBUG_QUERY, "%s\n", __FUNCTION__);
assert(!svga->sq);
/* Need to flush out buffered drawing commands so that they don't
* get counted in the query results.
*/
svga_hwtnl_flush_retry(svga);
if(sq->queryResult->state == SVGA3D_QUERYSTATE_PENDING) {
/* The application doesn't care for the pending query result. We cannot
* let go the existing buffer and just get a new one because its storage
* may be reused for other purposes and clobbered by the host when it
* determines the query result. So the only option here is to wait for
* the existing query's result -- not a big deal, given that no sane
* application would do this.
*/
uint64_t result;
svga_get_query_result(pipe, q, TRUE, (void*)&result);
assert(sq->queryResult->state != SVGA3D_QUERYSTATE_PENDING);
}
sq->queryResult->state = SVGA3D_QUERYSTATE_NEW;
sws->fence_reference(sws, &sq->fence, NULL);
ret = SVGA3D_BeginQuery(svga->swc, sq->type);
if(ret != PIPE_OK) {
svga_context_flush(svga, NULL);
ret = SVGA3D_BeginQuery(svga->swc, sq->type);
assert(ret == PIPE_OK);
}
svga->sq = sq;
}
static void svga_end_query(struct pipe_context *pipe,
struct pipe_query *q)
{
struct svga_context *svga = svga_context( pipe );
struct svga_query *sq = svga_query( q );
enum pipe_error ret;
SVGA_DBG(DEBUG_QUERY, "%s\n", __FUNCTION__);
assert(svga->sq == sq);
svga_hwtnl_flush_retry(svga);
/* Set to PENDING before sending EndQuery. */
sq->queryResult->state = SVGA3D_QUERYSTATE_PENDING;
ret = SVGA3D_EndQuery( svga->swc, sq->type, sq->hwbuf);
if(ret != PIPE_OK) {
svga_context_flush(svga, NULL);
ret = SVGA3D_EndQuery( svga->swc, sq->type, sq->hwbuf);
assert(ret == PIPE_OK);
}
/* TODO: Delay flushing. We don't really need to flush here, just ensure
* that there is one flush before svga_get_query_result attempts to get the
* result */
svga_context_flush(svga, NULL);
svga->sq = NULL;
}
static boolean svga_get_query_result(struct pipe_context *pipe,
struct pipe_query *q,
boolean wait,
union pipe_query_result *vresult)
{
struct svga_context *svga = svga_context( pipe );
struct svga_screen *svgascreen = svga_screen( pipe->screen );
struct svga_winsys_screen *sws = svgascreen->sws;
struct svga_query *sq = svga_query( q );
SVGA3dQueryState state;
uint64_t *result = (uint64_t*)vresult;
SVGA_DBG(DEBUG_QUERY, "%s wait: %d\n", __FUNCTION__);
/* The query status won't be updated by the host unless
* SVGA_3D_CMD_WAIT_FOR_QUERY is emitted. Unfortunately this will cause a
* synchronous wait on the host */
if(!sq->fence) {
enum pipe_error ret;
ret = SVGA3D_WaitForQuery( svga->swc, sq->type, sq->hwbuf);
if(ret != PIPE_OK) {
svga_context_flush(svga, NULL);
ret = SVGA3D_WaitForQuery( svga->swc, sq->type, sq->hwbuf);
assert(ret == PIPE_OK);
}
svga_context_flush(svga, &sq->fence);
assert(sq->fence);
}
state = sq->queryResult->state;
if(state == SVGA3D_QUERYSTATE_PENDING) {
if(!wait)
return FALSE;
sws->fence_finish(sws, sq->fence, SVGA_FENCE_FLAG_QUERY);
state = sq->queryResult->state;
}
assert(state == SVGA3D_QUERYSTATE_SUCCEEDED ||
state == SVGA3D_QUERYSTATE_FAILED);
*result = (uint64_t)sq->queryResult->result32;
SVGA_DBG(DEBUG_QUERY, "%s result %d\n", __FUNCTION__, (unsigned)*result);
return TRUE;
}
void svga_init_query_functions( struct svga_context *svga )
{
svga->pipe.create_query = svga_create_query;
svga->pipe.destroy_query = svga_destroy_query;
svga->pipe.begin_query = svga_begin_query;
svga->pipe.end_query = svga_end_query;
svga->pipe.get_query_result = svga_get_query_result;
}
| bsd-3-clause |
OptiPop/external_chromium_org_third_party_skia | tests/SurfaceTest.cpp | 15 | 19271 | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCanvas.h"
#include "SkData.h"
#include "SkDecodingImageGenerator.h"
#include "SkImageEncoder.h"
#include "SkRRect.h"
#include "SkSurface.h"
#include "SkUtils.h"
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#else
class GrContextFactory;
class GrContext;
#endif
enum SurfaceType {
kRaster_SurfaceType,
kRasterDirect_SurfaceType,
kGpu_SurfaceType,
kGpuScratch_SurfaceType,
};
static void release_storage(void* pixels, void* context) {
SkASSERT(pixels == context);
sk_free(pixels);
}
static SkSurface* createSurface(SurfaceType surfaceType, GrContext* context,
SkImageInfo* requestedInfo = NULL) {
static const SkImageInfo info = SkImageInfo::MakeN32Premul(10, 10);
if (requestedInfo) {
*requestedInfo = info;
}
switch (surfaceType) {
case kRaster_SurfaceType:
return SkSurface::NewRaster(info);
case kRasterDirect_SurfaceType: {
const size_t rowBytes = info.minRowBytes();
void* storage = sk_malloc_throw(info.getSafeSize(rowBytes));
return SkSurface::NewRasterDirectReleaseProc(info, storage, rowBytes,
release_storage, storage);
}
case kGpu_SurfaceType:
#if SK_SUPPORT_GPU
return context ? SkSurface::NewRenderTarget(context, info, 0, NULL) : NULL;
#endif
break;
case kGpuScratch_SurfaceType:
#if SK_SUPPORT_GPU
return context ? SkSurface::NewScratchRenderTarget(context, info) : NULL;
#endif
break;
}
return NULL;
}
enum ImageType {
kRasterCopy_ImageType,
kRasterData_ImageType,
kGpu_ImageType,
kCodec_ImageType,
};
static void test_image(skiatest::Reporter* reporter) {
SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
size_t rowBytes = info.minRowBytes();
size_t size = info.getSafeSize(rowBytes);
SkData* data = SkData::NewUninitialized(size);
REPORTER_ASSERT(reporter, 1 == data->getRefCnt());
SkImage* image = SkImage::NewRasterData(info, data, rowBytes);
REPORTER_ASSERT(reporter, 2 == data->getRefCnt());
image->unref();
REPORTER_ASSERT(reporter, 1 == data->getRefCnt());
data->unref();
}
static SkImage* createImage(ImageType imageType, GrContext* context,
SkColor color) {
const SkPMColor pmcolor = SkPreMultiplyColor(color);
const SkImageInfo info = SkImageInfo::MakeN32Premul(10, 10);
const size_t rowBytes = info.minRowBytes();
const size_t size = rowBytes * info.height();
SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
void* addr = data->writable_data();
sk_memset32((SkPMColor*)addr, pmcolor, SkToInt(size >> 2));
switch (imageType) {
case kRasterCopy_ImageType:
return SkImage::NewRasterCopy(info, addr, rowBytes);
case kRasterData_ImageType:
return SkImage::NewRasterData(info, data, rowBytes);
case kGpu_ImageType:
return NULL; // TODO
case kCodec_ImageType: {
SkBitmap bitmap;
bitmap.installPixels(info, addr, rowBytes);
SkAutoTUnref<SkData> src(
SkImageEncoder::EncodeData(bitmap, SkImageEncoder::kPNG_Type,
100));
return SkImage::NewFromGenerator(
SkDecodingImageGenerator::Create(data, SkDecodingImageGenerator::Options()));
}
}
SkASSERT(false);
return NULL;
}
static void test_imagepeek(skiatest::Reporter* reporter) {
static const struct {
ImageType fType;
bool fPeekShouldSucceed;
} gRec[] = {
{ kRasterCopy_ImageType, true },
{ kRasterData_ImageType, true },
{ kGpu_ImageType, false },
{ kCodec_ImageType, false },
};
const SkColor color = SK_ColorRED;
const SkPMColor pmcolor = SkPreMultiplyColor(color);
for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
SkImageInfo info;
size_t rowBytes;
SkAutoTUnref<SkImage> image(createImage(gRec[i].fType, NULL, color));
if (!image.get()) {
continue; // gpu may not be enabled
}
const void* addr = image->peekPixels(&info, &rowBytes);
bool success = SkToBool(addr);
REPORTER_ASSERT(reporter, gRec[i].fPeekShouldSucceed == success);
if (success) {
REPORTER_ASSERT(reporter, 10 == info.width());
REPORTER_ASSERT(reporter, 10 == info.height());
REPORTER_ASSERT(reporter, kN32_SkColorType == info.colorType());
REPORTER_ASSERT(reporter, kPremul_SkAlphaType == info.alphaType() ||
kOpaque_SkAlphaType == info.alphaType());
REPORTER_ASSERT(reporter, info.minRowBytes() <= rowBytes);
REPORTER_ASSERT(reporter, pmcolor == *(const SkPMColor*)addr);
}
}
}
static void test_canvaspeek(skiatest::Reporter* reporter,
GrContextFactory* factory) {
static const struct {
SurfaceType fType;
bool fPeekShouldSucceed;
} gRec[] = {
{ kRaster_SurfaceType, true },
{ kRasterDirect_SurfaceType, true },
#if SK_SUPPORT_GPU
{ kGpu_SurfaceType, false },
{ kGpuScratch_SurfaceType, false },
#endif
};
const SkColor color = SK_ColorRED;
const SkPMColor pmcolor = SkPreMultiplyColor(color);
int cnt;
#if SK_SUPPORT_GPU
cnt = GrContextFactory::kGLContextTypeCnt;
#else
cnt = 1;
#endif
for (int i= 0; i < cnt; ++i) {
GrContext* context = NULL;
#if SK_SUPPORT_GPU
GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType) i;
if (!GrContextFactory::IsRenderingGLContext(glCtxType)) {
continue;
}
context = factory->get(glCtxType);
if (NULL == context) {
continue;
}
#endif
for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
SkImageInfo info, requestInfo;
size_t rowBytes;
SkAutoTUnref<SkSurface> surface(createSurface(gRec[i].fType, context,
&requestInfo));
surface->getCanvas()->clear(color);
const void* addr = surface->getCanvas()->peekPixels(&info, &rowBytes);
bool success = SkToBool(addr);
REPORTER_ASSERT(reporter, gRec[i].fPeekShouldSucceed == success);
SkImageInfo info2;
size_t rb2;
const void* addr2 = surface->peekPixels(&info2, &rb2);
if (success) {
REPORTER_ASSERT(reporter, requestInfo == info);
REPORTER_ASSERT(reporter, requestInfo.minRowBytes() <= rowBytes);
REPORTER_ASSERT(reporter, pmcolor == *(const SkPMColor*)addr);
REPORTER_ASSERT(reporter, addr2 == addr);
REPORTER_ASSERT(reporter, info2 == info);
REPORTER_ASSERT(reporter, rb2 == rowBytes);
} else {
REPORTER_ASSERT(reporter, NULL == addr2);
}
}
}
}
static void TestSurfaceCopyOnWrite(skiatest::Reporter* reporter, SurfaceType surfaceType,
GrContext* context) {
// Verify that the right canvas commands trigger a copy on write
SkSurface* surface = createSurface(surfaceType, context);
SkAutoTUnref<SkSurface> aur_surface(surface);
SkCanvas* canvas = surface->getCanvas();
const SkRect testRect =
SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(4), SkIntToScalar(5));
SkMatrix testMatrix;
testMatrix.reset();
testMatrix.setScale(SkIntToScalar(2), SkIntToScalar(3));
SkPath testPath;
testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(2), SkIntToScalar(1)));
const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1);
SkRegion testRegion;
testRegion.setRect(testIRect);
const SkColor testColor = 0x01020304;
const SkPaint testPaint;
const SkPoint testPoints[3] = {
{SkIntToScalar(0), SkIntToScalar(0)},
{SkIntToScalar(2), SkIntToScalar(1)},
{SkIntToScalar(0), SkIntToScalar(2)}
};
const size_t testPointCount = 3;
SkBitmap testBitmap;
testBitmap.allocN32Pixels(10, 10);
testBitmap.eraseColor(0);
SkRRect testRRect;
testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1);
SkString testText("Hello World");
const SkPoint testPoints2[] = {
{ SkIntToScalar(0), SkIntToScalar(1) },
{ SkIntToScalar(1), SkIntToScalar(1) },
{ SkIntToScalar(2), SkIntToScalar(1) },
{ SkIntToScalar(3), SkIntToScalar(1) },
{ SkIntToScalar(4), SkIntToScalar(1) },
{ SkIntToScalar(5), SkIntToScalar(1) },
{ SkIntToScalar(6), SkIntToScalar(1) },
{ SkIntToScalar(7), SkIntToScalar(1) },
{ SkIntToScalar(8), SkIntToScalar(1) },
{ SkIntToScalar(9), SkIntToScalar(1) },
{ SkIntToScalar(10), SkIntToScalar(1) },
};
#define EXPECT_COPY_ON_WRITE(command) \
{ \
SkImage* imageBefore = surface->newImageSnapshot(); \
SkAutoTUnref<SkImage> aur_before(imageBefore); \
canvas-> command ; \
SkImage* imageAfter = surface->newImageSnapshot(); \
SkAutoTUnref<SkImage> aur_after(imageAfter); \
REPORTER_ASSERT(reporter, imageBefore != imageAfter); \
}
EXPECT_COPY_ON_WRITE(clear(testColor))
EXPECT_COPY_ON_WRITE(drawPaint(testPaint))
EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \
testPaint))
EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint))
EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint))
EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint))
EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint))
EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0))
EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, NULL, testRect))
EXPECT_COPY_ON_WRITE(drawBitmapMatrix(testBitmap, testMatrix, NULL))
EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, NULL))
EXPECT_COPY_ON_WRITE(drawSprite(testBitmap, 0, 0, NULL))
EXPECT_COPY_ON_WRITE(drawText(testText.c_str(), testText.size(), 0, 1, testPaint))
EXPECT_COPY_ON_WRITE(drawPosText(testText.c_str(), testText.size(), testPoints2, \
testPaint))
EXPECT_COPY_ON_WRITE(drawTextOnPath(testText.c_str(), testText.size(), testPath, NULL, \
testPaint))
}
static void TestSurfaceWritableAfterSnapshotRelease(skiatest::Reporter* reporter,
SurfaceType surfaceType,
GrContext* context) {
// This test succeeds by not triggering an assertion.
// The test verifies that the surface remains writable (usable) after
// acquiring and releasing a snapshot without triggering a copy on write.
SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context));
SkCanvas* canvas = surface->getCanvas();
canvas->clear(1);
surface->newImageSnapshot()->unref(); // Create and destroy SkImage
canvas->clear(2); // Must not assert internally
}
#if SK_SUPPORT_GPU
static void TestSurfaceInCache(skiatest::Reporter* reporter,
SurfaceType surfaceType,
GrContext* context) {
context->freeGpuResources();
int resourceCount;
context->getResourceCacheUsage(&resourceCount, NULL);
REPORTER_ASSERT(reporter, 0 == resourceCount);
SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context));
// Note: the stencil buffer is always cached, so kGpu_SurfaceType uses
// one cached resource, and kGpuScratch_SurfaceType uses two.
int expectedCachedResources = surfaceType == kGpuScratch_SurfaceType ? 2 : 1;
context->getResourceCacheUsage(&resourceCount, NULL);
REPORTER_ASSERT(reporter, expectedCachedResources == resourceCount);
// Verify that all the cached resources are locked in cache.
context->freeGpuResources();
context->getResourceCacheUsage(&resourceCount, NULL);
REPORTER_ASSERT(reporter, expectedCachedResources == resourceCount);
// Verify that all the cached resources are unlocked upon surface release
surface.reset(0);
context->freeGpuResources();
context->getResourceCacheUsage(&resourceCount, NULL);
REPORTER_ASSERT(reporter, 0 == resourceCount);
}
static void Test_crbug263329(skiatest::Reporter* reporter,
SurfaceType surfaceType,
GrContext* context) {
// This is a regression test for crbug.com/263329
// Bug was caused by onCopyOnWrite releasing the old surface texture
// back to the scratch texture pool even though the texture is used
// by and active SkImage_Gpu.
SkAutoTUnref<SkSurface> surface1(createSurface(surfaceType, context));
SkAutoTUnref<SkSurface> surface2(createSurface(surfaceType, context));
SkCanvas* canvas1 = surface1->getCanvas();
SkCanvas* canvas2 = surface2->getCanvas();
canvas1->clear(1);
SkAutoTUnref<SkImage> image1(surface1->newImageSnapshot());
// Trigger copy on write, new backing is a scratch texture
canvas1->clear(2);
SkAutoTUnref<SkImage> image2(surface1->newImageSnapshot());
// Trigger copy on write, old backing should not be returned to scratch
// pool because it is held by image2
canvas1->clear(3);
canvas2->clear(4);
SkAutoTUnref<SkImage> image3(surface2->newImageSnapshot());
// Trigger copy on write on surface2. The new backing store should not
// be recycling a texture that is held by an existing image.
canvas2->clear(5);
SkAutoTUnref<SkImage> image4(surface2->newImageSnapshot());
REPORTER_ASSERT(reporter, image4->getTexture() != image3->getTexture());
// The following assertion checks crbug.com/263329
REPORTER_ASSERT(reporter, image4->getTexture() != image2->getTexture());
REPORTER_ASSERT(reporter, image4->getTexture() != image1->getTexture());
REPORTER_ASSERT(reporter, image3->getTexture() != image2->getTexture());
REPORTER_ASSERT(reporter, image3->getTexture() != image1->getTexture());
REPORTER_ASSERT(reporter, image2->getTexture() != image1->getTexture());
}
static void TestGetTexture(skiatest::Reporter* reporter,
SurfaceType surfaceType,
GrContext* context) {
SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context));
SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
GrTexture* texture = image->getTexture();
if (surfaceType == kGpu_SurfaceType || surfaceType == kGpuScratch_SurfaceType) {
REPORTER_ASSERT(reporter, texture);
REPORTER_ASSERT(reporter, 0 != texture->getTextureHandle());
} else {
REPORTER_ASSERT(reporter, NULL == texture);
}
surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
REPORTER_ASSERT(reporter, image->getTexture() == texture);
}
#endif
static void TestSurfaceNoCanvas(skiatest::Reporter* reporter,
SurfaceType surfaceType,
GrContext* context,
SkSurface::ContentChangeMode mode) {
// Verifies the robustness of SkSurface for handling use cases where calls
// are made before a canvas is created.
{
// Test passes by not asserting
SkSurface* surface = createSurface(surfaceType, context);
SkAutoTUnref<SkSurface> aur_surface(surface);
surface->notifyContentWillChange(mode);
SkDEBUGCODE(surface->validate();)
}
{
SkSurface* surface = createSurface(surfaceType, context);
SkAutoTUnref<SkSurface> aur_surface(surface);
SkImage* image1 = surface->newImageSnapshot();
SkAutoTUnref<SkImage> aur_image1(image1);
SkDEBUGCODE(image1->validate();)
SkDEBUGCODE(surface->validate();)
surface->notifyContentWillChange(mode);
SkDEBUGCODE(image1->validate();)
SkDEBUGCODE(surface->validate();)
SkImage* image2 = surface->newImageSnapshot();
SkAutoTUnref<SkImage> aur_image2(image2);
SkDEBUGCODE(image2->validate();)
SkDEBUGCODE(surface->validate();)
REPORTER_ASSERT(reporter, image1 != image2);
}
}
DEF_GPUTEST(Surface, reporter, factory) {
test_image(reporter);
TestSurfaceCopyOnWrite(reporter, kRaster_SurfaceType, NULL);
TestSurfaceWritableAfterSnapshotRelease(reporter, kRaster_SurfaceType, NULL);
TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kDiscard_ContentChangeMode);
TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kRetain_ContentChangeMode);
test_imagepeek(reporter);
test_canvaspeek(reporter, factory);
#if SK_SUPPORT_GPU
TestGetTexture(reporter, kRaster_SurfaceType, NULL);
if (factory) {
for (int i= 0; i < GrContextFactory::kGLContextTypeCnt; ++i) {
GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType) i;
if (!GrContextFactory::IsRenderingGLContext(glCtxType)) {
continue;
}
GrContext* context = factory->get(glCtxType);
if (context) {
TestSurfaceInCache(reporter, kGpu_SurfaceType, context);
TestSurfaceInCache(reporter, kGpuScratch_SurfaceType, context);
Test_crbug263329(reporter, kGpu_SurfaceType, context);
Test_crbug263329(reporter, kGpuScratch_SurfaceType, context);
TestSurfaceCopyOnWrite(reporter, kGpu_SurfaceType, context);
TestSurfaceCopyOnWrite(reporter, kGpuScratch_SurfaceType, context);
TestSurfaceWritableAfterSnapshotRelease(reporter, kGpu_SurfaceType, context);
TestSurfaceWritableAfterSnapshotRelease(reporter, kGpuScratch_SurfaceType, context);
TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode);
TestSurfaceNoCanvas(reporter, kGpuScratch_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode);
TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kRetain_ContentChangeMode);
TestSurfaceNoCanvas(reporter, kGpuScratch_SurfaceType, context, SkSurface::kRetain_ContentChangeMode);
TestGetTexture(reporter, kGpu_SurfaceType, context);
TestGetTexture(reporter, kGpuScratch_SurfaceType, context);
}
}
}
#endif
}
| bsd-3-clause |
temasek/android_external_chromium_org_third_party_WebKit | Source/core/css/CSSRuleList.cpp | 17 | 1480 | /**
* (C) 1999-2003 Lars Knoll (knoll@kde.org)
* (C) 2002-2003 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2002, 2005, 2006, 2012 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/css/CSSRuleList.h"
#include "core/css/CSSRule.h"
namespace blink {
CSSRuleList::~CSSRuleList()
{
}
StaticCSSRuleList::StaticCSSRuleList()
#if !ENABLE(OILPAN)
: m_refCount(1)
#endif
{
}
StaticCSSRuleList::~StaticCSSRuleList()
{
}
#if !ENABLE(OILPAN)
void StaticCSSRuleList::deref()
{
ASSERT(m_refCount);
if (!--m_refCount)
delete this;
}
#endif
void StaticCSSRuleList::trace(Visitor* visitor)
{
visitor->trace(m_rules);
CSSRuleList::trace(visitor);
}
} // namespace blink
| bsd-3-clause |
castoryan/OpenBLAS | kernel/generic/geadd.c | 17 | 2188 | /***************************************************************************
Copyright (c) 2013, The OpenBLAS 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. Neither the name of the OpenBLAS project 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 OPENBLAS PROJECT 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 "common.h"
int CNAME(BLASLONG rows, BLASLONG cols, FLOAT alpha, FLOAT *a, BLASLONG lda, FLOAT beta, FLOAT *b, BLASLONG ldb)
{
BLASLONG i;
FLOAT *aptr,*bptr;
if ( rows <= 0 ) return(0);
if ( cols <= 0 ) return(0);
aptr = a;
bptr = b;
if ( alpha == 0.0 )
{
for ( i=0; i<cols ; i++ )
{
SCAL_K(rows, 0,0, beta, bptr, 1, NULL, 0,NULL,0);
bptr+=ldb;
}
return(0);
}
for (i = 0; i < cols; i++) {
AXPBY_K(rows, alpha, aptr, 1, beta, bptr, 1);
aptr += lda;
bptr += ldb;
}
return(0);
}
| bsd-3-clause |
honnibal/blaze-lib | blazetest/src/mathtest/dmatsmatsub/M2x2bMCa.cpp | 19 | 3789 | //=================================================================================================
/*!
// \file src/mathtest/dmatsmatsub/M2x2bMCa.cpp
// \brief Source file for the M2x2bMCa dense matrix/sparse matrix subtraction math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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 HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M2x2bMCa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StaticMatrix<TypeB,2UL,2UL> M2x2b;
typedef blaze::CompressedMatrix<TypeA> MCa;
// Creator type definitions
typedef blazetest::Creator<M2x2b> CM2x2b;
typedef blazetest::Creator<MCa> CMCa;
// Running the tests
for( size_t i=0UL; i<=4UL; ++i ) {
RUN_DMATSMATSUB_OPERATION_TEST( CM2x2b(), CMCa( 2UL, 2UL, i ) );
}
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| bsd-3-clause |
boulzordev/android_external_skia | src/image/SkSurface_Gpu.cpp | 23 | 4610 | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkSurface_Gpu.h"
#include "SkCanvas.h"
#include "SkGpuDevice.h"
#include "SkImage_Base.h"
#include "SkImage_Gpu.h"
#include "SkImagePriv.h"
#include "SkSurface_Base.h"
#if SK_SUPPORT_GPU
///////////////////////////////////////////////////////////////////////////////
SkSurface_Gpu::SkSurface_Gpu(SkGpuDevice* device)
: INHERITED(device->width(), device->height(), &device->surfaceProps())
, fDevice(SkRef(device)) {
}
SkSurface_Gpu::~SkSurface_Gpu() {
fDevice->unref();
}
SkCanvas* SkSurface_Gpu::onNewCanvas() {
SkCanvas::InitFlags flags = SkCanvas::kDefault_InitFlags;
// When we think this works...
// flags |= SkCanvas::kConservativeRasterClip_InitFlag;
return SkNEW_ARGS(SkCanvas, (fDevice, &this->props(), flags));
}
SkSurface* SkSurface_Gpu::onNewSurface(const SkImageInfo& info) {
GrRenderTarget* rt = fDevice->accessRenderTarget();
int sampleCount = rt->numSamples();
// TODO: Make caller specify this (change virtual signature of onNewSurface).
static const Budgeted kBudgeted = kNo_Budgeted;
return SkSurface::NewRenderTarget(fDevice->context(), kBudgeted, info, sampleCount,
&this->props());
}
SkImage* SkSurface_Gpu::onNewImageSnapshot(Budgeted budgeted) {
const SkImageInfo info = fDevice->imageInfo();
const int sampleCount = fDevice->accessRenderTarget()->numSamples();
SkImage* image = NULL;
GrTexture* tex = fDevice->accessRenderTarget()->asTexture();
if (tex) {
image = SkNEW_ARGS(SkImage_Gpu,
(info.width(), info.height(), info.alphaType(),
tex, sampleCount, budgeted));
}
if (image) {
as_IB(image)->initWithProps(this->props());
}
return image;
}
void SkSurface_Gpu::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y,
const SkPaint* paint) {
canvas->drawBitmap(fDevice->accessBitmap(false), x, y, paint);
}
// Create a new render target and, if necessary, copy the contents of the old
// render target into it. Note that this flushes the SkGpuDevice but
// doesn't force an OpenGL flush.
void SkSurface_Gpu::onCopyOnWrite(ContentChangeMode mode) {
GrRenderTarget* rt = fDevice->accessRenderTarget();
// are we sharing our render target with the image? Note this call should never create a new
// image because onCopyOnWrite is only called when there is a cached image.
SkImage* image = this->getCachedImage(kNo_Budgeted);
SkASSERT(image);
if (rt->asTexture() == image->getTexture()) {
this->fDevice->replaceRenderTarget(SkSurface::kRetain_ContentChangeMode == mode);
SkTextureImageApplyBudgetedDecision(image);
} else if (kDiscard_ContentChangeMode == mode) {
this->SkSurface_Gpu::onDiscard();
}
}
void SkSurface_Gpu::onDiscard() {
fDevice->accessRenderTarget()->discard();
}
///////////////////////////////////////////////////////////////////////////////
SkSurface* SkSurface::NewRenderTargetDirect(GrRenderTarget* target, const SkSurfaceProps* props) {
SkAutoTUnref<SkGpuDevice> device(SkGpuDevice::Create(target, props));
if (!device) {
return NULL;
}
return SkNEW_ARGS(SkSurface_Gpu, (device));
}
SkSurface* SkSurface::NewRenderTarget(GrContext* ctx, Budgeted budgeted, const SkImageInfo& info,
int sampleCount, const SkSurfaceProps* props) {
SkAutoTUnref<SkGpuDevice> device(SkGpuDevice::Create(ctx, budgeted, info, sampleCount, props,
SkGpuDevice::kNeedClear_Flag));
if (!device) {
return NULL;
}
return SkNEW_ARGS(SkSurface_Gpu, (device));
}
SkSurface* SkSurface::NewWrappedRenderTarget(GrContext* context, GrBackendTextureDesc desc,
const SkSurfaceProps* props) {
if (NULL == context) {
return NULL;
}
if (!SkToBool(desc.fFlags & kRenderTarget_GrBackendTextureFlag)) {
return NULL;
}
SkAutoTUnref<GrSurface> surface(context->textureProvider()->wrapBackendTexture(desc));
if (!surface) {
return NULL;
}
SkAutoTUnref<SkGpuDevice> device(SkGpuDevice::Create(surface->asRenderTarget(), props,
SkGpuDevice::kNeedClear_Flag));
if (!device) {
return NULL;
}
return SkNEW_ARGS(SkSurface_Gpu, (device));
}
#endif
| bsd-3-clause |
dededong/goblin-core | riscv/llvm/3.5/llvm-3.5.0.src/tools/llvm-c-test/disassemble.c | 24 | 2773 | /*===-- disassemble.c - tool for testing libLLVM and llvm-c API -----------===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file implements the --disassemble command in llvm-c-test. *|
|* --disassemble reads lines from stdin, parses them as a triple and hex *|
|* machine code, and prints disassembly of the machine code. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c-test.h"
#include "llvm-c/Disassembler.h"
#include "llvm-c/Target.h"
#include <stdio.h>
#include <stdlib.h>
static void pprint(int pos, unsigned char *buf, int len, const char *disasm) {
int i;
printf("%04x: ", pos);
for (i = 0; i < 8; i++) {
if (i < len) {
printf("%02x ", buf[i]);
} else {
printf(" ");
}
}
printf(" %s\n", disasm);
}
static void do_disassemble(const char *triple, unsigned char *buf, int siz) {
LLVMDisasmContextRef D = LLVMCreateDisasm(triple, NULL, 0, NULL, NULL);
char outline[1024];
int pos;
if (!D) {
printf("ERROR: Couldn't create disassebler for triple %s\n", triple);
return;
}
pos = 0;
while (pos < siz) {
size_t l = LLVMDisasmInstruction(D, buf + pos, siz - pos, 0, outline,
sizeof(outline));
if (!l) {
pprint(pos, buf + pos, 1, "\t???");
pos++;
} else {
pprint(pos, buf + pos, l, outline);
pos += l;
}
}
LLVMDisasmDispose(D);
}
static void handle_line(char **tokens, int ntokens) {
unsigned char disbuf[128];
size_t disbuflen = 0;
char *triple = tokens[0];
int i;
printf("triple: %s\n", triple);
for (i = 1; i < ntokens; i++) {
disbuf[disbuflen++] = strtol(tokens[i], NULL, 16);
if (disbuflen >= sizeof(disbuf)) {
fprintf(stderr, "Warning: Too long line, truncating\n");
break;
}
}
do_disassemble(triple, disbuf, disbuflen);
}
int disassemble(void) {
LLVMInitializeAllTargetInfos();
LLVMInitializeAllTargetMCs();
LLVMInitializeAllDisassemblers();
tokenize_stdin(handle_line);
return 0;
}
| bsd-3-clause |
raspberrypi/userland | containers/core/containers_filters.c | 26 | 7709 | /*
Copyright (c) 2012, Broadcom Europe Ltd
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.
* Neither the name of the copyright holder 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 HOLDER 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 <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "containers/containers.h"
#include "containers/core/containers_private.h"
#include "containers/core/containers_filters.h"
#if !defined(ENABLE_CONTAINERS_STANDALONE)
#include "vcos_dlfcn.h"
#define DL_SUFFIX VCOS_SO_EXT
#ifndef DL_PATH_PREFIX
#define DL_PATH_PREFIX ""
#endif
#endif
typedef struct VC_CONTAINER_FILTER_PRIVATE_T
{
/** Pointer to the container filter code and symbols */
void *handle;
} VC_CONTAINER_FILTER_PRIVATE_T;
typedef VC_CONTAINER_STATUS_T (*VC_CONTAINER_FILTER_OPEN_FUNC_T)(VC_CONTAINER_FILTER_T*, VC_CONTAINER_FOURCC_T);
static VC_CONTAINER_FILTER_OPEN_FUNC_T load_library(void **handle, VC_CONTAINER_FOURCC_T filter, const char *name);
static void unload_library(void *handle);
static struct {
VC_CONTAINER_FOURCC_T filter;
const char *name;
} filter_to_name_table[] =
{
{VC_FOURCC('d','r','m',' '), "divx"},
{VC_FOURCC('d','r','m',' '), "hdcp2"},
{0, NULL}
};
static VC_CONTAINER_STATUS_T vc_container_filter_load(VC_CONTAINER_FILTER_T *p_ctx,
VC_CONTAINER_FOURCC_T filter,
VC_CONTAINER_FOURCC_T type)
{
void *handle = NULL;
VC_CONTAINER_FILTER_OPEN_FUNC_T func;
VC_CONTAINER_STATUS_T status = VC_CONTAINER_ERROR_FORMAT_NOT_SUPPORTED;
unsigned int i;
for(i = 0; filter_to_name_table[i].filter; ++i)
{
if (filter_to_name_table[i].filter == filter)
{
if ((func = load_library(&handle, filter, filter_to_name_table[i].name)) != NULL)
{
status = (*func)(p_ctx, type);
if(status == VC_CONTAINER_SUCCESS) break;
unload_library(handle);
if (status != VC_CONTAINER_ERROR_FORMAT_NOT_SUPPORTED) break;
}
}
}
p_ctx->priv->handle = handle;
return status;
}
static void vc_container_filter_unload(VC_CONTAINER_FILTER_T *p_ctx)
{
unload_library(p_ctx->priv->handle);
p_ctx->priv->handle = NULL;
}
/*****************************************************************************/
VC_CONTAINER_FILTER_T *vc_container_filter_open(VC_CONTAINER_FOURCC_T filter,
VC_CONTAINER_FOURCC_T type,
VC_CONTAINER_T *p_container,
VC_CONTAINER_STATUS_T *p_status )
{
VC_CONTAINER_STATUS_T status = VC_CONTAINER_ERROR_NOT_FOUND;
VC_CONTAINER_FILTER_T *p_ctx = 0;
VC_CONTAINER_FILTER_PRIVATE_T *priv = 0;
/* Allocate our context before trying out the different filter modules */
p_ctx = malloc(sizeof(*p_ctx) + sizeof(*priv));
if(!p_ctx) { status = VC_CONTAINER_ERROR_OUT_OF_MEMORY; goto error; }
memset(p_ctx, 0, sizeof(*p_ctx) + sizeof(*priv));
p_ctx->priv = priv = (VC_CONTAINER_FILTER_PRIVATE_T *)&p_ctx[1];
p_ctx->container = p_container;
status = vc_container_filter_load(p_ctx, filter, type);
if(status != VC_CONTAINER_SUCCESS) goto error;
end:
if(p_status) *p_status = status;
return p_ctx;
error:
if(p_ctx) free(p_ctx);
p_ctx = 0;
goto end;
}
/*****************************************************************************/
VC_CONTAINER_STATUS_T vc_container_filter_close( VC_CONTAINER_FILTER_T *p_ctx )
{
if (p_ctx)
{
if(p_ctx->pf_close) p_ctx->pf_close(p_ctx);
if(p_ctx->priv && p_ctx->priv->handle) vc_container_filter_unload(p_ctx);
free(p_ctx);
}
return VC_CONTAINER_SUCCESS;
}
/*****************************************************************************/
VC_CONTAINER_STATUS_T vc_container_filter_process( VC_CONTAINER_FILTER_T *p_ctx, VC_CONTAINER_PACKET_T *p_packet )
{
VC_CONTAINER_STATUS_T status;
status = p_ctx->pf_process(p_ctx, p_packet);
return status;
}
VC_CONTAINER_STATUS_T vc_container_filter_control(VC_CONTAINER_FILTER_T *p_ctx, VC_CONTAINER_CONTROL_T operation, ... )
{
VC_CONTAINER_STATUS_T status = VC_CONTAINER_ERROR_UNSUPPORTED_OPERATION;
va_list args;
va_start( args, operation );
if(p_ctx->pf_control)
status = p_ctx->pf_control(p_ctx, operation, args);
va_end( args );
return status;
}
static VC_CONTAINER_FILTER_OPEN_FUNC_T load_library(void **handle, VC_CONTAINER_FOURCC_T filter, const char *name)
{
VC_CONTAINER_FILTER_OPEN_FUNC_T func = NULL;
#ifdef ENABLE_CONTAINERS_STANDALONE
VC_CONTAINER_PARAM_UNUSED(handle);
VC_CONTAINER_PARAM_UNUSED(filter);
VC_CONTAINER_PARAM_UNUSED(name);
#else
char *dl_name, *entrypt_name;
const char *entrypt_name_short = "filter_open";
char filter_[6], *ptr;
void *dl_handle;
int dl_name_len;
int entrypt_name_len;
snprintf(filter_, sizeof(filter_), "%4.4s", (const char*)&filter);
ptr = strchr(filter_, '\0');
while (ptr > filter_ && isspace(*--ptr)) *ptr = '\0';
strncat(filter_, "_", 1);
dl_name_len = strlen(DL_PATH_PREFIX) + strlen(filter_) + strlen(name) + strlen(DL_SUFFIX) + 1;
dl_name = malloc(dl_name_len);
if (!dl_name) return NULL;
entrypt_name_len = strlen(name) + 1 + strlen(filter_) + strlen(entrypt_name_short) + 1;
entrypt_name = malloc(entrypt_name_len);
if (!entrypt_name)
{
free(dl_name);
return NULL;
}
snprintf(dl_name, dl_name_len, "%s%s%s%s", DL_PATH_PREFIX, filter_, name, DL_SUFFIX);
snprintf(entrypt_name, entrypt_name_len, "%s_%s%s", name, filter_, entrypt_name_short);
if ((dl_handle = vcos_dlopen(dl_name, VCOS_DL_NOW)) != NULL)
{
/* Try generic entrypoint name before the mangled, full name */
func = (VC_CONTAINER_FILTER_OPEN_FUNC_T)vcos_dlsym(dl_handle, entrypt_name_short);
if (!func) func = (VC_CONTAINER_FILTER_OPEN_FUNC_T)vcos_dlsym(dl_handle, entrypt_name);
/* Only return handle if symbol found */
if (func)
*handle = dl_handle;
else
vcos_dlclose(dl_handle);
}
free(dl_name);
free(entrypt_name);
#endif
return func;
}
static void unload_library(void *handle)
{
#ifdef ENABLE_CONTAINERS_STANDALONE
VC_CONTAINER_PARAM_UNUSED(handle);
#else
vcos_dlclose(handle);
#endif
}
| bsd-3-clause |
guorendong/iridium-browser-ubuntu | buildtools/third_party/libc++/trunk/test/containers/associative/multimap/multimap.cons/iter_iter.pass.cpp | 28 | 3099 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <map>
// class multimap
// template <class InputIterator>
// multimap(InputIterator first, InputIterator last);
#include <map>
#include <cassert>
#include "min_allocator.h"
int main()
{
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2),
};
std::multimap<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
assert(m.size() == 9);
assert(distance(m.begin(), m.end()) == 9);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(1, 1.5));
assert(*next(m.begin(), 2) == V(1, 2));
assert(*next(m.begin(), 3) == V(2, 1));
assert(*next(m.begin(), 4) == V(2, 1.5));
assert(*next(m.begin(), 5) == V(2, 2));
assert(*next(m.begin(), 6) == V(3, 1));
assert(*next(m.begin(), 7) == V(3, 1.5));
assert(*next(m.begin(), 8) == V(3, 2));
}
#if __cplusplus >= 201103L
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2),
};
std::multimap<int, double, std::less<int>, min_allocator<V>> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
assert(m.size() == 9);
assert(distance(m.begin(), m.end()) == 9);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(1, 1.5));
assert(*next(m.begin(), 2) == V(1, 2));
assert(*next(m.begin(), 3) == V(2, 1));
assert(*next(m.begin(), 4) == V(2, 1.5));
assert(*next(m.begin(), 5) == V(2, 2));
assert(*next(m.begin(), 6) == V(3, 1));
assert(*next(m.begin(), 7) == V(3, 1.5));
assert(*next(m.begin(), 8) == V(3, 2));
}
#if _LIBCPP_STD_VER > 11
{
typedef std::pair<const int, double> V;
V ar[] =
{
V(1, 1),
V(1, 1.5),
V(1, 2),
V(2, 1),
V(2, 1.5),
V(2, 2),
V(3, 1),
V(3, 1.5),
V(3, 2),
};
typedef min_allocator<std::pair<const int, double>> A;
A a;
std::multimap<int, double, std::less<int>, A> m(ar, ar+sizeof(ar)/sizeof(ar[0]), a);
assert(m.size() == 9);
assert(distance(m.begin(), m.end()) == 9);
assert(*m.begin() == V(1, 1));
assert(*next(m.begin()) == V(1, 1.5));
assert(*next(m.begin(), 2) == V(1, 2));
assert(*next(m.begin(), 3) == V(2, 1));
assert(*next(m.begin(), 4) == V(2, 1.5));
assert(*next(m.begin(), 5) == V(2, 2));
assert(*next(m.begin(), 6) == V(3, 1));
assert(*next(m.begin(), 7) == V(3, 1.5));
assert(*next(m.begin(), 8) == V(3, 2));
assert(m.get_allocator() == a);
}
#endif
#endif
}
| bsd-3-clause |
yuyichao/OpenBLAS | lapack-netlib/SRC/sposv.f | 29 | 5688 | *> \brief <b> SPOSV computes the solution to system of linear equations A * X = B for PO matrices</b>
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download SPOSV + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sposv.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sposv.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sposv.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE SPOSV( UPLO, N, NRHS, A, LDA, B, LDB, INFO )
*
* .. Scalar Arguments ..
* CHARACTER UPLO
* INTEGER INFO, LDA, LDB, N, NRHS
* ..
* .. Array Arguments ..
* REAL A( LDA, * ), B( LDB, * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> SPOSV computes the solution to a real system of linear equations
*> A * X = B,
*> where A is an N-by-N symmetric positive definite matrix and X and B
*> are N-by-NRHS matrices.
*>
*> The Cholesky decomposition is used to factor A as
*> A = U**T* U, if UPLO = 'U', or
*> A = L * L**T, if UPLO = 'L',
*> where U is an upper triangular matrix and L is a lower triangular
*> matrix. The factored form of A is then used to solve the system of
*> equations A * X = B.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] UPLO
*> \verbatim
*> UPLO is CHARACTER*1
*> = 'U': Upper triangle of A is stored;
*> = 'L': Lower triangle of A is stored.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The number of linear equations, i.e., the order of the
*> matrix A. N >= 0.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*> NRHS is INTEGER
*> The number of right hand sides, i.e., the number of columns
*> of the matrix B. NRHS >= 0.
*> \endverbatim
*>
*> \param[in,out] A
*> \verbatim
*> A is REAL array, dimension (LDA,N)
*> On entry, the symmetric matrix A. If UPLO = 'U', the leading
*> N-by-N upper triangular part of A contains the upper
*> triangular part of the matrix A, and the strictly lower
*> triangular part of A is not referenced. If UPLO = 'L', the
*> leading N-by-N lower triangular part of A contains the lower
*> triangular part of the matrix A, and the strictly upper
*> triangular part of A is not referenced.
*>
*> On exit, if INFO = 0, the factor U or L from the Cholesky
*> factorization A = U**T*U or A = L*L**T.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> The leading dimension of the array A. LDA >= max(1,N).
*> \endverbatim
*>
*> \param[in,out] B
*> \verbatim
*> B is REAL array, dimension (LDB,NRHS)
*> On entry, the N-by-NRHS right hand side matrix B.
*> On exit, if INFO = 0, the N-by-NRHS solution matrix X.
*> \endverbatim
*>
*> \param[in] LDB
*> \verbatim
*> LDB is INTEGER
*> The leading dimension of the array B. LDB >= max(1,N).
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value
*> > 0: if INFO = i, the leading minor of order i of A is not
*> positive definite, so the factorization could not be
*> completed, and the solution has not been computed.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup realPOsolve
*
* =====================================================================
SUBROUTINE SPOSV( UPLO, N, NRHS, A, LDA, B, LDB, INFO )
*
* -- LAPACK driver routine (version 3.4.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2011
*
* .. Scalar Arguments ..
CHARACTER UPLO
INTEGER INFO, LDA, LDB, N, NRHS
* ..
* .. Array Arguments ..
REAL A( LDA, * ), B( LDB, * )
* ..
*
* =====================================================================
*
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL SPOTRF, SPOTRS, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
IF( .NOT.LSAME( UPLO, 'U' ) .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( NRHS.LT.0 ) THEN
INFO = -3
ELSE IF( LDA.LT.MAX( 1, N ) ) THEN
INFO = -5
ELSE IF( LDB.LT.MAX( 1, N ) ) THEN
INFO = -7
END IF
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'SPOSV ', -INFO )
RETURN
END IF
*
* Compute the Cholesky factorization A = U**T*U or A = L*L**T.
*
CALL SPOTRF( UPLO, N, A, LDA, INFO )
IF( INFO.EQ.0 ) THEN
*
* Solve the system A*X = B, overwriting B with X.
*
CALL SPOTRS( UPLO, N, NRHS, A, LDA, B, LDB, INFO )
*
END IF
RETURN
*
* End of SPOSV
*
END
| bsd-3-clause |
mydongistiny/external_chromium_org | third_party/speex/libspeex/stereo.c | 552 | 9883 | /* Copyright (C) 2002 Jean-Marc Valin
File: stereo.c
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 the Xiph.org Foundation 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 FOUNDATION 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <speex/speex_stereo.h>
#include <speex/speex_callbacks.h>
#include "math_approx.h"
#include "vq.h"
#include <math.h>
#include "os_support.h"
typedef struct RealSpeexStereoState {
spx_word32_t balance; /**< Left/right balance info */
spx_word32_t e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */
spx_word32_t smooth_left; /**< Smoothed left channel gain */
spx_word32_t smooth_right; /**< Smoothed right channel gain */
spx_uint32_t reserved1; /**< Reserved for future use */
spx_int32_t reserved2; /**< Reserved for future use */
} RealSpeexStereoState;
/*float e_ratio_quant[4] = {1, 1.26, 1.587, 2};*/
#ifndef FIXED_POINT
static const float e_ratio_quant[4] = {.25f, .315f, .397f, .5f};
static const float e_ratio_quant_bounds[3] = {0.2825f, 0.356f, 0.4485f};
#else
static const spx_word16_t e_ratio_quant[4] = {8192, 10332, 13009, 16384};
static const spx_word16_t e_ratio_quant_bounds[3] = {9257, 11665, 14696};
static const spx_word16_t balance_bounds[31] = {18, 23, 30, 38, 49, 63, 81, 104,
134, 172, 221, 284, 364, 468, 600, 771,
990, 1271, 1632, 2096, 2691, 3455, 4436, 5696,
7314, 9392, 12059, 15484, 19882, 25529, 32766};
#endif
/* This is an ugly compatibility hack that properly resets the stereo state
In case it it compiled in fixed-point, but initialised with the deprecated
floating point static initialiser */
#ifdef FIXED_POINT
#define COMPATIBILITY_HACK(s) do {if ((s)->reserved1 != 0xdeadbeef) speex_stereo_state_reset((SpeexStereoState*)s); } while (0);
#else
#define COMPATIBILITY_HACK(s)
#endif
EXPORT SpeexStereoState *speex_stereo_state_init()
{
SpeexStereoState *stereo = speex_alloc(sizeof(SpeexStereoState));
speex_stereo_state_reset(stereo);
return stereo;
}
EXPORT void speex_stereo_state_reset(SpeexStereoState *_stereo)
{
RealSpeexStereoState *stereo = (RealSpeexStereoState*)_stereo;
#ifdef FIXED_POINT
stereo->balance = 65536;
stereo->e_ratio = 16384;
stereo->smooth_left = 16384;
stereo->smooth_right = 16384;
stereo->reserved1 = 0xdeadbeef;
stereo->reserved2 = 0;
#else
stereo->balance = 1.0f;
stereo->e_ratio = .5f;
stereo->smooth_left = 1.f;
stereo->smooth_right = 1.f;
stereo->reserved1 = 0;
stereo->reserved2 = 0;
#endif
}
EXPORT void speex_stereo_state_destroy(SpeexStereoState *stereo)
{
speex_free(stereo);
}
#ifndef DISABLE_FLOAT_API
EXPORT void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits)
{
int i, tmp;
float e_left=0, e_right=0, e_tot=0;
float balance, e_ratio;
for (i=0;i<frame_size;i++)
{
e_left += ((float)data[2*i])*data[2*i];
e_right += ((float)data[2*i+1])*data[2*i+1];
data[i] = .5*(((float)data[2*i])+data[2*i+1]);
e_tot += ((float)data[i])*data[i];
}
balance=(e_left+1)/(e_right+1);
e_ratio = e_tot/(1+e_left+e_right);
/*Quantization*/
speex_bits_pack(bits, 14, 5);
speex_bits_pack(bits, SPEEX_INBAND_STEREO, 4);
balance=4*log(balance);
/*Pack sign*/
if (balance>0)
speex_bits_pack(bits, 0, 1);
else
speex_bits_pack(bits, 1, 1);
balance=floor(.5+fabs(balance));
if (balance>30)
balance=31;
speex_bits_pack(bits, (int)balance, 5);
/* FIXME: this is a hack */
tmp=scal_quant(e_ratio*Q15_ONE, e_ratio_quant_bounds, 4);
speex_bits_pack(bits, tmp, 2);
}
#endif /* #ifndef DISABLE_FLOAT_API */
EXPORT void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits)
{
int i, tmp;
spx_word32_t e_left=0, e_right=0, e_tot=0;
spx_word32_t balance, e_ratio;
spx_word32_t largest, smallest;
int balance_id;
#ifdef FIXED_POINT
int shift;
#endif
/* In band marker */
speex_bits_pack(bits, 14, 5);
/* Stereo marker */
speex_bits_pack(bits, SPEEX_INBAND_STEREO, 4);
for (i=0;i<frame_size;i++)
{
e_left += SHR32(MULT16_16(data[2*i],data[2*i]),8);
e_right += SHR32(MULT16_16(data[2*i+1],data[2*i+1]),8);
#ifdef FIXED_POINT
/* I think this is actually unbiased */
data[i] = SHR16(data[2*i],1)+PSHR16(data[2*i+1],1);
#else
data[i] = .5*(((float)data[2*i])+data[2*i+1]);
#endif
e_tot += SHR32(MULT16_16(data[i],data[i]),8);
}
if (e_left > e_right)
{
speex_bits_pack(bits, 0, 1);
largest = e_left;
smallest = e_right;
} else {
speex_bits_pack(bits, 1, 1);
largest = e_right;
smallest = e_left;
}
/* Balance quantization */
#ifdef FIXED_POINT
shift = spx_ilog2(largest)-15;
largest = VSHR32(largest, shift-4);
smallest = VSHR32(smallest, shift);
balance = DIV32(largest, ADD32(smallest, 1));
if (balance > 32767)
balance = 32767;
balance_id = scal_quant(EXTRACT16(balance), balance_bounds, 32);
#else
balance=(largest+1.)/(smallest+1.);
balance=4*log(balance);
balance_id=floor(.5+fabs(balance));
if (balance_id>30)
balance_id=31;
#endif
speex_bits_pack(bits, balance_id, 5);
/* "coherence" quantisation */
#ifdef FIXED_POINT
shift = spx_ilog2(e_tot);
e_tot = VSHR32(e_tot, shift-25);
e_left = VSHR32(e_left, shift-10);
e_right = VSHR32(e_right, shift-10);
e_ratio = DIV32(e_tot, e_left+e_right+1);
#else
e_ratio = e_tot/(1.+e_left+e_right);
#endif
tmp=scal_quant(EXTRACT16(e_ratio), e_ratio_quant_bounds, 4);
/*fprintf (stderr, "%d %d %d %d\n", largest, smallest, balance_id, e_ratio);*/
speex_bits_pack(bits, tmp, 2);
}
#ifndef DISABLE_FLOAT_API
EXPORT void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *_stereo)
{
int i;
spx_word32_t balance;
spx_word16_t e_left, e_right, e_ratio;
RealSpeexStereoState *stereo = (RealSpeexStereoState*)_stereo;
COMPATIBILITY_HACK(stereo);
balance=stereo->balance;
e_ratio=stereo->e_ratio;
/* These two are Q14, with max value just below 2. */
e_right = DIV32(QCONST32(1., 22), spx_sqrt(MULT16_32_Q15(e_ratio, ADD32(QCONST32(1., 16), balance))));
e_left = SHR32(MULT16_16(spx_sqrt(balance), e_right), 8);
for (i=frame_size-1;i>=0;i--)
{
spx_word16_t tmp=data[i];
stereo->smooth_left = EXTRACT16(PSHR32(MAC16_16(MULT16_16(stereo->smooth_left, QCONST16(0.98, 15)), e_left, QCONST16(0.02, 15)), 15));
stereo->smooth_right = EXTRACT16(PSHR32(MAC16_16(MULT16_16(stereo->smooth_right, QCONST16(0.98, 15)), e_right, QCONST16(0.02, 15)), 15));
data[2*i] = (float)MULT16_16_P14(stereo->smooth_left, tmp);
data[2*i+1] = (float)MULT16_16_P14(stereo->smooth_right, tmp);
}
}
#endif /* #ifndef DISABLE_FLOAT_API */
EXPORT void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *_stereo)
{
int i;
spx_word32_t balance;
spx_word16_t e_left, e_right, e_ratio;
RealSpeexStereoState *stereo = (RealSpeexStereoState*)_stereo;
COMPATIBILITY_HACK(stereo);
balance=stereo->balance;
e_ratio=stereo->e_ratio;
/* These two are Q14, with max value just below 2. */
e_right = DIV32(QCONST32(1., 22), spx_sqrt(MULT16_32_Q15(e_ratio, ADD32(QCONST32(1., 16), balance))));
e_left = SHR32(MULT16_16(spx_sqrt(balance), e_right), 8);
for (i=frame_size-1;i>=0;i--)
{
spx_int16_t tmp=data[i];
stereo->smooth_left = EXTRACT16(PSHR32(MAC16_16(MULT16_16(stereo->smooth_left, QCONST16(0.98, 15)), e_left, QCONST16(0.02, 15)), 15));
stereo->smooth_right = EXTRACT16(PSHR32(MAC16_16(MULT16_16(stereo->smooth_right, QCONST16(0.98, 15)), e_right, QCONST16(0.02, 15)), 15));
data[2*i] = (spx_int16_t)MULT16_16_P14(stereo->smooth_left, tmp);
data[2*i+1] = (spx_int16_t)MULT16_16_P14(stereo->smooth_right, tmp);
}
}
EXPORT int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data)
{
RealSpeexStereoState *stereo;
spx_word16_t sign=1, dexp;
int tmp;
stereo = (RealSpeexStereoState*)data;
COMPATIBILITY_HACK(stereo);
if (speex_bits_unpack_unsigned(bits, 1))
sign=-1;
dexp = speex_bits_unpack_unsigned(bits, 5);
#ifndef FIXED_POINT
stereo->balance = exp(sign*.25*dexp);
#else
stereo->balance = spx_exp(MULT16_16(sign, SHL16(dexp, 9)));
#endif
tmp = speex_bits_unpack_unsigned(bits, 2);
stereo->e_ratio = e_ratio_quant[tmp];
return 0;
}
| bsd-3-clause |
guker/OpenBLAS | test/cblat3.f | 44 | 130308 | PROGRAM CBLAT3
*
* Test program for the COMPLEX Level 3 Blas.
*
* The program must be driven by a short data file. The first 14 records
* of the file are read using list-directed input, the last 9 records
* are read using the format ( A6, L2 ). An annotated example of a data
* file can be obtained by deleting the first 3 characters from the
* following 23 lines:
* 'CBLAT3.SUMM' NAME OF SUMMARY OUTPUT FILE
* 6 UNIT NUMBER OF SUMMARY FILE
* 'CBLAT3.SNAP' NAME OF SNAPSHOT OUTPUT FILE
* -1 UNIT NUMBER OF SNAPSHOT FILE (NOT USED IF .LT. 0)
* F LOGICAL FLAG, T TO REWIND SNAPSHOT FILE AFTER EACH RECORD.
* F LOGICAL FLAG, T TO STOP ON FAILURES.
* T LOGICAL FLAG, T TO TEST ERROR EXITS.
* 16.0 THRESHOLD VALUE OF TEST RATIO
* 6 NUMBER OF VALUES OF N
* 0 1 2 3 5 9 VALUES OF N
* 3 NUMBER OF VALUES OF ALPHA
* (0.0,0.0) (1.0,0.0) (0.7,-0.9) VALUES OF ALPHA
* 3 NUMBER OF VALUES OF BETA
* (0.0,0.0) (1.0,0.0) (1.3,-1.1) VALUES OF BETA
* CGEMM T PUT F FOR NO TEST. SAME COLUMNS.
* CHEMM T PUT F FOR NO TEST. SAME COLUMNS.
* CSYMM T PUT F FOR NO TEST. SAME COLUMNS.
* CTRMM T PUT F FOR NO TEST. SAME COLUMNS.
* CTRSM T PUT F FOR NO TEST. SAME COLUMNS.
* CHERK T PUT F FOR NO TEST. SAME COLUMNS.
* CSYRK T PUT F FOR NO TEST. SAME COLUMNS.
* CHER2K T PUT F FOR NO TEST. SAME COLUMNS.
* CSYR2K T PUT F FOR NO TEST. SAME COLUMNS.
*
* See:
*
* Dongarra J. J., Du Croz J. J., Duff I. S. and Hammarling S.
* A Set of Level 3 Basic Linear Algebra Subprograms.
*
* Technical Memorandum No.88 (Revision 1), Mathematics and
* Computer Science Division, Argonne National Laboratory, 9700
* South Cass Avenue, Argonne, Illinois 60439, US.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
INTEGER NIN
PARAMETER ( NIN = 5 )
INTEGER NSUBS
PARAMETER ( NSUBS = 9 )
COMPLEX ZERO, ONE
PARAMETER ( ZERO = ( 0.0, 0.0 ), ONE = ( 1.0, 0.0 ) )
REAL RZERO, RHALF, RONE
PARAMETER ( RZERO = 0.0, RHALF = 0.5, RONE = 1.0 )
INTEGER NMAX
PARAMETER ( NMAX = 65 )
INTEGER NIDMAX, NALMAX, NBEMAX
PARAMETER ( NIDMAX = 9, NALMAX = 7, NBEMAX = 7 )
* .. Local Scalars ..
REAL EPS, ERR, THRESH
INTEGER I, ISNUM, J, N, NALF, NBET, NIDIM, NOUT, NTRA
LOGICAL FATAL, LTESTT, REWI, SAME, SFATAL, TRACE,
$ TSTERR
CHARACTER*1 TRANSA, TRANSB
CHARACTER*6 SNAMET
CHARACTER*32 SNAPS, SUMMRY
* .. Local Arrays ..
COMPLEX AA( NMAX*NMAX ), AB( NMAX, 2*NMAX ),
$ ALF( NALMAX ), AS( NMAX*NMAX ),
$ BB( NMAX*NMAX ), BET( NBEMAX ),
$ BS( NMAX*NMAX ), C( NMAX, NMAX ),
$ CC( NMAX*NMAX ), CS( NMAX*NMAX ), CT( NMAX ),
$ W( 2*NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDMAX )
LOGICAL LTEST( NSUBS )
CHARACTER*6 SNAMES( NSUBS )
* .. External Functions ..
REAL SDIFF
LOGICAL LCE
EXTERNAL SDIFF, LCE
* .. External Subroutines ..
EXTERNAL CCHK1, CCHK2, CCHK3, CCHK4, CCHK5, CCHKE, CMMCH
* .. Intrinsic Functions ..
INTRINSIC MAX, MIN
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
CHARACTER*6 SRNAMT
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
COMMON /SRNAMC/SRNAMT
* .. Data statements ..
DATA SNAMES/'CGEMM ', 'CHEMM ', 'CSYMM ', 'CTRMM ',
$ 'CTRSM ', 'CHERK ', 'CSYRK ', 'CHER2K',
$ 'CSYR2K'/
* .. Executable Statements ..
*
* Read name and unit number for summary output file and open file.
*
READ( NIN, FMT = * )SUMMRY
READ( NIN, FMT = * )NOUT
OPEN( NOUT, FILE = SUMMRY, STATUS = 'NEW' )
NOUTC = NOUT
*
* Read name and unit number for snapshot output file and open file.
*
READ( NIN, FMT = * )SNAPS
READ( NIN, FMT = * )NTRA
TRACE = NTRA.GE.0
IF( TRACE )THEN
OPEN( NTRA, FILE = SNAPS, STATUS = 'NEW' )
END IF
* Read the flag that directs rewinding of the snapshot file.
READ( NIN, FMT = * )REWI
REWI = REWI.AND.TRACE
* Read the flag that directs stopping on any failure.
READ( NIN, FMT = * )SFATAL
* Read the flag that indicates whether error exits are to be tested.
READ( NIN, FMT = * )TSTERR
* Read the threshold value of the test ratio
READ( NIN, FMT = * )THRESH
*
* Read and check the parameter values for the tests.
*
* Values of N
READ( NIN, FMT = * )NIDIM
IF( NIDIM.LT.1.OR.NIDIM.GT.NIDMAX )THEN
WRITE( NOUT, FMT = 9997 )'N', NIDMAX
GO TO 220
END IF
READ( NIN, FMT = * )( IDIM( I ), I = 1, NIDIM )
DO 10 I = 1, NIDIM
IF( IDIM( I ).LT.0.OR.IDIM( I ).GT.NMAX )THEN
WRITE( NOUT, FMT = 9996 )NMAX
GO TO 220
END IF
10 CONTINUE
* Values of ALPHA
READ( NIN, FMT = * )NALF
IF( NALF.LT.1.OR.NALF.GT.NALMAX )THEN
WRITE( NOUT, FMT = 9997 )'ALPHA', NALMAX
GO TO 220
END IF
READ( NIN, FMT = * )( ALF( I ), I = 1, NALF )
* Values of BETA
READ( NIN, FMT = * )NBET
IF( NBET.LT.1.OR.NBET.GT.NBEMAX )THEN
WRITE( NOUT, FMT = 9997 )'BETA', NBEMAX
GO TO 220
END IF
READ( NIN, FMT = * )( BET( I ), I = 1, NBET )
*
* Report values of parameters.
*
WRITE( NOUT, FMT = 9995 )
WRITE( NOUT, FMT = 9994 )( IDIM( I ), I = 1, NIDIM )
WRITE( NOUT, FMT = 9993 )( ALF( I ), I = 1, NALF )
WRITE( NOUT, FMT = 9992 )( BET( I ), I = 1, NBET )
IF( .NOT.TSTERR )THEN
WRITE( NOUT, FMT = * )
WRITE( NOUT, FMT = 9984 )
END IF
WRITE( NOUT, FMT = * )
WRITE( NOUT, FMT = 9999 )THRESH
WRITE( NOUT, FMT = * )
*
* Read names of subroutines and flags which indicate
* whether they are to be tested.
*
DO 20 I = 1, NSUBS
LTEST( I ) = .FALSE.
20 CONTINUE
30 READ( NIN, FMT = 9988, END = 60 )SNAMET, LTESTT
DO 40 I = 1, NSUBS
IF( SNAMET.EQ.SNAMES( I ) )
$ GO TO 50
40 CONTINUE
WRITE( NOUT, FMT = 9990 )SNAMET
STOP
50 LTEST( I ) = LTESTT
GO TO 30
*
60 CONTINUE
CLOSE ( NIN )
*
* Compute EPS (the machine precision).
*
EPS = RONE
70 CONTINUE
IF( SDIFF( RONE + EPS, RONE ).EQ.RZERO )
$ GO TO 80
EPS = RHALF*EPS
GO TO 70
80 CONTINUE
EPS = EPS + EPS
WRITE( NOUT, FMT = 9998 )EPS
*
* Check the reliability of CMMCH using exact data.
*
N = MIN( 32, NMAX )
DO 100 J = 1, N
DO 90 I = 1, N
AB( I, J ) = MAX( I - J + 1, 0 )
90 CONTINUE
AB( J, NMAX + 1 ) = J
AB( 1, NMAX + J ) = J
C( J, 1 ) = ZERO
100 CONTINUE
DO 110 J = 1, N
CC( J ) = J*( ( J + 1 )*J )/2 - ( ( J + 1 )*J*( J - 1 ) )/3
110 CONTINUE
* CC holds the exact result. On exit from CMMCH CT holds
* the result computed by CMMCH.
TRANSA = 'N'
TRANSB = 'N'
CALL CMMCH( TRANSA, TRANSB, N, 1, N, ONE, AB, NMAX,
$ AB( 1, NMAX + 1 ), NMAX, ZERO, C, NMAX, CT, G, CC,
$ NMAX, EPS, ERR, FATAL, NOUT, .TRUE. )
SAME = LCE( CC, CT, N )
IF( .NOT.SAME.OR.ERR.NE.RZERO )THEN
WRITE( NOUT, FMT = 9989 )TRANSA, TRANSB, SAME, ERR
STOP
END IF
TRANSB = 'C'
CALL CMMCH( TRANSA, TRANSB, N, 1, N, ONE, AB, NMAX,
$ AB( 1, NMAX + 1 ), NMAX, ZERO, C, NMAX, CT, G, CC,
$ NMAX, EPS, ERR, FATAL, NOUT, .TRUE. )
SAME = LCE( CC, CT, N )
IF( .NOT.SAME.OR.ERR.NE.RZERO )THEN
WRITE( NOUT, FMT = 9989 )TRANSA, TRANSB, SAME, ERR
STOP
END IF
DO 120 J = 1, N
AB( J, NMAX + 1 ) = N - J + 1
AB( 1, NMAX + J ) = N - J + 1
120 CONTINUE
DO 130 J = 1, N
CC( N - J + 1 ) = J*( ( J + 1 )*J )/2 -
$ ( ( J + 1 )*J*( J - 1 ) )/3
130 CONTINUE
TRANSA = 'C'
TRANSB = 'N'
CALL CMMCH( TRANSA, TRANSB, N, 1, N, ONE, AB, NMAX,
$ AB( 1, NMAX + 1 ), NMAX, ZERO, C, NMAX, CT, G, CC,
$ NMAX, EPS, ERR, FATAL, NOUT, .TRUE. )
SAME = LCE( CC, CT, N )
IF( .NOT.SAME.OR.ERR.NE.RZERO )THEN
WRITE( NOUT, FMT = 9989 )TRANSA, TRANSB, SAME, ERR
STOP
END IF
TRANSB = 'C'
CALL CMMCH( TRANSA, TRANSB, N, 1, N, ONE, AB, NMAX,
$ AB( 1, NMAX + 1 ), NMAX, ZERO, C, NMAX, CT, G, CC,
$ NMAX, EPS, ERR, FATAL, NOUT, .TRUE. )
SAME = LCE( CC, CT, N )
IF( .NOT.SAME.OR.ERR.NE.RZERO )THEN
WRITE( NOUT, FMT = 9989 )TRANSA, TRANSB, SAME, ERR
STOP
END IF
*
* Test each subroutine in turn.
*
DO 200 ISNUM = 1, NSUBS
WRITE( NOUT, FMT = * )
IF( .NOT.LTEST( ISNUM ) )THEN
* Subprogram is not to be tested.
WRITE( NOUT, FMT = 9987 )SNAMES( ISNUM )
ELSE
SRNAMT = SNAMES( ISNUM )
* Test error exits.
IF( TSTERR )THEN
CALL CCHKE( ISNUM, SNAMES( ISNUM ), NOUT )
WRITE( NOUT, FMT = * )
END IF
* Test computations.
INFOT = 0
OK = .TRUE.
FATAL = .FALSE.
GO TO ( 140, 150, 150, 160, 160, 170, 170,
$ 180, 180 )ISNUM
* Test CGEMM, 01.
140 CALL CCHK1( SNAMES( ISNUM ), EPS, THRESH, NOUT, NTRA, TRACE,
$ REWI, FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET,
$ NMAX, AB, AA, AS, AB( 1, NMAX + 1 ), BB, BS, C,
$ CC, CS, CT, G )
GO TO 190
* Test CHEMM, 02, CSYMM, 03.
150 CALL CCHK2( SNAMES( ISNUM ), EPS, THRESH, NOUT, NTRA, TRACE,
$ REWI, FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET,
$ NMAX, AB, AA, AS, AB( 1, NMAX + 1 ), BB, BS, C,
$ CC, CS, CT, G )
GO TO 190
* Test CTRMM, 04, CTRSM, 05.
160 CALL CCHK3( SNAMES( ISNUM ), EPS, THRESH, NOUT, NTRA, TRACE,
$ REWI, FATAL, NIDIM, IDIM, NALF, ALF, NMAX, AB,
$ AA, AS, AB( 1, NMAX + 1 ), BB, BS, CT, G, C )
GO TO 190
* Test CHERK, 06, CSYRK, 07.
170 CALL CCHK4( SNAMES( ISNUM ), EPS, THRESH, NOUT, NTRA, TRACE,
$ REWI, FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET,
$ NMAX, AB, AA, AS, AB( 1, NMAX + 1 ), BB, BS, C,
$ CC, CS, CT, G )
GO TO 190
* Test CHER2K, 08, CSYR2K, 09.
180 CALL CCHK5( SNAMES( ISNUM ), EPS, THRESH, NOUT, NTRA, TRACE,
$ REWI, FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET,
$ NMAX, AB, AA, AS, BB, BS, C, CC, CS, CT, G, W )
GO TO 190
*
190 IF( FATAL.AND.SFATAL )
$ GO TO 210
END IF
200 CONTINUE
WRITE( NOUT, FMT = 9986 )
GO TO 230
*
210 CONTINUE
WRITE( NOUT, FMT = 9985 )
GO TO 230
*
220 CONTINUE
WRITE( NOUT, FMT = 9991 )
*
230 CONTINUE
IF( TRACE )
$ CLOSE ( NTRA )
CLOSE ( NOUT )
STOP
*
9999 FORMAT( ' ROUTINES PASS COMPUTATIONAL TESTS IF TEST RATIO IS LES',
$ 'S THAN', F8.2 )
9998 FORMAT( ' RELATIVE MACHINE PRECISION IS TAKEN TO BE', 1P, E9.1 )
9997 FORMAT( ' NUMBER OF VALUES OF ', A, ' IS LESS THAN 1 OR GREATER ',
$ 'THAN ', I2 )
9996 FORMAT( ' VALUE OF N IS LESS THAN 0 OR GREATER THAN ', I2 )
9995 FORMAT( ' TESTS OF THE COMPLEX LEVEL 3 BLAS', //' THE F',
$ 'OLLOWING PARAMETER VALUES WILL BE USED:' )
9994 FORMAT( ' FOR N ', 9I6 )
9993 FORMAT( ' FOR ALPHA ',
$ 7( '(', F4.1, ',', F4.1, ') ', : ) )
9992 FORMAT( ' FOR BETA ',
$ 7( '(', F4.1, ',', F4.1, ') ', : ) )
9991 FORMAT( ' AMEND DATA FILE OR INCREASE ARRAY SIZES IN PROGRAM',
$ /' ******* TESTS ABANDONED *******' )
9990 FORMAT( ' SUBPROGRAM NAME ', A6, ' NOT RECOGNIZED', /' ******* T',
$ 'ESTS ABANDONED *******' )
9989 FORMAT( ' ERROR IN CMMCH - IN-LINE DOT PRODUCTS ARE BEING EVALU',
$ 'ATED WRONGLY.', /' CMMCH WAS CALLED WITH TRANSA = ', A1,
$ ' AND TRANSB = ', A1, /' AND RETURNED SAME = ', L1, ' AND ',
$ 'ERR = ', F12.3, '.', /' THIS MAY BE DUE TO FAULTS IN THE ',
$ 'ARITHMETIC OR THE COMPILER.', /' ******* TESTS ABANDONED ',
$ '*******' )
9988 FORMAT( A6, L2 )
9987 FORMAT( 1X, A6, ' WAS NOT TESTED' )
9986 FORMAT( /' END OF TESTS' )
9985 FORMAT( /' ******* FATAL ERROR - TESTS ABANDONED *******' )
9984 FORMAT( ' ERROR-EXITS WILL NOT BE TESTED' )
*
* End of CBLAT3.
*
END
SUBROUTINE CCHK1( SNAME, EPS, THRESH, NOUT, NTRA, TRACE, REWI,
$ FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET, NMAX,
$ A, AA, AS, B, BB, BS, C, CC, CS, CT, G )
*
* Tests CGEMM.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO
PARAMETER ( ZERO = ( 0.0, 0.0 ) )
REAL RZERO
PARAMETER ( RZERO = 0.0 )
* .. Scalar Arguments ..
REAL EPS, THRESH
INTEGER NALF, NBET, NIDIM, NMAX, NOUT, NTRA
LOGICAL FATAL, REWI, TRACE
CHARACTER*6 SNAME
* .. Array Arguments ..
COMPLEX A( NMAX, NMAX ), AA( NMAX*NMAX ), ALF( NALF ),
$ AS( NMAX*NMAX ), B( NMAX, NMAX ),
$ BB( NMAX*NMAX ), BET( NBET ), BS( NMAX*NMAX ),
$ C( NMAX, NMAX ), CC( NMAX*NMAX ),
$ CS( NMAX*NMAX ), CT( NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDIM )
* .. Local Scalars ..
COMPLEX ALPHA, ALS, BETA, BLS
REAL ERR, ERRMAX
INTEGER I, IA, IB, ICA, ICB, IK, IM, IN, K, KS, LAA,
$ LBB, LCC, LDA, LDAS, LDB, LDBS, LDC, LDCS, M,
$ MA, MB, MS, N, NA, NARGS, NB, NC, NS
LOGICAL NULL, RESET, SAME, TRANA, TRANB
CHARACTER*1 TRANAS, TRANBS, TRANSA, TRANSB
CHARACTER*3 ICH
* .. Local Arrays ..
LOGICAL ISAME( 13 )
* .. External Functions ..
LOGICAL LCE, LCERES
EXTERNAL LCE, LCERES
* .. External Subroutines ..
EXTERNAL CGEMM, CMAKE, CMMCH
* .. Intrinsic Functions ..
INTRINSIC MAX
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Data statements ..
DATA ICH/'NTC'/
* .. Executable Statements ..
*
NARGS = 13
NC = 0
RESET = .TRUE.
ERRMAX = RZERO
*
DO 110 IM = 1, NIDIM
M = IDIM( IM )
*
DO 100 IN = 1, NIDIM
N = IDIM( IN )
* Set LDC to 1 more than minimum value if room.
LDC = M
IF( LDC.LT.NMAX )
$ LDC = LDC + 1
* Skip tests if not enough room.
IF( LDC.GT.NMAX )
$ GO TO 100
LCC = LDC*N
NULL = N.LE.0.OR.M.LE.0
*
DO 90 IK = 1, NIDIM
K = IDIM( IK )
*
DO 80 ICA = 1, 3
TRANSA = ICH( ICA: ICA )
TRANA = TRANSA.EQ.'T'.OR.TRANSA.EQ.'C'
*
IF( TRANA )THEN
MA = K
NA = M
ELSE
MA = M
NA = K
END IF
* Set LDA to 1 more than minimum value if room.
LDA = MA
IF( LDA.LT.NMAX )
$ LDA = LDA + 1
* Skip tests if not enough room.
IF( LDA.GT.NMAX )
$ GO TO 80
LAA = LDA*NA
*
* Generate the matrix A.
*
CALL CMAKE( 'GE', ' ', ' ', MA, NA, A, NMAX, AA, LDA,
$ RESET, ZERO )
*
DO 70 ICB = 1, 3
TRANSB = ICH( ICB: ICB )
TRANB = TRANSB.EQ.'T'.OR.TRANSB.EQ.'C'
*
IF( TRANB )THEN
MB = N
NB = K
ELSE
MB = K
NB = N
END IF
* Set LDB to 1 more than minimum value if room.
LDB = MB
IF( LDB.LT.NMAX )
$ LDB = LDB + 1
* Skip tests if not enough room.
IF( LDB.GT.NMAX )
$ GO TO 70
LBB = LDB*NB
*
* Generate the matrix B.
*
CALL CMAKE( 'GE', ' ', ' ', MB, NB, B, NMAX, BB,
$ LDB, RESET, ZERO )
*
DO 60 IA = 1, NALF
ALPHA = ALF( IA )
*
DO 50 IB = 1, NBET
BETA = BET( IB )
*
* Generate the matrix C.
*
CALL CMAKE( 'GE', ' ', ' ', M, N, C, NMAX,
$ CC, LDC, RESET, ZERO )
*
NC = NC + 1
*
* Save every datum before calling the
* subroutine.
*
TRANAS = TRANSA
TRANBS = TRANSB
MS = M
NS = N
KS = K
ALS = ALPHA
DO 10 I = 1, LAA
AS( I ) = AA( I )
10 CONTINUE
LDAS = LDA
DO 20 I = 1, LBB
BS( I ) = BB( I )
20 CONTINUE
LDBS = LDB
BLS = BETA
DO 30 I = 1, LCC
CS( I ) = CC( I )
30 CONTINUE
LDCS = LDC
*
* Call the subroutine.
*
IF( TRACE )
$ WRITE( NTRA, FMT = 9995 )NC, SNAME,
$ TRANSA, TRANSB, M, N, K, ALPHA, LDA, LDB,
$ BETA, LDC
IF( REWI )
$ REWIND NTRA
CALL CGEMM( TRANSA, TRANSB, M, N, K, ALPHA,
$ AA, LDA, BB, LDB, BETA, CC, LDC )
*
* Check if error-exit was taken incorrectly.
*
IF( .NOT.OK )THEN
WRITE( NOUT, FMT = 9994 )
FATAL = .TRUE.
GO TO 120
END IF
*
* See what data changed inside subroutines.
*
ISAME( 1 ) = TRANSA.EQ.TRANAS
ISAME( 2 ) = TRANSB.EQ.TRANBS
ISAME( 3 ) = MS.EQ.M
ISAME( 4 ) = NS.EQ.N
ISAME( 5 ) = KS.EQ.K
ISAME( 6 ) = ALS.EQ.ALPHA
ISAME( 7 ) = LCE( AS, AA, LAA )
ISAME( 8 ) = LDAS.EQ.LDA
ISAME( 9 ) = LCE( BS, BB, LBB )
ISAME( 10 ) = LDBS.EQ.LDB
ISAME( 11 ) = BLS.EQ.BETA
IF( NULL )THEN
ISAME( 12 ) = LCE( CS, CC, LCC )
ELSE
ISAME( 12 ) = LCERES( 'GE', ' ', M, N, CS,
$ CC, LDC )
END IF
ISAME( 13 ) = LDCS.EQ.LDC
*
* If data was incorrectly changed, report
* and return.
*
SAME = .TRUE.
DO 40 I = 1, NARGS
SAME = SAME.AND.ISAME( I )
IF( .NOT.ISAME( I ) )
$ WRITE( NOUT, FMT = 9998 )I
40 CONTINUE
IF( .NOT.SAME )THEN
FATAL = .TRUE.
GO TO 120
END IF
*
IF( .NOT.NULL )THEN
*
* Check the result.
*
CALL CMMCH( TRANSA, TRANSB, M, N, K,
$ ALPHA, A, NMAX, B, NMAX, BETA,
$ C, NMAX, CT, G, CC, LDC, EPS,
$ ERR, FATAL, NOUT, .TRUE. )
ERRMAX = MAX( ERRMAX, ERR )
* If got really bad answer, report and
* return.
IF( FATAL )
$ GO TO 120
END IF
*
50 CONTINUE
*
60 CONTINUE
*
70 CONTINUE
*
80 CONTINUE
*
90 CONTINUE
*
100 CONTINUE
*
110 CONTINUE
*
* Report result.
*
IF( ERRMAX.LT.THRESH )THEN
WRITE( NOUT, FMT = 9999 )SNAME, NC
ELSE
WRITE( NOUT, FMT = 9997 )SNAME, NC, ERRMAX
END IF
GO TO 130
*
120 CONTINUE
WRITE( NOUT, FMT = 9996 )SNAME
WRITE( NOUT, FMT = 9995 )NC, SNAME, TRANSA, TRANSB, M, N, K,
$ ALPHA, LDA, LDB, BETA, LDC
*
130 CONTINUE
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE COMPUTATIONAL TESTS (', I6, ' CALL',
$ 'S)' )
9998 FORMAT( ' ******* FATAL ERROR - PARAMETER NUMBER ', I2, ' WAS CH',
$ 'ANGED INCORRECTLY *******' )
9997 FORMAT( ' ', A6, ' COMPLETED THE COMPUTATIONAL TESTS (', I6, ' C',
$ 'ALLS)', /' ******* BUT WITH MAXIMUM TEST RATIO', F8.2,
$ ' - SUSPECT *******' )
9996 FORMAT( ' ******* ', A6, ' FAILED ON CALL NUMBER:' )
9995 FORMAT( 1X, I6, ': ', A6, '(''', A1, ''',''', A1, ''',',
$ 3( I3, ',' ), '(', F4.1, ',', F4.1, '), A,', I3, ', B,', I3,
$ ',(', F4.1, ',', F4.1, '), C,', I3, ').' )
9994 FORMAT( ' ******* FATAL ERROR - ERROR-EXIT TAKEN ON VALID CALL *',
$ '******' )
*
* End of CCHK1.
*
END
SUBROUTINE CCHK2( SNAME, EPS, THRESH, NOUT, NTRA, TRACE, REWI,
$ FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET, NMAX,
$ A, AA, AS, B, BB, BS, C, CC, CS, CT, G )
*
* Tests CHEMM and CSYMM.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO
PARAMETER ( ZERO = ( 0.0, 0.0 ) )
REAL RZERO
PARAMETER ( RZERO = 0.0 )
* .. Scalar Arguments ..
REAL EPS, THRESH
INTEGER NALF, NBET, NIDIM, NMAX, NOUT, NTRA
LOGICAL FATAL, REWI, TRACE
CHARACTER*6 SNAME
* .. Array Arguments ..
COMPLEX A( NMAX, NMAX ), AA( NMAX*NMAX ), ALF( NALF ),
$ AS( NMAX*NMAX ), B( NMAX, NMAX ),
$ BB( NMAX*NMAX ), BET( NBET ), BS( NMAX*NMAX ),
$ C( NMAX, NMAX ), CC( NMAX*NMAX ),
$ CS( NMAX*NMAX ), CT( NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDIM )
* .. Local Scalars ..
COMPLEX ALPHA, ALS, BETA, BLS
REAL ERR, ERRMAX
INTEGER I, IA, IB, ICS, ICU, IM, IN, LAA, LBB, LCC,
$ LDA, LDAS, LDB, LDBS, LDC, LDCS, M, MS, N, NA,
$ NARGS, NC, NS
LOGICAL CONJ, LEFT, NULL, RESET, SAME
CHARACTER*1 SIDE, SIDES, UPLO, UPLOS
CHARACTER*2 ICHS, ICHU
* .. Local Arrays ..
LOGICAL ISAME( 13 )
* .. External Functions ..
LOGICAL LCE, LCERES
EXTERNAL LCE, LCERES
* .. External Subroutines ..
EXTERNAL CHEMM, CMAKE, CMMCH, CSYMM
* .. Intrinsic Functions ..
INTRINSIC MAX
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Data statements ..
DATA ICHS/'LR'/, ICHU/'UL'/
* .. Executable Statements ..
CONJ = SNAME( 2: 3 ).EQ.'HE'
*
NARGS = 12
NC = 0
RESET = .TRUE.
ERRMAX = RZERO
*
DO 100 IM = 1, NIDIM
M = IDIM( IM )
*
DO 90 IN = 1, NIDIM
N = IDIM( IN )
* Set LDC to 1 more than minimum value if room.
LDC = M
IF( LDC.LT.NMAX )
$ LDC = LDC + 1
* Skip tests if not enough room.
IF( LDC.GT.NMAX )
$ GO TO 90
LCC = LDC*N
NULL = N.LE.0.OR.M.LE.0
* Set LDB to 1 more than minimum value if room.
LDB = M
IF( LDB.LT.NMAX )
$ LDB = LDB + 1
* Skip tests if not enough room.
IF( LDB.GT.NMAX )
$ GO TO 90
LBB = LDB*N
*
* Generate the matrix B.
*
CALL CMAKE( 'GE', ' ', ' ', M, N, B, NMAX, BB, LDB, RESET,
$ ZERO )
*
DO 80 ICS = 1, 2
SIDE = ICHS( ICS: ICS )
LEFT = SIDE.EQ.'L'
*
IF( LEFT )THEN
NA = M
ELSE
NA = N
END IF
* Set LDA to 1 more than minimum value if room.
LDA = NA
IF( LDA.LT.NMAX )
$ LDA = LDA + 1
* Skip tests if not enough room.
IF( LDA.GT.NMAX )
$ GO TO 80
LAA = LDA*NA
*
DO 70 ICU = 1, 2
UPLO = ICHU( ICU: ICU )
*
* Generate the hermitian or symmetric matrix A.
*
CALL CMAKE( SNAME( 2: 3 ), UPLO, ' ', NA, NA, A, NMAX,
$ AA, LDA, RESET, ZERO )
*
DO 60 IA = 1, NALF
ALPHA = ALF( IA )
*
DO 50 IB = 1, NBET
BETA = BET( IB )
*
* Generate the matrix C.
*
CALL CMAKE( 'GE', ' ', ' ', M, N, C, NMAX, CC,
$ LDC, RESET, ZERO )
*
NC = NC + 1
*
* Save every datum before calling the
* subroutine.
*
SIDES = SIDE
UPLOS = UPLO
MS = M
NS = N
ALS = ALPHA
DO 10 I = 1, LAA
AS( I ) = AA( I )
10 CONTINUE
LDAS = LDA
DO 20 I = 1, LBB
BS( I ) = BB( I )
20 CONTINUE
LDBS = LDB
BLS = BETA
DO 30 I = 1, LCC
CS( I ) = CC( I )
30 CONTINUE
LDCS = LDC
*
* Call the subroutine.
*
IF( TRACE )
$ WRITE( NTRA, FMT = 9995 )NC, SNAME, SIDE,
$ UPLO, M, N, ALPHA, LDA, LDB, BETA, LDC
IF( REWI )
$ REWIND NTRA
IF( CONJ )THEN
CALL CHEMM( SIDE, UPLO, M, N, ALPHA, AA, LDA,
$ BB, LDB, BETA, CC, LDC )
ELSE
CALL CSYMM( SIDE, UPLO, M, N, ALPHA, AA, LDA,
$ BB, LDB, BETA, CC, LDC )
END IF
*
* Check if error-exit was taken incorrectly.
*
IF( .NOT.OK )THEN
WRITE( NOUT, FMT = 9994 )
FATAL = .TRUE.
GO TO 110
END IF
*
* See what data changed inside subroutines.
*
ISAME( 1 ) = SIDES.EQ.SIDE
ISAME( 2 ) = UPLOS.EQ.UPLO
ISAME( 3 ) = MS.EQ.M
ISAME( 4 ) = NS.EQ.N
ISAME( 5 ) = ALS.EQ.ALPHA
ISAME( 6 ) = LCE( AS, AA, LAA )
ISAME( 7 ) = LDAS.EQ.LDA
ISAME( 8 ) = LCE( BS, BB, LBB )
ISAME( 9 ) = LDBS.EQ.LDB
ISAME( 10 ) = BLS.EQ.BETA
IF( NULL )THEN
ISAME( 11 ) = LCE( CS, CC, LCC )
ELSE
ISAME( 11 ) = LCERES( 'GE', ' ', M, N, CS,
$ CC, LDC )
END IF
ISAME( 12 ) = LDCS.EQ.LDC
*
* If data was incorrectly changed, report and
* return.
*
SAME = .TRUE.
DO 40 I = 1, NARGS
SAME = SAME.AND.ISAME( I )
IF( .NOT.ISAME( I ) )
$ WRITE( NOUT, FMT = 9998 )I
40 CONTINUE
IF( .NOT.SAME )THEN
FATAL = .TRUE.
GO TO 110
END IF
*
IF( .NOT.NULL )THEN
*
* Check the result.
*
IF( LEFT )THEN
CALL CMMCH( 'N', 'N', M, N, M, ALPHA, A,
$ NMAX, B, NMAX, BETA, C, NMAX,
$ CT, G, CC, LDC, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
ELSE
CALL CMMCH( 'N', 'N', M, N, N, ALPHA, B,
$ NMAX, A, NMAX, BETA, C, NMAX,
$ CT, G, CC, LDC, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
END IF
ERRMAX = MAX( ERRMAX, ERR )
* If got really bad answer, report and
* return.
IF( FATAL )
$ GO TO 110
END IF
*
50 CONTINUE
*
60 CONTINUE
*
70 CONTINUE
*
80 CONTINUE
*
90 CONTINUE
*
100 CONTINUE
*
* Report result.
*
IF( ERRMAX.LT.THRESH )THEN
WRITE( NOUT, FMT = 9999 )SNAME, NC
ELSE
WRITE( NOUT, FMT = 9997 )SNAME, NC, ERRMAX
END IF
GO TO 120
*
110 CONTINUE
WRITE( NOUT, FMT = 9996 )SNAME
WRITE( NOUT, FMT = 9995 )NC, SNAME, SIDE, UPLO, M, N, ALPHA, LDA,
$ LDB, BETA, LDC
*
120 CONTINUE
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE COMPUTATIONAL TESTS (', I6, ' CALL',
$ 'S)' )
9998 FORMAT( ' ******* FATAL ERROR - PARAMETER NUMBER ', I2, ' WAS CH',
$ 'ANGED INCORRECTLY *******' )
9997 FORMAT( ' ', A6, ' COMPLETED THE COMPUTATIONAL TESTS (', I6, ' C',
$ 'ALLS)', /' ******* BUT WITH MAXIMUM TEST RATIO', F8.2,
$ ' - SUSPECT *******' )
9996 FORMAT( ' ******* ', A6, ' FAILED ON CALL NUMBER:' )
9995 FORMAT( 1X, I6, ': ', A6, '(', 2( '''', A1, ''',' ), 2( I3, ',' ),
$ '(', F4.1, ',', F4.1, '), A,', I3, ', B,', I3, ',(', F4.1,
$ ',', F4.1, '), C,', I3, ') .' )
9994 FORMAT( ' ******* FATAL ERROR - ERROR-EXIT TAKEN ON VALID CALL *',
$ '******' )
*
* End of CCHK2.
*
END
SUBROUTINE CCHK3( SNAME, EPS, THRESH, NOUT, NTRA, TRACE, REWI,
$ FATAL, NIDIM, IDIM, NALF, ALF, NMAX, A, AA, AS,
$ B, BB, BS, CT, G, C )
*
* Tests CTRMM and CTRSM.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO, ONE
PARAMETER ( ZERO = ( 0.0, 0.0 ), ONE = ( 1.0, 0.0 ) )
REAL RZERO
PARAMETER ( RZERO = 0.0 )
* .. Scalar Arguments ..
REAL EPS, THRESH
INTEGER NALF, NIDIM, NMAX, NOUT, NTRA
LOGICAL FATAL, REWI, TRACE
CHARACTER*6 SNAME
* .. Array Arguments ..
COMPLEX A( NMAX, NMAX ), AA( NMAX*NMAX ), ALF( NALF ),
$ AS( NMAX*NMAX ), B( NMAX, NMAX ),
$ BB( NMAX*NMAX ), BS( NMAX*NMAX ),
$ C( NMAX, NMAX ), CT( NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDIM )
* .. Local Scalars ..
COMPLEX ALPHA, ALS
REAL ERR, ERRMAX
INTEGER I, IA, ICD, ICS, ICT, ICU, IM, IN, J, LAA, LBB,
$ LDA, LDAS, LDB, LDBS, M, MS, N, NA, NARGS, NC,
$ NS
LOGICAL LEFT, NULL, RESET, SAME
CHARACTER*1 DIAG, DIAGS, SIDE, SIDES, TRANAS, TRANSA, UPLO,
$ UPLOS
CHARACTER*2 ICHD, ICHS, ICHU
CHARACTER*3 ICHT
* .. Local Arrays ..
LOGICAL ISAME( 13 )
* .. External Functions ..
LOGICAL LCE, LCERES
EXTERNAL LCE, LCERES
* .. External Subroutines ..
EXTERNAL CMAKE, CMMCH, CTRMM, CTRSM
* .. Intrinsic Functions ..
INTRINSIC MAX
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Data statements ..
DATA ICHU/'UL'/, ICHT/'NTC'/, ICHD/'UN'/, ICHS/'LR'/
* .. Executable Statements ..
*
NARGS = 11
NC = 0
RESET = .TRUE.
ERRMAX = RZERO
* Set up zero matrix for CMMCH.
DO 20 J = 1, NMAX
DO 10 I = 1, NMAX
C( I, J ) = ZERO
10 CONTINUE
20 CONTINUE
*
DO 140 IM = 1, NIDIM
M = IDIM( IM )
*
DO 130 IN = 1, NIDIM
N = IDIM( IN )
* Set LDB to 1 more than minimum value if room.
LDB = M
IF( LDB.LT.NMAX )
$ LDB = LDB + 1
* Skip tests if not enough room.
IF( LDB.GT.NMAX )
$ GO TO 130
LBB = LDB*N
NULL = M.LE.0.OR.N.LE.0
*
DO 120 ICS = 1, 2
SIDE = ICHS( ICS: ICS )
LEFT = SIDE.EQ.'L'
IF( LEFT )THEN
NA = M
ELSE
NA = N
END IF
* Set LDA to 1 more than minimum value if room.
LDA = NA
IF( LDA.LT.NMAX )
$ LDA = LDA + 1
* Skip tests if not enough room.
IF( LDA.GT.NMAX )
$ GO TO 130
LAA = LDA*NA
*
DO 110 ICU = 1, 2
UPLO = ICHU( ICU: ICU )
*
DO 100 ICT = 1, 3
TRANSA = ICHT( ICT: ICT )
*
DO 90 ICD = 1, 2
DIAG = ICHD( ICD: ICD )
*
DO 80 IA = 1, NALF
ALPHA = ALF( IA )
*
* Generate the matrix A.
*
CALL CMAKE( 'TR', UPLO, DIAG, NA, NA, A,
$ NMAX, AA, LDA, RESET, ZERO )
*
* Generate the matrix B.
*
CALL CMAKE( 'GE', ' ', ' ', M, N, B, NMAX,
$ BB, LDB, RESET, ZERO )
*
NC = NC + 1
*
* Save every datum before calling the
* subroutine.
*
SIDES = SIDE
UPLOS = UPLO
TRANAS = TRANSA
DIAGS = DIAG
MS = M
NS = N
ALS = ALPHA
DO 30 I = 1, LAA
AS( I ) = AA( I )
30 CONTINUE
LDAS = LDA
DO 40 I = 1, LBB
BS( I ) = BB( I )
40 CONTINUE
LDBS = LDB
*
* Call the subroutine.
*
IF( SNAME( 4: 5 ).EQ.'MM' )THEN
IF( TRACE )
$ WRITE( NTRA, FMT = 9995 )NC, SNAME,
$ SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA,
$ LDA, LDB
IF( REWI )
$ REWIND NTRA
CALL CTRMM( SIDE, UPLO, TRANSA, DIAG, M,
$ N, ALPHA, AA, LDA, BB, LDB )
ELSE IF( SNAME( 4: 5 ).EQ.'SM' )THEN
IF( TRACE )
$ WRITE( NTRA, FMT = 9995 )NC, SNAME,
$ SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA,
$ LDA, LDB
IF( REWI )
$ REWIND NTRA
CALL CTRSM( SIDE, UPLO, TRANSA, DIAG, M,
$ N, ALPHA, AA, LDA, BB, LDB )
END IF
*
* Check if error-exit was taken incorrectly.
*
IF( .NOT.OK )THEN
WRITE( NOUT, FMT = 9994 )
FATAL = .TRUE.
GO TO 150
END IF
*
* See what data changed inside subroutines.
*
ISAME( 1 ) = SIDES.EQ.SIDE
ISAME( 2 ) = UPLOS.EQ.UPLO
ISAME( 3 ) = TRANAS.EQ.TRANSA
ISAME( 4 ) = DIAGS.EQ.DIAG
ISAME( 5 ) = MS.EQ.M
ISAME( 6 ) = NS.EQ.N
ISAME( 7 ) = ALS.EQ.ALPHA
ISAME( 8 ) = LCE( AS, AA, LAA )
ISAME( 9 ) = LDAS.EQ.LDA
IF( NULL )THEN
ISAME( 10 ) = LCE( BS, BB, LBB )
ELSE
ISAME( 10 ) = LCERES( 'GE', ' ', M, N, BS,
$ BB, LDB )
END IF
ISAME( 11 ) = LDBS.EQ.LDB
*
* If data was incorrectly changed, report and
* return.
*
SAME = .TRUE.
DO 50 I = 1, NARGS
SAME = SAME.AND.ISAME( I )
IF( .NOT.ISAME( I ) )
$ WRITE( NOUT, FMT = 9998 )I
50 CONTINUE
IF( .NOT.SAME )THEN
FATAL = .TRUE.
GO TO 150
END IF
*
IF( .NOT.NULL )THEN
IF( SNAME( 4: 5 ).EQ.'MM' )THEN
*
* Check the result.
*
IF( LEFT )THEN
CALL CMMCH( TRANSA, 'N', M, N, M,
$ ALPHA, A, NMAX, B, NMAX,
$ ZERO, C, NMAX, CT, G,
$ BB, LDB, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
ELSE
CALL CMMCH( 'N', TRANSA, M, N, N,
$ ALPHA, B, NMAX, A, NMAX,
$ ZERO, C, NMAX, CT, G,
$ BB, LDB, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
END IF
ELSE IF( SNAME( 4: 5 ).EQ.'SM' )THEN
*
* Compute approximation to original
* matrix.
*
DO 70 J = 1, N
DO 60 I = 1, M
C( I, J ) = BB( I + ( J - 1 )*
$ LDB )
BB( I + ( J - 1 )*LDB ) = ALPHA*
$ B( I, J )
60 CONTINUE
70 CONTINUE
*
IF( LEFT )THEN
CALL CMMCH( TRANSA, 'N', M, N, M,
$ ONE, A, NMAX, C, NMAX,
$ ZERO, B, NMAX, CT, G,
$ BB, LDB, EPS, ERR,
$ FATAL, NOUT, .FALSE. )
ELSE
CALL CMMCH( 'N', TRANSA, M, N, N,
$ ONE, C, NMAX, A, NMAX,
$ ZERO, B, NMAX, CT, G,
$ BB, LDB, EPS, ERR,
$ FATAL, NOUT, .FALSE. )
END IF
END IF
ERRMAX = MAX( ERRMAX, ERR )
* If got really bad answer, report and
* return.
IF( FATAL )
$ GO TO 150
END IF
*
80 CONTINUE
*
90 CONTINUE
*
100 CONTINUE
*
110 CONTINUE
*
120 CONTINUE
*
130 CONTINUE
*
140 CONTINUE
*
* Report result.
*
IF( ERRMAX.LT.THRESH )THEN
WRITE( NOUT, FMT = 9999 )SNAME, NC
ELSE
WRITE( NOUT, FMT = 9997 )SNAME, NC, ERRMAX
END IF
GO TO 160
*
150 CONTINUE
WRITE( NOUT, FMT = 9996 )SNAME
WRITE( NOUT, FMT = 9995 )NC, SNAME, SIDE, UPLO, TRANSA, DIAG, M,
$ N, ALPHA, LDA, LDB
*
160 CONTINUE
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE COMPUTATIONAL TESTS (', I6, ' CALL',
$ 'S)' )
9998 FORMAT( ' ******* FATAL ERROR - PARAMETER NUMBER ', I2, ' WAS CH',
$ 'ANGED INCORRECTLY *******' )
9997 FORMAT( ' ', A6, ' COMPLETED THE COMPUTATIONAL TESTS (', I6, ' C',
$ 'ALLS)', /' ******* BUT WITH MAXIMUM TEST RATIO', F8.2,
$ ' - SUSPECT *******' )
9996 FORMAT( ' ******* ', A6, ' FAILED ON CALL NUMBER:' )
9995 FORMAT( 1X, I6, ': ', A6, '(', 4( '''', A1, ''',' ), 2( I3, ',' ),
$ '(', F4.1, ',', F4.1, '), A,', I3, ', B,', I3, ') ',
$ ' .' )
9994 FORMAT( ' ******* FATAL ERROR - ERROR-EXIT TAKEN ON VALID CALL *',
$ '******' )
*
* End of CCHK3.
*
END
SUBROUTINE CCHK4( SNAME, EPS, THRESH, NOUT, NTRA, TRACE, REWI,
$ FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET, NMAX,
$ A, AA, AS, B, BB, BS, C, CC, CS, CT, G )
*
* Tests CHERK and CSYRK.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO
PARAMETER ( ZERO = ( 0.0, 0.0 ) )
REAL RONE, RZERO
PARAMETER ( RONE = 1.0, RZERO = 0.0 )
* .. Scalar Arguments ..
REAL EPS, THRESH
INTEGER NALF, NBET, NIDIM, NMAX, NOUT, NTRA
LOGICAL FATAL, REWI, TRACE
CHARACTER*6 SNAME
* .. Array Arguments ..
COMPLEX A( NMAX, NMAX ), AA( NMAX*NMAX ), ALF( NALF ),
$ AS( NMAX*NMAX ), B( NMAX, NMAX ),
$ BB( NMAX*NMAX ), BET( NBET ), BS( NMAX*NMAX ),
$ C( NMAX, NMAX ), CC( NMAX*NMAX ),
$ CS( NMAX*NMAX ), CT( NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDIM )
* .. Local Scalars ..
COMPLEX ALPHA, ALS, BETA, BETS
REAL ERR, ERRMAX, RALPHA, RALS, RBETA, RBETS
INTEGER I, IA, IB, ICT, ICU, IK, IN, J, JC, JJ, K, KS,
$ LAA, LCC, LDA, LDAS, LDC, LDCS, LJ, MA, N, NA,
$ NARGS, NC, NS
LOGICAL CONJ, NULL, RESET, SAME, TRAN, UPPER
CHARACTER*1 TRANS, TRANSS, TRANST, UPLO, UPLOS
CHARACTER*2 ICHT, ICHU
* .. Local Arrays ..
LOGICAL ISAME( 13 )
* .. External Functions ..
LOGICAL LCE, LCERES
EXTERNAL LCE, LCERES
* .. External Subroutines ..
EXTERNAL CHERK, CMAKE, CMMCH, CSYRK
* .. Intrinsic Functions ..
INTRINSIC CMPLX, MAX, REAL
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Data statements ..
DATA ICHT/'NC'/, ICHU/'UL'/
* .. Executable Statements ..
CONJ = SNAME( 2: 3 ).EQ.'HE'
*
NARGS = 10
NC = 0
RESET = .TRUE.
ERRMAX = RZERO
RALS = RONE
RBETS = RONE
*
DO 100 IN = 1, NIDIM
N = IDIM( IN )
* Set LDC to 1 more than minimum value if room.
LDC = N
IF( LDC.LT.NMAX )
$ LDC = LDC + 1
* Skip tests if not enough room.
IF( LDC.GT.NMAX )
$ GO TO 100
LCC = LDC*N
*
DO 90 IK = 1, NIDIM
K = IDIM( IK )
*
DO 80 ICT = 1, 2
TRANS = ICHT( ICT: ICT )
TRAN = TRANS.EQ.'C'
IF( TRAN.AND..NOT.CONJ )
$ TRANS = 'T'
IF( TRAN )THEN
MA = K
NA = N
ELSE
MA = N
NA = K
END IF
* Set LDA to 1 more than minimum value if room.
LDA = MA
IF( LDA.LT.NMAX )
$ LDA = LDA + 1
* Skip tests if not enough room.
IF( LDA.GT.NMAX )
$ GO TO 80
LAA = LDA*NA
*
* Generate the matrix A.
*
CALL CMAKE( 'GE', ' ', ' ', MA, NA, A, NMAX, AA, LDA,
$ RESET, ZERO )
*
DO 70 ICU = 1, 2
UPLO = ICHU( ICU: ICU )
UPPER = UPLO.EQ.'U'
*
DO 60 IA = 1, NALF
ALPHA = ALF( IA )
IF( CONJ )THEN
RALPHA = REAL( ALPHA )
ALPHA = CMPLX( RALPHA, RZERO )
END IF
*
DO 50 IB = 1, NBET
BETA = BET( IB )
IF( CONJ )THEN
RBETA = REAL( BETA )
BETA = CMPLX( RBETA, RZERO )
END IF
NULL = N.LE.0
IF( CONJ )
$ NULL = NULL.OR.( ( K.LE.0.OR.RALPHA.EQ.
$ RZERO ).AND.RBETA.EQ.RONE )
*
* Generate the matrix C.
*
CALL CMAKE( SNAME( 2: 3 ), UPLO, ' ', N, N, C,
$ NMAX, CC, LDC, RESET, ZERO )
*
NC = NC + 1
*
* Save every datum before calling the subroutine.
*
UPLOS = UPLO
TRANSS = TRANS
NS = N
KS = K
IF( CONJ )THEN
RALS = RALPHA
ELSE
ALS = ALPHA
END IF
DO 10 I = 1, LAA
AS( I ) = AA( I )
10 CONTINUE
LDAS = LDA
IF( CONJ )THEN
RBETS = RBETA
ELSE
BETS = BETA
END IF
DO 20 I = 1, LCC
CS( I ) = CC( I )
20 CONTINUE
LDCS = LDC
*
* Call the subroutine.
*
IF( CONJ )THEN
IF( TRACE )
$ WRITE( NTRA, FMT = 9994 )NC, SNAME, UPLO,
$ TRANS, N, K, RALPHA, LDA, RBETA, LDC
IF( REWI )
$ REWIND NTRA
CALL CHERK( UPLO, TRANS, N, K, RALPHA, AA,
$ LDA, RBETA, CC, LDC )
ELSE
IF( TRACE )
$ WRITE( NTRA, FMT = 9993 )NC, SNAME, UPLO,
$ TRANS, N, K, ALPHA, LDA, BETA, LDC
IF( REWI )
$ REWIND NTRA
CALL CSYRK( UPLO, TRANS, N, K, ALPHA, AA,
$ LDA, BETA, CC, LDC )
END IF
*
* Check if error-exit was taken incorrectly.
*
IF( .NOT.OK )THEN
WRITE( NOUT, FMT = 9992 )
FATAL = .TRUE.
GO TO 120
END IF
*
* See what data changed inside subroutines.
*
ISAME( 1 ) = UPLOS.EQ.UPLO
ISAME( 2 ) = TRANSS.EQ.TRANS
ISAME( 3 ) = NS.EQ.N
ISAME( 4 ) = KS.EQ.K
IF( CONJ )THEN
ISAME( 5 ) = RALS.EQ.RALPHA
ELSE
ISAME( 5 ) = ALS.EQ.ALPHA
END IF
ISAME( 6 ) = LCE( AS, AA, LAA )
ISAME( 7 ) = LDAS.EQ.LDA
IF( CONJ )THEN
ISAME( 8 ) = RBETS.EQ.RBETA
ELSE
ISAME( 8 ) = BETS.EQ.BETA
END IF
IF( NULL )THEN
ISAME( 9 ) = LCE( CS, CC, LCC )
ELSE
ISAME( 9 ) = LCERES( SNAME( 2: 3 ), UPLO, N,
$ N, CS, CC, LDC )
END IF
ISAME( 10 ) = LDCS.EQ.LDC
*
* If data was incorrectly changed, report and
* return.
*
SAME = .TRUE.
DO 30 I = 1, NARGS
SAME = SAME.AND.ISAME( I )
IF( .NOT.ISAME( I ) )
$ WRITE( NOUT, FMT = 9998 )I
30 CONTINUE
IF( .NOT.SAME )THEN
FATAL = .TRUE.
GO TO 120
END IF
*
IF( .NOT.NULL )THEN
*
* Check the result column by column.
*
IF( CONJ )THEN
TRANST = 'C'
ELSE
TRANST = 'T'
END IF
JC = 1
DO 40 J = 1, N
IF( UPPER )THEN
JJ = 1
LJ = J
ELSE
JJ = J
LJ = N - J + 1
END IF
IF( TRAN )THEN
CALL CMMCH( TRANST, 'N', LJ, 1, K,
$ ALPHA, A( 1, JJ ), NMAX,
$ A( 1, J ), NMAX, BETA,
$ C( JJ, J ), NMAX, CT, G,
$ CC( JC ), LDC, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
ELSE
CALL CMMCH( 'N', TRANST, LJ, 1, K,
$ ALPHA, A( JJ, 1 ), NMAX,
$ A( J, 1 ), NMAX, BETA,
$ C( JJ, J ), NMAX, CT, G,
$ CC( JC ), LDC, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
END IF
IF( UPPER )THEN
JC = JC + LDC
ELSE
JC = JC + LDC + 1
END IF
ERRMAX = MAX( ERRMAX, ERR )
* If got really bad answer, report and
* return.
IF( FATAL )
$ GO TO 110
40 CONTINUE
END IF
*
50 CONTINUE
*
60 CONTINUE
*
70 CONTINUE
*
80 CONTINUE
*
90 CONTINUE
*
100 CONTINUE
*
* Report result.
*
IF( ERRMAX.LT.THRESH )THEN
WRITE( NOUT, FMT = 9999 )SNAME, NC
ELSE
WRITE( NOUT, FMT = 9997 )SNAME, NC, ERRMAX
END IF
GO TO 130
*
110 CONTINUE
IF( N.GT.1 )
$ WRITE( NOUT, FMT = 9995 )J
*
120 CONTINUE
WRITE( NOUT, FMT = 9996 )SNAME
IF( CONJ )THEN
WRITE( NOUT, FMT = 9994 )NC, SNAME, UPLO, TRANS, N, K, RALPHA,
$ LDA, RBETA, LDC
ELSE
WRITE( NOUT, FMT = 9993 )NC, SNAME, UPLO, TRANS, N, K, ALPHA,
$ LDA, BETA, LDC
END IF
*
130 CONTINUE
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE COMPUTATIONAL TESTS (', I6, ' CALL',
$ 'S)' )
9998 FORMAT( ' ******* FATAL ERROR - PARAMETER NUMBER ', I2, ' WAS CH',
$ 'ANGED INCORRECTLY *******' )
9997 FORMAT( ' ', A6, ' COMPLETED THE COMPUTATIONAL TESTS (', I6, ' C',
$ 'ALLS)', /' ******* BUT WITH MAXIMUM TEST RATIO', F8.2,
$ ' - SUSPECT *******' )
9996 FORMAT( ' ******* ', A6, ' FAILED ON CALL NUMBER:' )
9995 FORMAT( ' THESE ARE THE RESULTS FOR COLUMN ', I3 )
9994 FORMAT( 1X, I6, ': ', A6, '(', 2( '''', A1, ''',' ), 2( I3, ',' ),
$ F4.1, ', A,', I3, ',', F4.1, ', C,', I3, ') ',
$ ' .' )
9993 FORMAT( 1X, I6, ': ', A6, '(', 2( '''', A1, ''',' ), 2( I3, ',' ),
$ '(', F4.1, ',', F4.1, ') , A,', I3, ',(', F4.1, ',', F4.1,
$ '), C,', I3, ') .' )
9992 FORMAT( ' ******* FATAL ERROR - ERROR-EXIT TAKEN ON VALID CALL *',
$ '******' )
*
* End of CCHK4.
*
END
SUBROUTINE CCHK5( SNAME, EPS, THRESH, NOUT, NTRA, TRACE, REWI,
$ FATAL, NIDIM, IDIM, NALF, ALF, NBET, BET, NMAX,
$ AB, AA, AS, BB, BS, C, CC, CS, CT, G, W )
*
* Tests CHER2K and CSYR2K.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO, ONE
PARAMETER ( ZERO = ( 0.0, 0.0 ), ONE = ( 1.0, 0.0 ) )
REAL RONE, RZERO
PARAMETER ( RONE = 1.0, RZERO = 0.0 )
* .. Scalar Arguments ..
REAL EPS, THRESH
INTEGER NALF, NBET, NIDIM, NMAX, NOUT, NTRA
LOGICAL FATAL, REWI, TRACE
CHARACTER*6 SNAME
* .. Array Arguments ..
COMPLEX AA( NMAX*NMAX ), AB( 2*NMAX*NMAX ),
$ ALF( NALF ), AS( NMAX*NMAX ), BB( NMAX*NMAX ),
$ BET( NBET ), BS( NMAX*NMAX ), C( NMAX, NMAX ),
$ CC( NMAX*NMAX ), CS( NMAX*NMAX ), CT( NMAX ),
$ W( 2*NMAX )
REAL G( NMAX )
INTEGER IDIM( NIDIM )
* .. Local Scalars ..
COMPLEX ALPHA, ALS, BETA, BETS
REAL ERR, ERRMAX, RBETA, RBETS
INTEGER I, IA, IB, ICT, ICU, IK, IN, J, JC, JJ, JJAB,
$ K, KS, LAA, LBB, LCC, LDA, LDAS, LDB, LDBS,
$ LDC, LDCS, LJ, MA, N, NA, NARGS, NC, NS
LOGICAL CONJ, NULL, RESET, SAME, TRAN, UPPER
CHARACTER*1 TRANS, TRANSS, TRANST, UPLO, UPLOS
CHARACTER*2 ICHT, ICHU
* .. Local Arrays ..
LOGICAL ISAME( 13 )
* .. External Functions ..
LOGICAL LCE, LCERES
EXTERNAL LCE, LCERES
* .. External Subroutines ..
EXTERNAL CHER2K, CMAKE, CMMCH, CSYR2K
* .. Intrinsic Functions ..
INTRINSIC CMPLX, CONJG, MAX, REAL
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Data statements ..
DATA ICHT/'NC'/, ICHU/'UL'/
* .. Executable Statements ..
CONJ = SNAME( 2: 3 ).EQ.'HE'
*
NARGS = 12
NC = 0
RESET = .TRUE.
ERRMAX = RZERO
*
DO 130 IN = 1, NIDIM
N = IDIM( IN )
* Set LDC to 1 more than minimum value if room.
LDC = N
IF( LDC.LT.NMAX )
$ LDC = LDC + 1
* Skip tests if not enough room.
IF( LDC.GT.NMAX )
$ GO TO 130
LCC = LDC*N
*
DO 120 IK = 1, NIDIM
K = IDIM( IK )
*
DO 110 ICT = 1, 2
TRANS = ICHT( ICT: ICT )
TRAN = TRANS.EQ.'C'
IF( TRAN.AND..NOT.CONJ )
$ TRANS = 'T'
IF( TRAN )THEN
MA = K
NA = N
ELSE
MA = N
NA = K
END IF
* Set LDA to 1 more than minimum value if room.
LDA = MA
IF( LDA.LT.NMAX )
$ LDA = LDA + 1
* Skip tests if not enough room.
IF( LDA.GT.NMAX )
$ GO TO 110
LAA = LDA*NA
*
* Generate the matrix A.
*
IF( TRAN )THEN
CALL CMAKE( 'GE', ' ', ' ', MA, NA, AB, 2*NMAX, AA,
$ LDA, RESET, ZERO )
ELSE
CALL CMAKE( 'GE', ' ', ' ', MA, NA, AB, NMAX, AA, LDA,
$ RESET, ZERO )
END IF
*
* Generate the matrix B.
*
LDB = LDA
LBB = LAA
IF( TRAN )THEN
CALL CMAKE( 'GE', ' ', ' ', MA, NA, AB( K + 1 ),
$ 2*NMAX, BB, LDB, RESET, ZERO )
ELSE
CALL CMAKE( 'GE', ' ', ' ', MA, NA, AB( K*NMAX + 1 ),
$ NMAX, BB, LDB, RESET, ZERO )
END IF
*
DO 100 ICU = 1, 2
UPLO = ICHU( ICU: ICU )
UPPER = UPLO.EQ.'U'
*
DO 90 IA = 1, NALF
ALPHA = ALF( IA )
*
DO 80 IB = 1, NBET
BETA = BET( IB )
IF( CONJ )THEN
RBETA = REAL( BETA )
BETA = CMPLX( RBETA, RZERO )
END IF
NULL = N.LE.0
IF( CONJ )
$ NULL = NULL.OR.( ( K.LE.0.OR.ALPHA.EQ.
$ ZERO ).AND.RBETA.EQ.RONE )
*
* Generate the matrix C.
*
CALL CMAKE( SNAME( 2: 3 ), UPLO, ' ', N, N, C,
$ NMAX, CC, LDC, RESET, ZERO )
*
NC = NC + 1
*
* Save every datum before calling the subroutine.
*
UPLOS = UPLO
TRANSS = TRANS
NS = N
KS = K
ALS = ALPHA
DO 10 I = 1, LAA
AS( I ) = AA( I )
10 CONTINUE
LDAS = LDA
DO 20 I = 1, LBB
BS( I ) = BB( I )
20 CONTINUE
LDBS = LDB
IF( CONJ )THEN
RBETS = RBETA
ELSE
BETS = BETA
END IF
DO 30 I = 1, LCC
CS( I ) = CC( I )
30 CONTINUE
LDCS = LDC
*
* Call the subroutine.
*
IF( CONJ )THEN
IF( TRACE )
$ WRITE( NTRA, FMT = 9994 )NC, SNAME, UPLO,
$ TRANS, N, K, ALPHA, LDA, LDB, RBETA, LDC
IF( REWI )
$ REWIND NTRA
CALL CHER2K( UPLO, TRANS, N, K, ALPHA, AA,
$ LDA, BB, LDB, RBETA, CC, LDC )
ELSE
IF( TRACE )
$ WRITE( NTRA, FMT = 9993 )NC, SNAME, UPLO,
$ TRANS, N, K, ALPHA, LDA, LDB, BETA, LDC
IF( REWI )
$ REWIND NTRA
CALL CSYR2K( UPLO, TRANS, N, K, ALPHA, AA,
$ LDA, BB, LDB, BETA, CC, LDC )
END IF
*
* Check if error-exit was taken incorrectly.
*
IF( .NOT.OK )THEN
WRITE( NOUT, FMT = 9992 )
FATAL = .TRUE.
GO TO 150
END IF
*
* See what data changed inside subroutines.
*
ISAME( 1 ) = UPLOS.EQ.UPLO
ISAME( 2 ) = TRANSS.EQ.TRANS
ISAME( 3 ) = NS.EQ.N
ISAME( 4 ) = KS.EQ.K
ISAME( 5 ) = ALS.EQ.ALPHA
ISAME( 6 ) = LCE( AS, AA, LAA )
ISAME( 7 ) = LDAS.EQ.LDA
ISAME( 8 ) = LCE( BS, BB, LBB )
ISAME( 9 ) = LDBS.EQ.LDB
IF( CONJ )THEN
ISAME( 10 ) = RBETS.EQ.RBETA
ELSE
ISAME( 10 ) = BETS.EQ.BETA
END IF
IF( NULL )THEN
ISAME( 11 ) = LCE( CS, CC, LCC )
ELSE
ISAME( 11 ) = LCERES( 'HE', UPLO, N, N, CS,
$ CC, LDC )
END IF
ISAME( 12 ) = LDCS.EQ.LDC
*
* If data was incorrectly changed, report and
* return.
*
SAME = .TRUE.
DO 40 I = 1, NARGS
SAME = SAME.AND.ISAME( I )
IF( .NOT.ISAME( I ) )
$ WRITE( NOUT, FMT = 9998 )I
40 CONTINUE
IF( .NOT.SAME )THEN
FATAL = .TRUE.
GO TO 150
END IF
*
IF( .NOT.NULL )THEN
*
* Check the result column by column.
*
IF( CONJ )THEN
TRANST = 'C'
ELSE
TRANST = 'T'
END IF
JJAB = 1
JC = 1
DO 70 J = 1, N
IF( UPPER )THEN
JJ = 1
LJ = J
ELSE
JJ = J
LJ = N - J + 1
END IF
IF( TRAN )THEN
DO 50 I = 1, K
W( I ) = ALPHA*AB( ( J - 1 )*2*
$ NMAX + K + I )
IF( CONJ )THEN
W( K + I ) = CONJG( ALPHA )*
$ AB( ( J - 1 )*2*
$ NMAX + I )
ELSE
W( K + I ) = ALPHA*
$ AB( ( J - 1 )*2*
$ NMAX + I )
END IF
50 CONTINUE
CALL CMMCH( TRANST, 'N', LJ, 1, 2*K,
$ ONE, AB( JJAB ), 2*NMAX, W,
$ 2*NMAX, BETA, C( JJ, J ),
$ NMAX, CT, G, CC( JC ), LDC,
$ EPS, ERR, FATAL, NOUT,
$ .TRUE. )
ELSE
DO 60 I = 1, K
IF( CONJ )THEN
W( I ) = ALPHA*CONJG( AB( ( K +
$ I - 1 )*NMAX + J ) )
W( K + I ) = CONJG( ALPHA*
$ AB( ( I - 1 )*NMAX +
$ J ) )
ELSE
W( I ) = ALPHA*AB( ( K + I - 1 )*
$ NMAX + J )
W( K + I ) = ALPHA*
$ AB( ( I - 1 )*NMAX +
$ J )
END IF
60 CONTINUE
CALL CMMCH( 'N', 'N', LJ, 1, 2*K, ONE,
$ AB( JJ ), NMAX, W, 2*NMAX,
$ BETA, C( JJ, J ), NMAX, CT,
$ G, CC( JC ), LDC, EPS, ERR,
$ FATAL, NOUT, .TRUE. )
END IF
IF( UPPER )THEN
JC = JC + LDC
ELSE
JC = JC + LDC + 1
IF( TRAN )
$ JJAB = JJAB + 2*NMAX
END IF
ERRMAX = MAX( ERRMAX, ERR )
* If got really bad answer, report and
* return.
IF( FATAL )
$ GO TO 140
70 CONTINUE
END IF
*
80 CONTINUE
*
90 CONTINUE
*
100 CONTINUE
*
110 CONTINUE
*
120 CONTINUE
*
130 CONTINUE
*
* Report result.
*
IF( ERRMAX.LT.THRESH )THEN
WRITE( NOUT, FMT = 9999 )SNAME, NC
ELSE
WRITE( NOUT, FMT = 9997 )SNAME, NC, ERRMAX
END IF
GO TO 160
*
140 CONTINUE
IF( N.GT.1 )
$ WRITE( NOUT, FMT = 9995 )J
*
150 CONTINUE
WRITE( NOUT, FMT = 9996 )SNAME
IF( CONJ )THEN
WRITE( NOUT, FMT = 9994 )NC, SNAME, UPLO, TRANS, N, K, ALPHA,
$ LDA, LDB, RBETA, LDC
ELSE
WRITE( NOUT, FMT = 9993 )NC, SNAME, UPLO, TRANS, N, K, ALPHA,
$ LDA, LDB, BETA, LDC
END IF
*
160 CONTINUE
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE COMPUTATIONAL TESTS (', I6, ' CALL',
$ 'S)' )
9998 FORMAT( ' ******* FATAL ERROR - PARAMETER NUMBER ', I2, ' WAS CH',
$ 'ANGED INCORRECTLY *******' )
9997 FORMAT( ' ', A6, ' COMPLETED THE COMPUTATIONAL TESTS (', I6, ' C',
$ 'ALLS)', /' ******* BUT WITH MAXIMUM TEST RATIO', F8.2,
$ ' - SUSPECT *******' )
9996 FORMAT( ' ******* ', A6, ' FAILED ON CALL NUMBER:' )
9995 FORMAT( ' THESE ARE THE RESULTS FOR COLUMN ', I3 )
9994 FORMAT( 1X, I6, ': ', A6, '(', 2( '''', A1, ''',' ), 2( I3, ',' ),
$ '(', F4.1, ',', F4.1, '), A,', I3, ', B,', I3, ',', F4.1,
$ ', C,', I3, ') .' )
9993 FORMAT( 1X, I6, ': ', A6, '(', 2( '''', A1, ''',' ), 2( I3, ',' ),
$ '(', F4.1, ',', F4.1, '), A,', I3, ', B,', I3, ',(', F4.1,
$ ',', F4.1, '), C,', I3, ') .' )
9992 FORMAT( ' ******* FATAL ERROR - ERROR-EXIT TAKEN ON VALID CALL *',
$ '******' )
*
* End of CCHK5.
*
END
SUBROUTINE CCHKE( ISNUM, SRNAMT, NOUT )
*
* Tests the error exits from the Level 3 Blas.
* Requires a special version of the error-handling routine XERBLA.
* ALPHA, RALPHA, BETA, RBETA, A, B and C should not need to be defined.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
INTEGER ISNUM, NOUT
CHARACTER*6 SRNAMT
* .. Scalars in Common ..
INTEGER INFOT, NOUTC
LOGICAL LERR, OK
* .. Local Scalars ..
COMPLEX ALPHA, BETA
REAL RALPHA, RBETA
* .. Local Arrays ..
COMPLEX A( 2, 1 ), B( 2, 1 ), C( 2, 1 )
* .. External Subroutines ..
EXTERNAL CGEMM, CHEMM, CHER2K, CHERK, CHKXER, CSYMM,
$ CSYR2K, CSYRK, CTRMM, CTRSM
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUTC, OK, LERR
* .. Executable Statements ..
* OK is set to .FALSE. by the special version of XERBLA or by CHKXER
* if anything is wrong.
OK = .TRUE.
* LERR is set to .TRUE. by the special version of XERBLA each time
* it is called, and is then tested and re-set by CHKXER.
LERR = .FALSE.
GO TO ( 10, 20, 30, 40, 50, 60, 70, 80,
$ 90 )ISNUM
10 INFOT = 1
CALL CGEMM( '/', 'N', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 1
CALL CGEMM( '/', 'C', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 1
CALL CGEMM( '/', 'T', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CGEMM( 'N', '/', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CGEMM( 'C', '/', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CGEMM( 'T', '/', 0, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'N', 'N', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'N', 'C', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'N', 'T', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'C', 'N', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'C', 'C', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'C', 'T', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'T', 'N', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'T', 'C', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CGEMM( 'T', 'T', -1, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'N', 'N', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'N', 'C', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'N', 'T', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'C', 'N', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'C', 'C', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'C', 'T', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'T', 'N', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'T', 'C', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CGEMM( 'T', 'T', 0, -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'N', 'N', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'N', 'C', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'N', 'T', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'C', 'N', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'C', 'C', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'C', 'T', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'T', 'N', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'T', 'C', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CGEMM( 'T', 'T', 0, 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'N', 'N', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'N', 'C', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'N', 'T', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'C', 'N', 0, 0, 2, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'C', 'C', 0, 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'C', 'T', 0, 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'T', 'N', 0, 0, 2, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'T', 'C', 0, 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 8
CALL CGEMM( 'T', 'T', 0, 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'N', 'N', 0, 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'C', 'N', 0, 0, 2, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'T', 'N', 0, 0, 2, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'N', 'C', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'C', 'C', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'T', 'C', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'N', 'T', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'C', 'T', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CGEMM( 'T', 'T', 0, 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'N', 'N', 2, 0, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'N', 'C', 2, 0, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'N', 'T', 2, 0, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'C', 'N', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'C', 'C', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'C', 'T', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'T', 'N', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'T', 'C', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 13
CALL CGEMM( 'T', 'T', 2, 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
20 INFOT = 1
CALL CHEMM( '/', 'U', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CHEMM( 'L', '/', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHEMM( 'L', 'U', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHEMM( 'R', 'U', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHEMM( 'L', 'L', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHEMM( 'R', 'L', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHEMM( 'L', 'U', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHEMM( 'R', 'U', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHEMM( 'L', 'L', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHEMM( 'R', 'L', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHEMM( 'L', 'U', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHEMM( 'R', 'U', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHEMM( 'L', 'L', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHEMM( 'R', 'L', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHEMM( 'L', 'U', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHEMM( 'R', 'U', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHEMM( 'L', 'L', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHEMM( 'R', 'L', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHEMM( 'L', 'U', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHEMM( 'R', 'U', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHEMM( 'L', 'L', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHEMM( 'R', 'L', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
30 INFOT = 1
CALL CSYMM( '/', 'U', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CSYMM( 'L', '/', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYMM( 'L', 'U', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYMM( 'R', 'U', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYMM( 'L', 'L', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYMM( 'R', 'L', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYMM( 'L', 'U', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYMM( 'R', 'U', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYMM( 'L', 'L', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYMM( 'R', 'L', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYMM( 'L', 'U', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYMM( 'R', 'U', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYMM( 'L', 'L', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYMM( 'R', 'L', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYMM( 'L', 'U', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYMM( 'R', 'U', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYMM( 'L', 'L', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYMM( 'R', 'L', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYMM( 'L', 'U', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYMM( 'R', 'U', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYMM( 'L', 'L', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYMM( 'R', 'L', 2, 0, ALPHA, A, 1, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
40 INFOT = 1
CALL CTRMM( '/', 'U', 'N', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CTRMM( 'L', '/', 'N', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CTRMM( 'L', 'U', '/', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CTRMM( 'L', 'U', 'N', '/', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'U', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'U', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'U', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'U', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'U', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'U', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'L', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'L', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'L', 'L', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'L', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'L', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRMM( 'R', 'L', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'U', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'U', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'U', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'U', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'U', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'U', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'L', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'L', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'L', 'L', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'L', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'L', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRMM( 'R', 'L', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'U', 'N', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'U', 'C', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'U', 'T', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'U', 'N', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'U', 'C', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'U', 'T', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'L', 'N', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'L', 'C', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'L', 'L', 'T', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'L', 'N', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'L', 'C', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRMM( 'R', 'L', 'T', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'U', 'N', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'U', 'C', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'U', 'T', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'U', 'N', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'U', 'C', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'U', 'T', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'L', 'N', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'L', 'C', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'L', 'L', 'T', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'L', 'N', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'L', 'C', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRMM( 'R', 'L', 'T', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
50 INFOT = 1
CALL CTRSM( '/', 'U', 'N', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CTRSM( 'L', '/', 'N', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CTRSM( 'L', 'U', '/', 'N', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CTRSM( 'L', 'U', 'N', '/', 0, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'U', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'U', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'U', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'U', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'U', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'U', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'L', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'L', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'L', 'L', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'L', 'N', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'L', 'C', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 5
CALL CTRSM( 'R', 'L', 'T', 'N', -1, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'U', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'U', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'U', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'U', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'U', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'U', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'L', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'L', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'L', 'L', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'L', 'N', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'L', 'C', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 6
CALL CTRSM( 'R', 'L', 'T', 'N', 0, -1, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'U', 'N', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'U', 'C', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'U', 'T', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'U', 'N', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'U', 'C', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'U', 'T', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'L', 'N', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'L', 'C', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'L', 'L', 'T', 'N', 2, 0, ALPHA, A, 1, B, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'L', 'N', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'L', 'C', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CTRSM( 'R', 'L', 'T', 'N', 0, 2, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'U', 'N', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'U', 'C', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'U', 'T', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'U', 'N', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'U', 'C', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'U', 'T', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'L', 'N', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'L', 'C', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'L', 'L', 'T', 'N', 2, 0, ALPHA, A, 2, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'L', 'N', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'L', 'C', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 11
CALL CTRSM( 'R', 'L', 'T', 'N', 2, 0, ALPHA, A, 1, B, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
60 INFOT = 1
CALL CHERK( '/', 'N', 0, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CHERK( 'U', 'T', 0, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHERK( 'U', 'N', -1, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHERK( 'U', 'C', -1, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHERK( 'L', 'N', -1, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHERK( 'L', 'C', -1, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHERK( 'U', 'N', 0, -1, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHERK( 'U', 'C', 0, -1, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHERK( 'L', 'N', 0, -1, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHERK( 'L', 'C', 0, -1, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHERK( 'U', 'N', 2, 0, RALPHA, A, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHERK( 'U', 'C', 0, 2, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHERK( 'L', 'N', 2, 0, RALPHA, A, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHERK( 'L', 'C', 0, 2, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CHERK( 'U', 'N', 2, 0, RALPHA, A, 2, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CHERK( 'U', 'C', 2, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CHERK( 'L', 'N', 2, 0, RALPHA, A, 2, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CHERK( 'L', 'C', 2, 0, RALPHA, A, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
70 INFOT = 1
CALL CSYRK( '/', 'N', 0, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CSYRK( 'U', 'C', 0, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYRK( 'U', 'N', -1, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYRK( 'U', 'T', -1, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYRK( 'L', 'N', -1, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYRK( 'L', 'T', -1, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYRK( 'U', 'N', 0, -1, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYRK( 'U', 'T', 0, -1, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYRK( 'L', 'N', 0, -1, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYRK( 'L', 'T', 0, -1, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYRK( 'U', 'N', 2, 0, ALPHA, A, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYRK( 'U', 'T', 0, 2, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYRK( 'L', 'N', 2, 0, ALPHA, A, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYRK( 'L', 'T', 0, 2, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CSYRK( 'U', 'N', 2, 0, ALPHA, A, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CSYRK( 'U', 'T', 2, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CSYRK( 'L', 'N', 2, 0, ALPHA, A, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 10
CALL CSYRK( 'L', 'T', 2, 0, ALPHA, A, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
80 INFOT = 1
CALL CHER2K( '/', 'N', 0, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CHER2K( 'U', 'T', 0, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHER2K( 'U', 'N', -1, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHER2K( 'U', 'C', -1, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHER2K( 'L', 'N', -1, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CHER2K( 'L', 'C', -1, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHER2K( 'U', 'N', 0, -1, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHER2K( 'U', 'C', 0, -1, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHER2K( 'L', 'N', 0, -1, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CHER2K( 'L', 'C', 0, -1, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHER2K( 'U', 'N', 2, 0, ALPHA, A, 1, B, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHER2K( 'U', 'C', 0, 2, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHER2K( 'L', 'N', 2, 0, ALPHA, A, 1, B, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CHER2K( 'L', 'C', 0, 2, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHER2K( 'U', 'N', 2, 0, ALPHA, A, 2, B, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHER2K( 'U', 'C', 0, 2, ALPHA, A, 2, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHER2K( 'L', 'N', 2, 0, ALPHA, A, 2, B, 1, RBETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CHER2K( 'L', 'C', 0, 2, ALPHA, A, 2, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHER2K( 'U', 'N', 2, 0, ALPHA, A, 2, B, 2, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHER2K( 'U', 'C', 2, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHER2K( 'L', 'N', 2, 0, ALPHA, A, 2, B, 2, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CHER2K( 'L', 'C', 2, 0, ALPHA, A, 1, B, 1, RBETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
GO TO 100
90 INFOT = 1
CALL CSYR2K( '/', 'N', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 2
CALL CSYR2K( 'U', 'C', 0, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYR2K( 'U', 'N', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYR2K( 'U', 'T', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYR2K( 'L', 'N', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 3
CALL CSYR2K( 'L', 'T', -1, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYR2K( 'U', 'N', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYR2K( 'U', 'T', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYR2K( 'L', 'N', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 4
CALL CSYR2K( 'L', 'T', 0, -1, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYR2K( 'U', 'N', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYR2K( 'U', 'T', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYR2K( 'L', 'N', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 7
CALL CSYR2K( 'L', 'T', 0, 2, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYR2K( 'U', 'N', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYR2K( 'U', 'T', 0, 2, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYR2K( 'L', 'N', 2, 0, ALPHA, A, 2, B, 1, BETA, C, 2 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 9
CALL CSYR2K( 'L', 'T', 0, 2, ALPHA, A, 2, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYR2K( 'U', 'N', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYR2K( 'U', 'T', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYR2K( 'L', 'N', 2, 0, ALPHA, A, 2, B, 2, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
INFOT = 12
CALL CSYR2K( 'L', 'T', 2, 0, ALPHA, A, 1, B, 1, BETA, C, 1 )
CALL CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
*
100 IF( OK )THEN
WRITE( NOUT, FMT = 9999 )SRNAMT
ELSE
WRITE( NOUT, FMT = 9998 )SRNAMT
END IF
RETURN
*
9999 FORMAT( ' ', A6, ' PASSED THE TESTS OF ERROR-EXITS' )
9998 FORMAT( ' ******* ', A6, ' FAILED THE TESTS OF ERROR-EXITS *****',
$ '**' )
*
* End of CCHKE.
*
END
SUBROUTINE CMAKE( TYPE, UPLO, DIAG, M, N, A, NMAX, AA, LDA, RESET,
$ TRANSL )
*
* Generates values for an M by N matrix A.
* Stores the values in the array AA in the data structure required
* by the routine, with unwanted elements set to rogue value.
*
* TYPE is 'GE', 'HE', 'SY' or 'TR'.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO, ONE
PARAMETER ( ZERO = ( 0.0, 0.0 ), ONE = ( 1.0, 0.0 ) )
COMPLEX ROGUE
PARAMETER ( ROGUE = ( -1.0E10, 1.0E10 ) )
REAL RZERO
PARAMETER ( RZERO = 0.0 )
REAL RROGUE
PARAMETER ( RROGUE = -1.0E10 )
* .. Scalar Arguments ..
COMPLEX TRANSL
INTEGER LDA, M, N, NMAX
LOGICAL RESET
CHARACTER*1 DIAG, UPLO
CHARACTER*2 TYPE
* .. Array Arguments ..
COMPLEX A( NMAX, * ), AA( * )
* .. Local Scalars ..
INTEGER I, IBEG, IEND, J, JJ
LOGICAL GEN, HER, LOWER, SYM, TRI, UNIT, UPPER
* .. External Functions ..
COMPLEX CBEG
EXTERNAL CBEG
* .. Intrinsic Functions ..
INTRINSIC CMPLX, CONJG, REAL
* .. Executable Statements ..
GEN = TYPE.EQ.'GE'
HER = TYPE.EQ.'HE'
SYM = TYPE.EQ.'SY'
TRI = TYPE.EQ.'TR'
UPPER = ( HER.OR.SYM.OR.TRI ).AND.UPLO.EQ.'U'
LOWER = ( HER.OR.SYM.OR.TRI ).AND.UPLO.EQ.'L'
UNIT = TRI.AND.DIAG.EQ.'U'
*
* Generate data in array A.
*
DO 20 J = 1, N
DO 10 I = 1, M
IF( GEN.OR.( UPPER.AND.I.LE.J ).OR.( LOWER.AND.I.GE.J ) )
$ THEN
A( I, J ) = CBEG( RESET ) + TRANSL
IF( I.NE.J )THEN
* Set some elements to zero
IF( N.GT.3.AND.J.EQ.N/2 )
$ A( I, J ) = ZERO
IF( HER )THEN
A( J, I ) = CONJG( A( I, J ) )
ELSE IF( SYM )THEN
A( J, I ) = A( I, J )
ELSE IF( TRI )THEN
A( J, I ) = ZERO
END IF
END IF
END IF
10 CONTINUE
IF( HER )
$ A( J, J ) = CMPLX( REAL( A( J, J ) ), RZERO )
IF( TRI )
$ A( J, J ) = A( J, J ) + ONE
IF( UNIT )
$ A( J, J ) = ONE
20 CONTINUE
*
* Store elements in array AS in data structure required by routine.
*
IF( TYPE.EQ.'GE' )THEN
DO 50 J = 1, N
DO 30 I = 1, M
AA( I + ( J - 1 )*LDA ) = A( I, J )
30 CONTINUE
DO 40 I = M + 1, LDA
AA( I + ( J - 1 )*LDA ) = ROGUE
40 CONTINUE
50 CONTINUE
ELSE IF( TYPE.EQ.'HE'.OR.TYPE.EQ.'SY'.OR.TYPE.EQ.'TR' )THEN
DO 90 J = 1, N
IF( UPPER )THEN
IBEG = 1
IF( UNIT )THEN
IEND = J - 1
ELSE
IEND = J
END IF
ELSE
IF( UNIT )THEN
IBEG = J + 1
ELSE
IBEG = J
END IF
IEND = N
END IF
DO 60 I = 1, IBEG - 1
AA( I + ( J - 1 )*LDA ) = ROGUE
60 CONTINUE
DO 70 I = IBEG, IEND
AA( I + ( J - 1 )*LDA ) = A( I, J )
70 CONTINUE
DO 80 I = IEND + 1, LDA
AA( I + ( J - 1 )*LDA ) = ROGUE
80 CONTINUE
IF( HER )THEN
JJ = J + ( J - 1 )*LDA
AA( JJ ) = CMPLX( REAL( AA( JJ ) ), RROGUE )
END IF
90 CONTINUE
END IF
RETURN
*
* End of CMAKE.
*
END
SUBROUTINE CMMCH( TRANSA, TRANSB, M, N, KK, ALPHA, A, LDA, B, LDB,
$ BETA, C, LDC, CT, G, CC, LDCC, EPS, ERR, FATAL,
$ NOUT, MV )
*
* Checks the results of the computational tests.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Parameters ..
COMPLEX ZERO
PARAMETER ( ZERO = ( 0.0, 0.0 ) )
REAL RZERO, RONE
PARAMETER ( RZERO = 0.0, RONE = 1.0 )
* .. Scalar Arguments ..
COMPLEX ALPHA, BETA
REAL EPS, ERR
INTEGER KK, LDA, LDB, LDC, LDCC, M, N, NOUT
LOGICAL FATAL, MV
CHARACTER*1 TRANSA, TRANSB
* .. Array Arguments ..
COMPLEX A( LDA, * ), B( LDB, * ), C( LDC, * ),
$ CC( LDCC, * ), CT( * )
REAL G( * )
* .. Local Scalars ..
COMPLEX CL
REAL ERRI
INTEGER I, J, K
LOGICAL CTRANA, CTRANB, TRANA, TRANB
* .. Intrinsic Functions ..
INTRINSIC ABS, AIMAG, CONJG, MAX, REAL, SQRT
* .. Statement Functions ..
REAL ABS1
* .. Statement Function definitions ..
ABS1( CL ) = ABS( REAL( CL ) ) + ABS( AIMAG( CL ) )
* .. Executable Statements ..
TRANA = TRANSA.EQ.'T'.OR.TRANSA.EQ.'C'
TRANB = TRANSB.EQ.'T'.OR.TRANSB.EQ.'C'
CTRANA = TRANSA.EQ.'C'
CTRANB = TRANSB.EQ.'C'
*
* Compute expected result, one column at a time, in CT using data
* in A, B and C.
* Compute gauges in G.
*
DO 220 J = 1, N
*
DO 10 I = 1, M
CT( I ) = ZERO
G( I ) = RZERO
10 CONTINUE
IF( .NOT.TRANA.AND..NOT.TRANB )THEN
DO 30 K = 1, KK
DO 20 I = 1, M
CT( I ) = CT( I ) + A( I, K )*B( K, J )
G( I ) = G( I ) + ABS1( A( I, K ) )*ABS1( B( K, J ) )
20 CONTINUE
30 CONTINUE
ELSE IF( TRANA.AND..NOT.TRANB )THEN
IF( CTRANA )THEN
DO 50 K = 1, KK
DO 40 I = 1, M
CT( I ) = CT( I ) + CONJG( A( K, I ) )*B( K, J )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( K, J ) )
40 CONTINUE
50 CONTINUE
ELSE
DO 70 K = 1, KK
DO 60 I = 1, M
CT( I ) = CT( I ) + A( K, I )*B( K, J )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( K, J ) )
60 CONTINUE
70 CONTINUE
END IF
ELSE IF( .NOT.TRANA.AND.TRANB )THEN
IF( CTRANB )THEN
DO 90 K = 1, KK
DO 80 I = 1, M
CT( I ) = CT( I ) + A( I, K )*CONJG( B( J, K ) )
G( I ) = G( I ) + ABS1( A( I, K ) )*
$ ABS1( B( J, K ) )
80 CONTINUE
90 CONTINUE
ELSE
DO 110 K = 1, KK
DO 100 I = 1, M
CT( I ) = CT( I ) + A( I, K )*B( J, K )
G( I ) = G( I ) + ABS1( A( I, K ) )*
$ ABS1( B( J, K ) )
100 CONTINUE
110 CONTINUE
END IF
ELSE IF( TRANA.AND.TRANB )THEN
IF( CTRANA )THEN
IF( CTRANB )THEN
DO 130 K = 1, KK
DO 120 I = 1, M
CT( I ) = CT( I ) + CONJG( A( K, I ) )*
$ CONJG( B( J, K ) )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( J, K ) )
120 CONTINUE
130 CONTINUE
ELSE
DO 150 K = 1, KK
DO 140 I = 1, M
CT( I ) = CT( I ) + CONJG( A( K, I ) )*B( J, K )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( J, K ) )
140 CONTINUE
150 CONTINUE
END IF
ELSE
IF( CTRANB )THEN
DO 170 K = 1, KK
DO 160 I = 1, M
CT( I ) = CT( I ) + A( K, I )*CONJG( B( J, K ) )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( J, K ) )
160 CONTINUE
170 CONTINUE
ELSE
DO 190 K = 1, KK
DO 180 I = 1, M
CT( I ) = CT( I ) + A( K, I )*B( J, K )
G( I ) = G( I ) + ABS1( A( K, I ) )*
$ ABS1( B( J, K ) )
180 CONTINUE
190 CONTINUE
END IF
END IF
END IF
DO 200 I = 1, M
CT( I ) = ALPHA*CT( I ) + BETA*C( I, J )
G( I ) = ABS1( ALPHA )*G( I ) +
$ ABS1( BETA )*ABS1( C( I, J ) )
200 CONTINUE
*
* Compute the error ratio for this result.
*
ERR = ZERO
DO 210 I = 1, M
ERRI = ABS1( CT( I ) - CC( I, J ) )/EPS
IF( G( I ).NE.RZERO )
$ ERRI = ERRI/G( I )
ERR = MAX( ERR, ERRI )
IF( ERR*SQRT( EPS ).GE.RONE )
$ GO TO 230
210 CONTINUE
*
220 CONTINUE
*
* If the loop completes, all results are at least half accurate.
GO TO 250
*
* Report fatal error.
*
230 FATAL = .TRUE.
WRITE( NOUT, FMT = 9999 )
DO 240 I = 1, M
IF( MV )THEN
WRITE( NOUT, FMT = 9998 )I, CT( I ), CC( I, J )
ELSE
WRITE( NOUT, FMT = 9998 )I, CC( I, J ), CT( I )
END IF
240 CONTINUE
IF( N.GT.1 )
$ WRITE( NOUT, FMT = 9997 )J
*
250 CONTINUE
RETURN
*
9999 FORMAT( ' ******* FATAL ERROR - COMPUTED RESULT IS LESS THAN HAL',
$ 'F ACCURATE *******', /' EXPECTED RE',
$ 'SULT COMPUTED RESULT' )
9998 FORMAT( 1X, I7, 2( ' (', G15.6, ',', G15.6, ')' ) )
9997 FORMAT( ' THESE ARE THE RESULTS FOR COLUMN ', I3 )
*
* End of CMMCH.
*
END
LOGICAL FUNCTION LCE( RI, RJ, LR )
*
* Tests if two arrays are identical.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
INTEGER LR
* .. Array Arguments ..
COMPLEX RI( * ), RJ( * )
* .. Local Scalars ..
INTEGER I
* .. Executable Statements ..
DO 10 I = 1, LR
IF( RI( I ).NE.RJ( I ) )
$ GO TO 20
10 CONTINUE
LCE = .TRUE.
GO TO 30
20 CONTINUE
LCE = .FALSE.
30 RETURN
*
* End of LCE.
*
END
LOGICAL FUNCTION LCERES( TYPE, UPLO, M, N, AA, AS, LDA )
*
* Tests if selected elements in two arrays are equal.
*
* TYPE is 'GE' or 'HE' or 'SY'.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
INTEGER LDA, M, N
CHARACTER*1 UPLO
CHARACTER*2 TYPE
* .. Array Arguments ..
COMPLEX AA( LDA, * ), AS( LDA, * )
* .. Local Scalars ..
INTEGER I, IBEG, IEND, J
LOGICAL UPPER
* .. Executable Statements ..
UPPER = UPLO.EQ.'U'
IF( TYPE.EQ.'GE' )THEN
DO 20 J = 1, N
DO 10 I = M + 1, LDA
IF( AA( I, J ).NE.AS( I, J ) )
$ GO TO 70
10 CONTINUE
20 CONTINUE
ELSE IF( TYPE.EQ.'HE'.OR.TYPE.EQ.'SY' )THEN
DO 50 J = 1, N
IF( UPPER )THEN
IBEG = 1
IEND = J
ELSE
IBEG = J
IEND = N
END IF
DO 30 I = 1, IBEG - 1
IF( AA( I, J ).NE.AS( I, J ) )
$ GO TO 70
30 CONTINUE
DO 40 I = IEND + 1, LDA
IF( AA( I, J ).NE.AS( I, J ) )
$ GO TO 70
40 CONTINUE
50 CONTINUE
END IF
*
60 CONTINUE
LCERES = .TRUE.
GO TO 80
70 CONTINUE
LCERES = .FALSE.
80 RETURN
*
* End of LCERES.
*
END
COMPLEX FUNCTION CBEG( RESET )
*
* Generates complex numbers as pairs of random numbers uniformly
* distributed between -0.5 and 0.5.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
LOGICAL RESET
* .. Local Scalars ..
INTEGER I, IC, J, MI, MJ
* .. Save statement ..
SAVE I, IC, J, MI, MJ
* .. Intrinsic Functions ..
INTRINSIC CMPLX
* .. Executable Statements ..
IF( RESET )THEN
* Initialize local variables.
MI = 891
MJ = 457
I = 7
J = 7
IC = 0
RESET = .FALSE.
END IF
*
* The sequence of values of I or J is bounded between 1 and 999.
* If initial I or J = 1,2,3,6,7 or 9, the period will be 50.
* If initial I or J = 4 or 8, the period will be 25.
* If initial I or J = 5, the period will be 10.
* IC is used to break up the period by skipping 1 value of I or J
* in 6.
*
IC = IC + 1
10 I = I*MI
J = J*MJ
I = I - 1000*( I/1000 )
J = J - 1000*( J/1000 )
IF( IC.GE.5 )THEN
IC = 0
GO TO 10
END IF
CBEG = CMPLX( ( I - 500 )/1001.0, ( J - 500 )/1001.0 )
RETURN
*
* End of CBEG.
*
END
REAL FUNCTION SDIFF( X, Y )
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
REAL X, Y
* .. Executable Statements ..
SDIFF = X - Y
RETURN
*
* End of SDIFF.
*
END
SUBROUTINE CHKXER( SRNAMT, INFOT, NOUT, LERR, OK )
*
* Tests whether XERBLA has detected an error when it should.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
INTEGER INFOT, NOUT
LOGICAL LERR, OK
CHARACTER*6 SRNAMT
* .. Executable Statements ..
IF( .NOT.LERR )THEN
WRITE( NOUT, FMT = 9999 )INFOT, SRNAMT
OK = .FALSE.
END IF
LERR = .FALSE.
RETURN
*
9999 FORMAT( ' ***** ILLEGAL VALUE OF PARAMETER NUMBER ', I2, ' NOT D',
$ 'ETECTED BY ', A6, ' *****' )
*
* End of CHKXER.
*
END
SUBROUTINE XERBLA( SRNAME, INFO )
*
* This is a special version of XERBLA to be used only as part of
* the test program for testing error exits from the Level 3 BLAS
* routines.
*
* XERBLA is an error handler for the Level 3 BLAS routines.
*
* It is called by the Level 3 BLAS routines if an input parameter is
* invalid.
*
* Auxiliary routine for test program for Level 3 Blas.
*
* -- Written on 8-February-1989.
* Jack Dongarra, Argonne National Laboratory.
* Iain Duff, AERE Harwell.
* Jeremy Du Croz, Numerical Algorithms Group Ltd.
* Sven Hammarling, Numerical Algorithms Group Ltd.
*
* .. Scalar Arguments ..
INTEGER INFO
CHARACTER*6 SRNAME
* .. Scalars in Common ..
INTEGER INFOT, NOUT
LOGICAL LERR, OK
CHARACTER*6 SRNAMT
* .. Common blocks ..
COMMON /INFOC/INFOT, NOUT, OK, LERR
COMMON /SRNAMC/SRNAMT
* .. Executable Statements ..
LERR = .TRUE.
IF( INFO.NE.INFOT )THEN
IF( INFOT.NE.0 )THEN
WRITE( NOUT, FMT = 9999 )INFO, INFOT
ELSE
WRITE( NOUT, FMT = 9997 )INFO
END IF
OK = .FALSE.
END IF
IF( SRNAME.NE.SRNAMT )THEN
WRITE( NOUT, FMT = 9998 )SRNAME, SRNAMT
OK = .FALSE.
END IF
RETURN
*
9999 FORMAT( ' ******* XERBLA WAS CALLED WITH INFO = ', I6, ' INSTEAD',
$ ' OF ', I2, ' *******' )
9998 FORMAT( ' ******* XERBLA WAS CALLED WITH SRNAME = ', A6, ' INSTE',
$ 'AD OF ', A6, ' *******' )
9997 FORMAT( ' ******* XERBLA WAS CALLED WITH INFO = ', I6,
$ ' *******' )
*
* End of XERBLA
*
END
| bsd-3-clause |
WebRTC-Labs/libvpx | vp8/common/sad_c.c | 58 | 14728 | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <limits.h>
#include <stdlib.h>
#include "vpx_config.h"
#include "vpx/vpx_integer.h"
static unsigned int sad_mx_n_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad, int m, int n)
{
int r, c;
unsigned int sad = 0;
for (r = 0; r < n; r++)
{
for (c = 0; c < m; c++)
{
sad += abs(src_ptr[c] - ref_ptr[c]);
}
if (sad > max_sad)
break;
src_ptr += src_stride;
ref_ptr += ref_stride;
}
return sad;
}
/* max_sad is provided as an optional optimization point. Alternative
* implementations of these functions are not required to check it.
*/
unsigned int vp8_sad16x16_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad)
{
return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, max_sad, 16, 16);
}
unsigned int vp8_sad8x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad)
{
return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, max_sad, 8, 8);
}
unsigned int vp8_sad16x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad)
{
return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, max_sad, 16, 8);
}
unsigned int vp8_sad8x16_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad)
{
return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, max_sad, 8, 16);
}
unsigned int vp8_sad4x4_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int max_sad)
{
return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, max_sad, 4, 4);
}
void vp8_sad16x16x3_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
}
void vp8_sad16x16x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned short *sad_array)
{
sad_array[0] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
sad_array[3] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 3, ref_stride, UINT_MAX);
sad_array[4] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 4, ref_stride, UINT_MAX);
sad_array[5] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 5, ref_stride, UINT_MAX);
sad_array[6] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 6, ref_stride, UINT_MAX);
sad_array[7] = (unsigned short)vp8_sad16x16_c(src_ptr, src_stride, ref_ptr + 7, ref_stride, UINT_MAX);
}
void vp8_sad16x8x3_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
}
void vp8_sad16x8x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned short *sad_array)
{
sad_array[0] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
sad_array[3] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 3, ref_stride, UINT_MAX);
sad_array[4] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 4, ref_stride, UINT_MAX);
sad_array[5] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 5, ref_stride, UINT_MAX);
sad_array[6] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 6, ref_stride, UINT_MAX);
sad_array[7] = (unsigned short)vp8_sad16x8_c(src_ptr, src_stride, ref_ptr + 7, ref_stride, UINT_MAX);
}
void vp8_sad8x8x3_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
}
void vp8_sad8x8x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned short *sad_array)
{
sad_array[0] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
sad_array[3] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 3, ref_stride, UINT_MAX);
sad_array[4] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 4, ref_stride, UINT_MAX);
sad_array[5] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 5, ref_stride, UINT_MAX);
sad_array[6] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 6, ref_stride, UINT_MAX);
sad_array[7] = (unsigned short)vp8_sad8x8_c(src_ptr, src_stride, ref_ptr + 7, ref_stride, UINT_MAX);
}
void vp8_sad8x16x3_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
}
void vp8_sad8x16x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned short *sad_array)
{
sad_array[0] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
sad_array[3] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 3, ref_stride, UINT_MAX);
sad_array[4] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 4, ref_stride, UINT_MAX);
sad_array[5] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 5, ref_stride, UINT_MAX);
sad_array[6] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 6, ref_stride, UINT_MAX);
sad_array[7] = (unsigned short)vp8_sad8x16_c(src_ptr, src_stride, ref_ptr + 7, ref_stride, UINT_MAX);
}
void vp8_sad4x4x3_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
}
void vp8_sad4x4x8_c(const unsigned char *src_ptr, int src_stride,
const unsigned char *ref_ptr, int ref_stride,
unsigned short *sad_array)
{
sad_array[0] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 0, ref_stride, UINT_MAX);
sad_array[1] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 1, ref_stride, UINT_MAX);
sad_array[2] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 2, ref_stride, UINT_MAX);
sad_array[3] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 3, ref_stride, UINT_MAX);
sad_array[4] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 4, ref_stride, UINT_MAX);
sad_array[5] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 5, ref_stride, UINT_MAX);
sad_array[6] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 6, ref_stride, UINT_MAX);
sad_array[7] = (unsigned short)vp8_sad4x4_c(src_ptr, src_stride, ref_ptr + 7, ref_stride, UINT_MAX);
}
void vp8_sad16x16x4d_c(const unsigned char *src_ptr, int src_stride,
const unsigned char * const ref_ptr[], int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr[0], ref_stride, UINT_MAX);
sad_array[1] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr[1], ref_stride, UINT_MAX);
sad_array[2] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr[2], ref_stride, UINT_MAX);
sad_array[3] = vp8_sad16x16_c(src_ptr, src_stride, ref_ptr[3], ref_stride, UINT_MAX);
}
void vp8_sad16x8x4d_c(const unsigned char *src_ptr, int src_stride,
const unsigned char * const ref_ptr[], int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr[0], ref_stride, UINT_MAX);
sad_array[1] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr[1], ref_stride, UINT_MAX);
sad_array[2] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr[2], ref_stride, UINT_MAX);
sad_array[3] = vp8_sad16x8_c(src_ptr, src_stride, ref_ptr[3], ref_stride, UINT_MAX);
}
void vp8_sad8x8x4d_c(const unsigned char *src_ptr, int src_stride,
const unsigned char * const ref_ptr[], int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr[0], ref_stride, UINT_MAX);
sad_array[1] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr[1], ref_stride, UINT_MAX);
sad_array[2] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr[2], ref_stride, UINT_MAX);
sad_array[3] = vp8_sad8x8_c(src_ptr, src_stride, ref_ptr[3], ref_stride, UINT_MAX);
}
void vp8_sad8x16x4d_c(const unsigned char *src_ptr, int src_stride,
const unsigned char * const ref_ptr[], int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr[0], ref_stride, UINT_MAX);
sad_array[1] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr[1], ref_stride, UINT_MAX);
sad_array[2] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr[2], ref_stride, UINT_MAX);
sad_array[3] = vp8_sad8x16_c(src_ptr, src_stride, ref_ptr[3], ref_stride, UINT_MAX);
}
void vp8_sad4x4x4d_c(const unsigned char *src_ptr, int src_stride,
const unsigned char * const ref_ptr[], int ref_stride,
unsigned int *sad_array)
{
sad_array[0] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr[0], ref_stride, UINT_MAX);
sad_array[1] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr[1], ref_stride, UINT_MAX);
sad_array[2] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr[2], ref_stride, UINT_MAX);
sad_array[3] = vp8_sad4x4_c(src_ptr, src_stride, ref_ptr[3], ref_stride, UINT_MAX);
}
/* Copy 2 macroblocks to a buffer */
void vp8_copy32xn_c(unsigned char *src_ptr, int src_stride,
unsigned char *dst_ptr, int dst_stride,
int height)
{
int r;
for (r = 0; r < height; r++)
{
#if !(CONFIG_FAST_UNALIGNED)
dst_ptr[0] = src_ptr[0];
dst_ptr[1] = src_ptr[1];
dst_ptr[2] = src_ptr[2];
dst_ptr[3] = src_ptr[3];
dst_ptr[4] = src_ptr[4];
dst_ptr[5] = src_ptr[5];
dst_ptr[6] = src_ptr[6];
dst_ptr[7] = src_ptr[7];
dst_ptr[8] = src_ptr[8];
dst_ptr[9] = src_ptr[9];
dst_ptr[10] = src_ptr[10];
dst_ptr[11] = src_ptr[11];
dst_ptr[12] = src_ptr[12];
dst_ptr[13] = src_ptr[13];
dst_ptr[14] = src_ptr[14];
dst_ptr[15] = src_ptr[15];
dst_ptr[16] = src_ptr[16];
dst_ptr[17] = src_ptr[17];
dst_ptr[18] = src_ptr[18];
dst_ptr[19] = src_ptr[19];
dst_ptr[20] = src_ptr[20];
dst_ptr[21] = src_ptr[21];
dst_ptr[22] = src_ptr[22];
dst_ptr[23] = src_ptr[23];
dst_ptr[24] = src_ptr[24];
dst_ptr[25] = src_ptr[25];
dst_ptr[26] = src_ptr[26];
dst_ptr[27] = src_ptr[27];
dst_ptr[28] = src_ptr[28];
dst_ptr[29] = src_ptr[29];
dst_ptr[30] = src_ptr[30];
dst_ptr[31] = src_ptr[31];
#else
((uint32_t *)dst_ptr)[0] = ((uint32_t *)src_ptr)[0] ;
((uint32_t *)dst_ptr)[1] = ((uint32_t *)src_ptr)[1] ;
((uint32_t *)dst_ptr)[2] = ((uint32_t *)src_ptr)[2] ;
((uint32_t *)dst_ptr)[3] = ((uint32_t *)src_ptr)[3] ;
((uint32_t *)dst_ptr)[4] = ((uint32_t *)src_ptr)[4] ;
((uint32_t *)dst_ptr)[5] = ((uint32_t *)src_ptr)[5] ;
((uint32_t *)dst_ptr)[6] = ((uint32_t *)src_ptr)[6] ;
((uint32_t *)dst_ptr)[7] = ((uint32_t *)src_ptr)[7] ;
#endif
src_ptr += src_stride;
dst_ptr += dst_stride;
}
}
| bsd-3-clause |
jefleponot/phantomjs | src/qt/src/3rdparty/webkit/Source/WebCore/bindings/js/JavaScriptCallFrame.cpp | 58 | 3541 | /*
* Copyright (C) 2008 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "JavaScriptCallFrame.h"
#include "JSDOMBinding.h"
#if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
#include "PlatformString.h"
#include <debugger/DebuggerCallFrame.h>
#include <runtime/Completion.h>
#include <runtime/JSGlobalObject.h>
#include <runtime/JSLock.h>
#include <runtime/JSObject.h>
#include <runtime/JSValue.h>
using namespace JSC;
namespace WebCore {
JavaScriptCallFrame::JavaScriptCallFrame(const DebuggerCallFrame& debuggerCallFrame, PassRefPtr<JavaScriptCallFrame> caller, intptr_t sourceID, const TextPosition0& textPosition)
: m_debuggerCallFrame(debuggerCallFrame)
, m_caller(caller)
, m_sourceID(sourceID)
, m_textPosition(textPosition)
, m_isValid(true)
{
}
JavaScriptCallFrame* JavaScriptCallFrame::caller()
{
return m_caller.get();
}
JSC::ScopeChainNode* JavaScriptCallFrame::scopeChain() const
{
ASSERT(m_isValid);
if (!m_isValid)
return 0;
return m_debuggerCallFrame.scopeChain();
}
JSC::JSGlobalObject* JavaScriptCallFrame::dynamicGlobalObject() const
{
ASSERT(m_isValid);
if (!m_isValid)
return 0;
return m_debuggerCallFrame.dynamicGlobalObject();
}
String JavaScriptCallFrame::functionName() const
{
ASSERT(m_isValid);
if (!m_isValid)
return String();
UString functionName = m_debuggerCallFrame.calculatedFunctionName();
if (functionName.isEmpty())
return String();
return ustringToString(functionName);
}
DebuggerCallFrame::Type JavaScriptCallFrame::type() const
{
ASSERT(m_isValid);
if (!m_isValid)
return DebuggerCallFrame::ProgramType;
return m_debuggerCallFrame.type();
}
JSObject* JavaScriptCallFrame::thisObject() const
{
ASSERT(m_isValid);
if (!m_isValid)
return 0;
return m_debuggerCallFrame.thisObject();
}
// Evaluate some JavaScript code in the scope of this frame.
JSValue JavaScriptCallFrame::evaluate(const UString& script, JSValue& exception) const
{
ASSERT(m_isValid);
if (!m_isValid)
return jsNull();
JSLock lock(SilenceAssertionsOnly);
return m_debuggerCallFrame.evaluate(script, exception);
}
} // namespace WebCore
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
| bsd-3-clause |
tangyibin/goblin-core | riscv/llvm/3.5/cfe-3.5.0.src/test/CXX/over/over.match/over.match.best/over.ics.rank/p3-0x.cpp | 63 | 1107 | // RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
// expected-no-diagnostics
namespace std_example {
int i;
int f1();
int&& f2();
int &g(const int &);
float &g(const int &&);
int &j = g(i);
float &k = g(f1());
float &l = g(f2());
int &g2(const int &);
float &g2(int &&);
int &j2 = g2(i);
float &k2 = g2(f1());
float &l2 = g2(f2());
// FIXME: We don't support ref-qualifiers yet.
#if 0
struct A {
A& operator<<(int);
void p() &;
void p() &&;
};
A& operator<<(A&&, char);
A() << 1;
A() << 'c';
A a;
a << 1;
a << 'c';
A().p();
a.p();
#endif
}
template<typename T>
struct remove_reference {
typedef T type;
};
template<typename T>
struct remove_reference<T&> {
typedef T type;
};
template<typename T>
struct remove_reference<T&&> {
typedef T type;
};
namespace FunctionReferencesOverloading {
template<typename T> int &f(typename remove_reference<T>::type&);
template<typename T> float &f(typename remove_reference<T>::type&&);
void test_f(int (&func_ref)(int)) {
int &ir = f<int (&)(int)>(func_ref);
}
}
| bsd-3-clause |
smasala/phantomjs | src/qt/qtbase/src/3rdparty/pcre/sljit/sljitNativePPC_32.c | 75 | 10065 | /*
* Stack-less Just-In-Time compiler
*
* Copyright 2009-2012 Zoltan Herczeg (hzmester@freemail.hu). 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 HOLDER(S) 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 HOLDER(S) 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.
*/
/* ppc 32-bit arch dependent functions. */
static sljit_si load_immediate(struct sljit_compiler *compiler, sljit_si reg, sljit_sw imm)
{
if (imm <= SIMM_MAX && imm >= SIMM_MIN)
return push_inst(compiler, ADDI | D(reg) | A(0) | IMM(imm));
if (!(imm & ~0xffff))
return push_inst(compiler, ORI | S(ZERO_REG) | A(reg) | IMM(imm));
FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(imm >> 16)));
return (imm & 0xffff) ? push_inst(compiler, ORI | S(reg) | A(reg) | IMM(imm)) : SLJIT_SUCCESS;
}
#define INS_CLEAR_LEFT(dst, src, from) \
(RLWINM | S(src) | A(dst) | ((from) << 6) | (31 << 1))
static SLJIT_INLINE sljit_si emit_single_op(struct sljit_compiler *compiler, sljit_si op, sljit_si flags,
sljit_si dst, sljit_si src1, sljit_si src2)
{
switch (op) {
case SLJIT_MOV:
case SLJIT_MOV_UI:
case SLJIT_MOV_SI:
case SLJIT_MOV_P:
SLJIT_ASSERT(src1 == TMP_REG1);
if (dst != src2)
return push_inst(compiler, OR | S(src2) | A(dst) | B(src2));
return SLJIT_SUCCESS;
case SLJIT_MOV_UB:
case SLJIT_MOV_SB:
SLJIT_ASSERT(src1 == TMP_REG1);
if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) {
if (op == SLJIT_MOV_SB)
return push_inst(compiler, EXTSB | S(src2) | A(dst));
return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 24));
}
else if ((flags & REG_DEST) && op == SLJIT_MOV_SB)
return push_inst(compiler, EXTSB | S(src2) | A(dst));
else {
SLJIT_ASSERT(dst == src2);
}
return SLJIT_SUCCESS;
case SLJIT_MOV_UH:
case SLJIT_MOV_SH:
SLJIT_ASSERT(src1 == TMP_REG1);
if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) {
if (op == SLJIT_MOV_SH)
return push_inst(compiler, EXTSH | S(src2) | A(dst));
return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 16));
}
else {
SLJIT_ASSERT(dst == src2);
}
return SLJIT_SUCCESS;
case SLJIT_NOT:
SLJIT_ASSERT(src1 == TMP_REG1);
return push_inst(compiler, NOR | RC(flags) | S(src2) | A(dst) | B(src2));
case SLJIT_NEG:
SLJIT_ASSERT(src1 == TMP_REG1);
return push_inst(compiler, NEG | OERC(flags) | D(dst) | A(src2));
case SLJIT_CLZ:
SLJIT_ASSERT(src1 == TMP_REG1);
return push_inst(compiler, CNTLZW | RC(flags) | S(src2) | A(dst));
case SLJIT_ADD:
if (flags & ALT_FORM1) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ADDI | D(dst) | A(src1) | compiler->imm);
}
if (flags & ALT_FORM2) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ADDIS | D(dst) | A(src1) | compiler->imm);
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ADDIC | D(dst) | A(src1) | compiler->imm);
}
if (flags & ALT_FORM4) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
FAIL_IF(push_inst(compiler, ADDI | D(dst) | A(src1) | (compiler->imm & 0xffff)));
return push_inst(compiler, ADDIS | D(dst) | A(dst) | (((compiler->imm >> 16) & 0xffff) + ((compiler->imm >> 15) & 0x1)));
}
if (!(flags & ALT_SET_FLAGS))
return push_inst(compiler, ADD | D(dst) | A(src1) | B(src2));
return push_inst(compiler, ADDC | OERC(ALT_SET_FLAGS) | D(dst) | A(src1) | B(src2));
case SLJIT_ADDC:
if (flags & ALT_FORM1) {
FAIL_IF(push_inst(compiler, MFXER | D(0)));
FAIL_IF(push_inst(compiler, ADDE | D(dst) | A(src1) | B(src2)));
return push_inst(compiler, MTXER | S(0));
}
return push_inst(compiler, ADDE | D(dst) | A(src1) | B(src2));
case SLJIT_SUB:
if (flags & ALT_FORM1) {
/* Flags does not set: BIN_IMM_EXTS unnecessary. */
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, SUBFIC | D(dst) | A(src1) | compiler->imm);
}
if (flags & (ALT_FORM2 | ALT_FORM3)) {
SLJIT_ASSERT(src2 == TMP_REG2);
if (flags & ALT_FORM2)
FAIL_IF(push_inst(compiler, CMPI | CRD(0) | A(src1) | compiler->imm));
if (flags & ALT_FORM3)
return push_inst(compiler, CMPLI | CRD(4) | A(src1) | compiler->imm);
return SLJIT_SUCCESS;
}
if (flags & (ALT_FORM4 | ALT_FORM5)) {
if (flags & ALT_FORM4)
FAIL_IF(push_inst(compiler, CMPL | CRD(4) | A(src1) | B(src2)));
if (flags & ALT_FORM5)
FAIL_IF(push_inst(compiler, CMP | CRD(0) | A(src1) | B(src2)));
return SLJIT_SUCCESS;
}
if (!(flags & ALT_SET_FLAGS))
return push_inst(compiler, SUBF | D(dst) | A(src2) | B(src1));
if (flags & ALT_FORM6)
FAIL_IF(push_inst(compiler, CMPL | CRD(4) | A(src1) | B(src2)));
return push_inst(compiler, SUBFC | OERC(ALT_SET_FLAGS) | D(dst) | A(src2) | B(src1));
case SLJIT_SUBC:
if (flags & ALT_FORM1) {
FAIL_IF(push_inst(compiler, MFXER | D(0)));
FAIL_IF(push_inst(compiler, SUBFE | D(dst) | A(src2) | B(src1)));
return push_inst(compiler, MTXER | S(0));
}
return push_inst(compiler, SUBFE | D(dst) | A(src2) | B(src1));
case SLJIT_MUL:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, MULLI | D(dst) | A(src1) | compiler->imm);
}
return push_inst(compiler, MULLW | OERC(flags) | D(dst) | A(src2) | B(src1));
case SLJIT_AND:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ANDI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ANDIS | S(src1) | A(dst) | compiler->imm);
}
return push_inst(compiler, AND | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_OR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ORI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, ORIS | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
FAIL_IF(push_inst(compiler, ORI | S(src1) | A(dst) | IMM(compiler->imm)));
return push_inst(compiler, ORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16));
}
return push_inst(compiler, OR | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_XOR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, XORI | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM2) {
SLJIT_ASSERT(src2 == TMP_REG2);
return push_inst(compiler, XORIS | S(src1) | A(dst) | compiler->imm);
}
if (flags & ALT_FORM3) {
SLJIT_ASSERT(src2 == TMP_REG2);
FAIL_IF(push_inst(compiler, XORI | S(src1) | A(dst) | IMM(compiler->imm)));
return push_inst(compiler, XORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16));
}
return push_inst(compiler, XOR | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_SHL:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11) | ((31 - compiler->imm) << 1));
}
return push_inst(compiler, SLW | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_LSHR:
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (((32 - compiler->imm) & 0x1f) << 11) | (compiler->imm << 6) | (31 << 1));
}
return push_inst(compiler, SRW | RC(flags) | S(src1) | A(dst) | B(src2));
case SLJIT_ASHR:
if (flags & ALT_FORM3)
FAIL_IF(push_inst(compiler, MFXER | D(0)));
if (flags & ALT_FORM1) {
SLJIT_ASSERT(src2 == TMP_REG2);
compiler->imm &= 0x1f;
FAIL_IF(push_inst(compiler, SRAWI | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11)));
}
else
FAIL_IF(push_inst(compiler, SRAW | RC(flags) | S(src1) | A(dst) | B(src2)));
return (flags & ALT_FORM3) ? push_inst(compiler, MTXER | S(0)) : SLJIT_SUCCESS;
}
SLJIT_ASSERT_STOP();
return SLJIT_SUCCESS;
}
static SLJIT_INLINE sljit_si emit_const(struct sljit_compiler *compiler, sljit_si reg, sljit_sw init_value)
{
FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(init_value >> 16)));
return push_inst(compiler, ORI | S(reg) | A(reg) | IMM(init_value));
}
SLJIT_API_FUNC_ATTRIBUTE void sljit_set_jump_addr(sljit_uw addr, sljit_uw new_addr)
{
sljit_ins *inst = (sljit_ins*)addr;
inst[0] = (inst[0] & 0xffff0000) | ((new_addr >> 16) & 0xffff);
inst[1] = (inst[1] & 0xffff0000) | (new_addr & 0xffff);
SLJIT_CACHE_FLUSH(inst, inst + 2);
}
SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_sw new_constant)
{
sljit_ins *inst = (sljit_ins*)addr;
inst[0] = (inst[0] & 0xffff0000) | ((new_constant >> 16) & 0xffff);
inst[1] = (inst[1] & 0xffff0000) | (new_constant & 0xffff);
SLJIT_CACHE_FLUSH(inst, inst + 2);
}
| bsd-3-clause |
Guardiannw/react-native | ReactCommon/cxxreact/JSCMemory.cpp | 78 | 1214 | // Copyright 2004-present Facebook. All Rights Reserved.
#include "JSCMemory.h"
#ifdef WITH_FB_MEMORY_PROFILING
#include <stdio.h>
#include <string.h>
#include <JavaScriptCore/API/JSProfilerPrivate.h>
#include <jschelpers/JSCHelpers.h>
#include <jschelpers/Value.h>
using namespace facebook::react;
static JSValueRef nativeCaptureHeap(
JSContextRef ctx,
JSObjectRef function,
JSObjectRef thisObject,
size_t argumentCount,
const JSValueRef arguments[],
JSValueRef* exception) {
if (argumentCount < 1) {
if (exception) {
*exception = Value::makeError(
ctx,
"nativeCaptureHeap requires the path to save the capture");
}
return Value::makeUndefined(ctx);
}
auto outputFilename = String::adopt(
ctx, JSValueToStringCopy(ctx, arguments[0], exception));
JSCaptureHeap(ctx, outputFilename.str().c_str(), exception);
return Value::makeUndefined(ctx);
}
#endif // WITH_FB_MEMORY_PROFILING
namespace facebook {
namespace react {
void addNativeMemoryHooks(JSGlobalContextRef ctx) {
#ifdef WITH_FB_MEMORY_PROFILING
installGlobalFunction(ctx, "nativeCaptureHeap", nativeCaptureHeap);
#endif // WITH_FB_MEMORY_PROFILING
}
} }
| bsd-3-clause |
petermat/phantomjs | src/qt/qtbase/src/gui/kernel/qdrag.cpp | 84 | 12617 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qdrag.h>
#include "private/qguiapplication_p.h"
#include <qpixmap.h>
#include <qpoint.h>
#include "qdnd_p.h"
#ifndef QT_NO_DRAGANDDROP
QT_BEGIN_NAMESPACE
/*!
\class QDrag
\inmodule QtGui
\ingroup draganddrop
\brief The QDrag class provides support for MIME-based drag and drop data
transfer.
Drag and drop is an intuitive way for users to copy or move data around in an
application, and is used in many desktop environments as a mechanism for copying
data between applications. Drag and drop support in Qt is centered around the
QDrag class that handles most of the details of a drag and drop operation.
The data to be transferred by the drag and drop operation is contained in a
QMimeData object. This is specified with the setMimeData() function in the
following way:
\snippet dragging/mainwindow.cpp 1
Note that setMimeData() assigns ownership of the QMimeData object to the
QDrag object. The QDrag must be constructed on the heap with a parent QObject
to ensure that Qt can clean up after the drag and drop operation has been
completed.
A pixmap can be used to represent the data while the drag is in
progress, and will move with the cursor to the drop target. This
pixmap typically shows an icon that represents the MIME type of
the data being transferred, but any pixmap can be set with
setPixmap(). The cursor's hot spot can be given a position
relative to the top-left corner of the pixmap with the
setHotSpot() function. The following code positions the pixmap so
that the cursor's hot spot points to the center of its bottom
edge:
\snippet separations/finalwidget.cpp 2
\note On X11, the pixmap may not be able to keep up with the mouse
movements if the hot spot causes the pixmap to be displayed
directly under the cursor.
The source and target widgets can be found with source() and target().
These functions are often used to determine whether drag and drop operations
started and finished at the same widget, so that special behavior can be
implemented.
QDrag only deals with the drag and drop operation itself. It is up to the
developer to decide when a drag operation begins, and how a QDrag object should
be constructed and used. For a given widget, it is often necessary to
reimplement \l{QWidget::mousePressEvent()}{mousePressEvent()} to determine
whether the user has pressed a mouse button, and reimplement
\l{QWidget::mouseMoveEvent()}{mouseMoveEvent()} to check whether a QDrag is
required.
\sa {Drag and Drop}, QClipboard, QMimeData, QMacPasteboardMime,
{Draggable Icons Example}, {Draggable Text Example}, {Drop Site Example},
{Fridge Magnets Example}
*/
/*!
Constructs a new drag object for the widget specified by \a dragSource.
*/
QDrag::QDrag(QObject *dragSource)
: QObject(*new QDragPrivate, dragSource)
{
Q_D(QDrag);
d->source = dragSource;
d->target = 0;
d->data = 0;
d->hotspot = QPoint(-10, -10);
d->executed_action = Qt::IgnoreAction;
d->supported_actions = Qt::IgnoreAction;
d->default_action = Qt::IgnoreAction;
}
/*!
Destroys the drag object.
*/
QDrag::~QDrag()
{
Q_D(QDrag);
delete d->data;
}
/*!
Sets the data to be sent to the given MIME \a data. Ownership of the data is
transferred to the QDrag object.
*/
void QDrag::setMimeData(QMimeData *data)
{
Q_D(QDrag);
if (d->data == data)
return;
if (d->data != 0)
delete d->data;
d->data = data;
}
/*!
Returns the MIME data that is encapsulated by the drag object.
*/
QMimeData *QDrag::mimeData() const
{
Q_D(const QDrag);
return d->data;
}
/*!
Sets \a pixmap as the pixmap used to represent the data in a drag
and drop operation. You can only set a pixmap before the drag is
started.
*/
void QDrag::setPixmap(const QPixmap &pixmap)
{
Q_D(QDrag);
d->pixmap = pixmap;
}
/*!
Returns the pixmap used to represent the data in a drag and drop operation.
*/
QPixmap QDrag::pixmap() const
{
Q_D(const QDrag);
return d->pixmap;
}
/*!
Sets the position of the hot spot relative to the top-left corner of the
pixmap used to the point specified by \a hotspot.
\b{Note:} on X11, the pixmap may not be able to keep up with the mouse
movements if the hot spot causes the pixmap to be displayed
directly under the cursor.
*/
void QDrag::setHotSpot(const QPoint& hotspot)
{
Q_D(QDrag);
d->hotspot = hotspot;
}
/*!
Returns the position of the hot spot relative to the top-left corner of the
cursor.
*/
QPoint QDrag::hotSpot() const
{
Q_D(const QDrag);
return d->hotspot;
}
/*!
Returns the source of the drag object. This is the widget where the drag
and drop operation originated.
*/
QObject *QDrag::source() const
{
Q_D(const QDrag);
return d->source;
}
/*!
Returns the target of the drag and drop operation. This is the widget where
the drag object was dropped.
*/
QObject *QDrag::target() const
{
Q_D(const QDrag);
return d->target;
}
/*!
\since 4.3
Starts the drag and drop operation and returns a value indicating the requested
drop action when it is completed. The drop actions that the user can choose
from are specified in \a supportedActions. The default proposed action will be selected
among the allowed actions in the following order: Move, Copy and Link.
\b{Note:} On Linux and Mac OS X, the drag and drop operation
can take some time, but this function does not block the event
loop. Other events are still delivered to the application while
the operation is performed. On Windows, the Qt event loop is
blocked during the operation.
*/
Qt::DropAction QDrag::exec(Qt::DropActions supportedActions)
{
return exec(supportedActions, Qt::IgnoreAction);
}
/*!
\since 4.3
Starts the drag and drop operation and returns a value indicating the requested
drop action when it is completed. The drop actions that the user can choose
from are specified in \a supportedActions.
The \a defaultDropAction determines which action will be proposed when the user performs a
drag without using modifier keys.
\b{Note:} On Linux and Mac OS X, the drag and drop operation
can take some time, but this function does not block the event
loop. Other events are still delivered to the application while
the operation is performed. On Windows, the Qt event loop is
blocked during the operation. However, QDrag::exec() on
Windows causes processEvents() to be called frequently to keep the GUI responsive.
If any loops or operations are called while a drag operation is active, it will block the drag operation.
*/
Qt::DropAction QDrag::exec(Qt::DropActions supportedActions, Qt::DropAction defaultDropAction)
{
Q_D(QDrag);
if (!d->data) {
qWarning("QDrag: No mimedata set before starting the drag");
return d->executed_action;
}
Qt::DropAction transformedDefaultDropAction = Qt::IgnoreAction;
if (defaultDropAction == Qt::IgnoreAction) {
if (supportedActions & Qt::MoveAction) {
transformedDefaultDropAction = Qt::MoveAction;
} else if (supportedActions & Qt::CopyAction) {
transformedDefaultDropAction = Qt::CopyAction;
} else if (supportedActions & Qt::LinkAction) {
transformedDefaultDropAction = Qt::LinkAction;
}
} else {
transformedDefaultDropAction = defaultDropAction;
}
d->supported_actions = supportedActions;
d->default_action = transformedDefaultDropAction;
d->executed_action = QDragManager::self()->drag(this);
return d->executed_action;
}
/*!
\obsolete
\b{Note:} It is recommended to use exec() instead of this function.
Starts the drag and drop operation and returns a value indicating the requested
drop action when it is completed. The drop actions that the user can choose
from are specified in \a request. Qt::CopyAction is always allowed.
\b{Note:} Although the drag and drop operation can take some time, this function
does not block the event loop. Other events are still delivered to the application
while the operation is performed.
\sa exec()
*/
Qt::DropAction QDrag::start(Qt::DropActions request)
{
Q_D(QDrag);
if (!d->data) {
qWarning("QDrag: No mimedata set before starting the drag");
return d->executed_action;
}
d->supported_actions = request | Qt::CopyAction;
d->default_action = Qt::IgnoreAction;
d->executed_action = QDragManager::self()->drag(this);
return d->executed_action;
}
/*!
Sets the drag \a cursor for the \a action. This allows you
to override the default native cursors. To revert to using the
native cursor for \a action pass in a null QPixmap as \a cursor.
The \a action can only be CopyAction, MoveAction or LinkAction.
All other values of DropAction are ignored.
*/
void QDrag::setDragCursor(const QPixmap &cursor, Qt::DropAction action)
{
Q_D(QDrag);
if (action != Qt::CopyAction && action != Qt::MoveAction && action != Qt::LinkAction)
return;
if (cursor.isNull())
d->customCursors.remove(action);
else
d->customCursors[action] = cursor;
}
/*!
Returns the drag cursor for the \a action.
\since 5.0
*/
QPixmap QDrag::dragCursor(Qt::DropAction action) const
{
typedef QMap<Qt::DropAction, QPixmap>::const_iterator Iterator;
Q_D(const QDrag);
const Iterator it = d->customCursors.constFind(action);
if (it != d->customCursors.constEnd())
return it.value();
Qt::CursorShape shape = Qt::ForbiddenCursor;
switch (action) {
case Qt::MoveAction:
shape = Qt::DragMoveCursor;
break;
case Qt::CopyAction:
shape = Qt::DragCopyCursor;
break;
case Qt::LinkAction:
shape = Qt::DragLinkCursor;
break;
default:
shape = Qt::ForbiddenCursor;
}
return QGuiApplicationPrivate::instance()->getPixmapCursor(shape);
}
/*!
Returns the set of possible drop actions for this drag operation.
\sa exec(), defaultAction()
*/
Qt::DropActions QDrag::supportedActions() const
{
Q_D(const QDrag);
return d->supported_actions;
}
/*!
Returns the default proposed drop action for this drag operation.
\sa exec(), supportedActions()
*/
Qt::DropAction QDrag::defaultAction() const
{
Q_D(const QDrag);
return d->default_action;
}
/*!
\fn void QDrag::actionChanged(Qt::DropAction action)
This signal is emitted when the \a action associated with the
drag changes.
\sa targetChanged()
*/
/*!
\fn void QDrag::targetChanged(QObject *newTarget)
This signal is emitted when the target of the drag and drop
operation changes, with \a newTarget the new target.
\sa target(), actionChanged()
*/
QT_END_NAMESPACE
#endif // QT_NO_DRAGANDDROP
| bsd-3-clause |
bukalov/phantomjs | src/qt/qtbase/src/tools/moc/preprocessor.cpp | 84 | 40835 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Copyright (C) 2014 Olivier Goffart <ogoffart@woboq.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "preprocessor.h"
#include "utils.h"
#include <qstringlist.h>
#include <qfile.h>
#include <qdir.h>
#include <qfileinfo.h>
QT_BEGIN_NAMESPACE
#include "ppkeywords.cpp"
#include "keywords.cpp"
// transform \r\n into \n
// \r into \n (os9 style)
// backslash-newlines into newlines
static QByteArray cleaned(const QByteArray &input)
{
QByteArray result;
result.reserve(input.size());
const char *data = input.constData();
char *output = result.data();
int newlines = 0;
while (*data) {
while (*data && is_space(*data))
++data;
bool takeLine = (*data == '#');
if (*data == '%' && *(data+1) == ':') {
takeLine = true;
++data;
}
if (takeLine) {
*output = '#';
++output;
do ++data; while (*data && is_space(*data));
}
while (*data) {
// handle \\\n, \\\r\n and \\\r
if (*data == '\\') {
if (*(data + 1) == '\r') {
++data;
}
if (*data && (*(data + 1) == '\n' || (*data) == '\r')) {
++newlines;
data += 1;
if (*data != '\r')
data += 1;
continue;
}
} else if (*data == '\r' && *(data + 1) == '\n') { // reduce \r\n to \n
++data;
}
char ch = *data;
if (ch == '\r') // os9: replace \r with \n
ch = '\n';
*output = ch;
++output;
if (*data == '\n') {
// output additional newlines to keep the correct line-numbering
// for the lines following the backslash-newline sequence(s)
while (newlines) {
*output = '\n';
++output;
--newlines;
}
++data;
break;
}
++data;
}
}
result.resize(output - result.constData());
return result;
}
bool Preprocessor::preprocessOnly = false;
void Preprocessor::skipUntilEndif()
{
while(index < symbols.size() - 1 && symbols.at(index).token != PP_ENDIF){
switch (symbols.at(index).token) {
case PP_IF:
case PP_IFDEF:
case PP_IFNDEF:
++index;
skipUntilEndif();
break;
default:
;
}
++index;
}
}
bool Preprocessor::skipBranch()
{
while (index < symbols.size() - 1
&& (symbols.at(index).token != PP_ENDIF
&& symbols.at(index).token != PP_ELIF
&& symbols.at(index).token != PP_ELSE)
){
switch (symbols.at(index).token) {
case PP_IF:
case PP_IFDEF:
case PP_IFNDEF:
++index;
skipUntilEndif();
break;
default:
;
}
++index;
}
return (index < symbols.size() - 1);
}
Symbols Preprocessor::tokenize(const QByteArray& input, int lineNum, Preprocessor::TokenizeMode mode)
{
Symbols symbols;
const char *begin = input.constData();
const char *data = begin;
while (*data) {
if (mode == TokenizeCpp || mode == TokenizeDefine) {
int column = 0;
const char *lexem = data;
int state = 0;
Token token = NOTOKEN;
for (;;) {
if (static_cast<signed char>(*data) < 0) {
++data;
continue;
}
int nextindex = keywords[state].next;
int next = 0;
if (*data == keywords[state].defchar)
next = keywords[state].defnext;
else if (!state || nextindex)
next = keyword_trans[nextindex][(int)*data];
if (!next)
break;
state = next;
token = keywords[state].token;
++data;
}
// suboptimal, is_ident_char should use a table
if (keywords[state].ident && is_ident_char(*data))
token = keywords[state].ident;
if (token == NOTOKEN) {
++data;
// an error really, but let's ignore this input
// to not confuse moc later. However in pre-processor
// only mode let's continue.
if (!Preprocessor::preprocessOnly)
continue;
}
++column;
if (token > SPECIAL_TREATMENT_MARK) {
switch (token) {
case QUOTE:
data = skipQuote(data);
token = STRING_LITERAL;
// concatenate multi-line strings for easier
// STRING_LITERAAL handling in moc
if (!Preprocessor::preprocessOnly
&& !symbols.isEmpty()
&& symbols.last().token == STRING_LITERAL) {
QByteArray newString = symbols.last().unquotedLexem();
newString += input.mid(lexem - begin + 1, data - lexem - 2);
newString.prepend('\"');
newString.append('\"');
symbols.last() = Symbol(symbols.last().lineNum,
STRING_LITERAL,
newString);
continue;
}
break;
case SINGLEQUOTE:
while (*data && (*data != '\''
|| (*(data-1)=='\\'
&& *(data-2)!='\\')))
++data;
if (*data)
++data;
token = CHARACTER_LITERAL;
break;
case LANGLE_SCOPE:
// split <:: into two tokens, < and ::
token = LANGLE;
data -= 2;
break;
case DIGIT:
while (is_digit_char(*data))
++data;
if (!*data || *data != '.') {
token = INTEGER_LITERAL;
if (data - lexem == 1 &&
(*data == 'x' || *data == 'X')
&& *lexem == '0') {
++data;
while (is_hex_char(*data))
++data;
}
break;
}
token = FLOATING_LITERAL;
++data;
// fall through
case FLOATING_LITERAL:
while (is_digit_char(*data))
++data;
if (*data == '+' || *data == '-')
++data;
if (*data == 'e' || *data == 'E') {
++data;
while (is_digit_char(*data))
++data;
}
if (*data == 'f' || *data == 'F'
|| *data == 'l' || *data == 'L')
++data;
break;
case HASH:
if (column == 1 && mode == TokenizeCpp) {
mode = PreparePreprocessorStatement;
while (*data && (*data == ' ' || *data == '\t'))
++data;
if (is_ident_char(*data))
mode = TokenizePreprocessorStatement;
continue;
}
break;
case PP_HASHHASH:
if (mode == TokenizeCpp)
continue;
break;
case NEWLINE:
++lineNum;
if (mode == TokenizeDefine) {
mode = TokenizeCpp;
// emit the newline token
break;
}
continue;
case BACKSLASH:
{
const char *rewind = data;
while (*data && (*data == ' ' || *data == '\t'))
++data;
if (*data && *data == '\n') {
++data;
continue;
}
data = rewind;
} break;
case CHARACTER:
while (is_ident_char(*data))
++data;
token = IDENTIFIER;
break;
case C_COMMENT:
if (*data) {
if (*data == '\n')
++lineNum;
++data;
if (*data) {
if (*data == '\n')
++lineNum;
++data;
}
}
while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
if (*data == '\n')
++lineNum;
++data;
}
token = WHITESPACE; // one comment, one whitespace
// fall through;
case WHITESPACE:
if (column == 1)
column = 0;
while (*data && (*data == ' ' || *data == '\t'))
++data;
if (Preprocessor::preprocessOnly) // tokenize whitespace
break;
continue;
case CPP_COMMENT:
while (*data && *data != '\n')
++data;
continue; // ignore safely, the newline is a separator
default:
continue; //ignore
}
}
#ifdef USE_LEXEM_STORE
if (!Preprocessor::preprocessOnly
&& token != IDENTIFIER
&& token != STRING_LITERAL
&& token != FLOATING_LITERAL
&& token != INTEGER_LITERAL)
symbols += Symbol(lineNum, token);
else
#endif
symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
} else { // Preprocessor
const char *lexem = data;
int state = 0;
Token token = NOTOKEN;
if (mode == TokenizePreprocessorStatement) {
state = pp_keyword_trans[0][(int)'#'];
mode = TokenizePreprocessor;
}
for (;;) {
if (static_cast<signed char>(*data) < 0) {
++data;
continue;
}
int nextindex = pp_keywords[state].next;
int next = 0;
if (*data == pp_keywords[state].defchar)
next = pp_keywords[state].defnext;
else if (!state || nextindex)
next = pp_keyword_trans[nextindex][(int)*data];
if (!next)
break;
state = next;
token = pp_keywords[state].token;
++data;
}
// suboptimal, is_ident_char should use a table
if (pp_keywords[state].ident && is_ident_char(*data))
token = pp_keywords[state].ident;
switch (token) {
case NOTOKEN:
++data;
break;
case PP_DEFINE:
mode = PrepareDefine;
break;
case PP_IFDEF:
symbols += Symbol(lineNum, PP_IF);
symbols += Symbol(lineNum, PP_DEFINED);
continue;
case PP_IFNDEF:
symbols += Symbol(lineNum, PP_IF);
symbols += Symbol(lineNum, PP_NOT);
symbols += Symbol(lineNum, PP_DEFINED);
continue;
case PP_INCLUDE:
mode = TokenizeInclude;
break;
case PP_QUOTE:
data = skipQuote(data);
token = PP_STRING_LITERAL;
break;
case PP_SINGLEQUOTE:
while (*data && (*data != '\''
|| (*(data-1)=='\\'
&& *(data-2)!='\\')))
++data;
if (*data)
++data;
token = PP_CHARACTER_LITERAL;
break;
case PP_DIGIT:
while (is_digit_char(*data))
++data;
if (!*data || *data != '.') {
token = PP_INTEGER_LITERAL;
if (data - lexem == 1 &&
(*data == 'x' || *data == 'X')
&& *lexem == '0') {
++data;
while (is_hex_char(*data))
++data;
}
break;
}
token = PP_FLOATING_LITERAL;
++data;
// fall through
case PP_FLOATING_LITERAL:
while (is_digit_char(*data))
++data;
if (*data == '+' || *data == '-')
++data;
if (*data == 'e' || *data == 'E') {
++data;
while (is_digit_char(*data))
++data;
}
if (*data == 'f' || *data == 'F'
|| *data == 'l' || *data == 'L')
++data;
break;
case PP_CHARACTER:
if (mode == PreparePreprocessorStatement) {
// rewind entire token to begin
data = lexem;
mode = TokenizePreprocessorStatement;
continue;
}
while (is_ident_char(*data))
++data;
token = PP_IDENTIFIER;
if (mode == PrepareDefine) {
symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
// make sure we explicitly add the whitespace here if the next char
// is not an opening brace, so we can distinguish correctly between
// regular and function macros
if (*data != '(')
symbols += Symbol(lineNum, WHITESPACE);
mode = TokenizeDefine;
continue;
}
break;
case PP_C_COMMENT:
if (*data) {
if (*data == '\n')
++lineNum;
++data;
if (*data) {
if (*data == '\n')
++lineNum;
++data;
}
}
while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
if (*data == '\n')
++lineNum;
++data;
}
token = PP_WHITESPACE; // one comment, one whitespace
// fall through;
case PP_WHITESPACE:
while (*data && (*data == ' ' || *data == '\t'))
++data;
continue; // the preprocessor needs no whitespace
case PP_CPP_COMMENT:
while (*data && *data != '\n')
++data;
continue; // ignore safely, the newline is a separator
case PP_NEWLINE:
++lineNum;
mode = TokenizeCpp;
break;
case PP_BACKSLASH:
{
const char *rewind = data;
while (*data && (*data == ' ' || *data == '\t'))
++data;
if (*data && *data == '\n') {
++data;
continue;
}
data = rewind;
} break;
case PP_LANGLE:
if (mode != TokenizeInclude)
break;
token = PP_STRING_LITERAL;
while (*data && *data != '\n' && *(data-1) != '>')
++data;
break;
default:
break;
}
if (mode == PreparePreprocessorStatement)
continue;
#ifdef USE_LEXEM_STORE
if (token != PP_IDENTIFIER
&& token != PP_STRING_LITERAL
&& token != PP_FLOATING_LITERAL
&& token != PP_INTEGER_LITERAL)
symbols += Symbol(lineNum, token);
else
#endif
symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
}
}
symbols += Symbol(); // eof symbol
return symbols;
}
Symbols Preprocessor::macroExpand(Preprocessor *that, Symbols &toExpand, int &index,
int lineNum, bool one, const QSet<QByteArray> &excludeSymbols)
{
SymbolStack symbols;
SafeSymbols sf;
sf.symbols = toExpand;
sf.index = index;
sf.excludedSymbols = excludeSymbols;
symbols.push(sf);
Symbols result;
if (toExpand.isEmpty())
return result;
for (;;) {
QByteArray macro;
Symbols newSyms = macroExpandIdentifier(that, symbols, lineNum, ¯o);
if (macro.isEmpty()) {
result += newSyms;
} else {
SafeSymbols sf;
sf.symbols = newSyms;
sf.index = 0;
sf.expandedMacro = macro;
symbols.push(sf);
}
if (!symbols.hasNext() || (one && symbols.size() == 1))
break;
symbols.next();
}
if (symbols.size())
index = symbols.top().index;
else
index = toExpand.size();
return result;
}
Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &symbols, int lineNum, QByteArray *macroName)
{
Symbol s = symbols.symbol();
// not a macro
if (s.token != PP_IDENTIFIER || !that->macros.contains(s) || symbols.dontReplaceSymbol(s.lexem())) {
Symbols syms;
syms += s;
syms.last().lineNum = lineNum;
return syms;
}
const Macro ¯o = that->macros.value(s);
*macroName = s.lexem();
Symbols expansion;
if (!macro.isFunction) {
expansion = macro.symbols;
} else {
bool haveSpace = false;
while (symbols.test(PP_WHITESPACE)) { haveSpace = true; }
if (!symbols.test(PP_LPAREN)) {
*macroName = QByteArray();
Symbols syms;
if (haveSpace)
syms += Symbol(lineNum, PP_WHITESPACE);
syms += s;
syms.last().lineNum = lineNum;
return syms;
}
QList<Symbols> arguments;
while (symbols.hasNext()) {
Symbols argument;
// strip leading space
while (symbols.test(PP_WHITESPACE)) {}
int nesting = 0;
bool vararg = macro.isVariadic && (arguments.size() == macro.arguments.size() - 1);
while (symbols.hasNext()) {
Token t = symbols.next();
if (t == PP_LPAREN) {
++nesting;
} else if (t == PP_RPAREN) {
--nesting;
if (nesting < 0)
break;
} else if (t == PP_COMMA && nesting == 0) {
if (!vararg)
break;
}
argument += symbols.symbol();
}
arguments += argument;
if (nesting < 0)
break;
else if (!symbols.hasNext())
that->error("missing ')' in macro usage");
}
// empty VA_ARGS
if (macro.isVariadic && arguments.size() == macro.arguments.size() - 1)
arguments += Symbols();
// now replace the macro arguments with the expanded arguments
enum Mode {
Normal,
Hash,
HashHash
} mode = Normal;
for (int i = 0; i < macro.symbols.size(); ++i) {
const Symbol &s = macro.symbols.at(i);
if (s.token == HASH || s.token == PP_HASHHASH) {
mode = (s.token == HASH ? Hash : HashHash);
continue;
}
int index = macro.arguments.indexOf(s);
if (mode == Normal) {
if (index >= 0 && index < arguments.size()) {
// each argument undoergoes macro expansion if it's not used as part of a # or ##
if (i == macro.symbols.size() - 1 || macro.symbols.at(i + 1).token != PP_HASHHASH) {
Symbols arg = arguments.at(index);
int idx = 1;
expansion += macroExpand(that, arg, idx, lineNum, false, symbols.excludeSymbols());
} else {
expansion += arguments.at(index);
}
} else {
expansion += s;
}
} else if (mode == Hash) {
if (index < 0)
that->error("'#' is not followed by a macro parameter");
const Symbols &arg = arguments.at(index);
QByteArray stringified;
for (int i = 0; i < arg.size(); ++i) {
stringified += arg.at(i).lexem();
}
stringified.replace('"', "\\\"");
stringified.prepend('"');
stringified.append('"');
expansion += Symbol(lineNum, STRING_LITERAL, stringified);
} else if (mode == HashHash){
if (s.token == WHITESPACE)
continue;
while (expansion.size() && expansion.last().token == PP_WHITESPACE)
expansion.pop_back();
Symbol next = s;
if (index >= 0) {
const Symbols &arg = arguments.at(index);
if (arg.size() == 0) {
mode = Normal;
continue;
}
next = arg.at(0);
}
if (!expansion.isEmpty() && expansion.last().token == s.token) {
Symbol last = expansion.last();
expansion.pop_back();
if (last.token == STRING_LITERAL || s.token == STRING_LITERAL)
that->error("Can't concatenate non identifier tokens");
QByteArray lexem = last.lexem() + next.lexem();
expansion += Symbol(lineNum, last.token, lexem);
} else {
expansion += next;
}
if (index >= 0) {
const Symbols &arg = arguments.at(index);
for (int i = 1; i < arg.size(); ++i)
expansion += arg.at(i);
}
}
mode = Normal;
}
if (mode != Normal)
that->error("'#' or '##' found at the end of a macro argument");
}
return expansion;
}
void Preprocessor::substituteUntilNewline(Symbols &substituted)
{
while (hasNext()) {
Token token = next();
if (token == PP_IDENTIFIER) {
substituted += macroExpand(this, symbols, index, symbol().lineNum, true);
} else if (token == PP_DEFINED) {
bool braces = test(PP_LPAREN);
next(PP_IDENTIFIER);
Symbol definedOrNotDefined = symbol();
definedOrNotDefined.token = macros.contains(definedOrNotDefined)? PP_MOC_TRUE : PP_MOC_FALSE;
substituted += definedOrNotDefined;
if (braces)
test(PP_RPAREN);
continue;
} else if (token == PP_NEWLINE) {
substituted += symbol();
break;
} else {
substituted += symbol();
}
}
}
class PP_Expression : public Parser
{
public:
int value() { index = 0; return unary_expression_lookup() ? conditional_expression() : 0; }
int conditional_expression();
int logical_OR_expression();
int logical_AND_expression();
int inclusive_OR_expression();
int exclusive_OR_expression();
int AND_expression();
int equality_expression();
int relational_expression();
int shift_expression();
int additive_expression();
int multiplicative_expression();
int unary_expression();
bool unary_expression_lookup();
int primary_expression();
bool primary_expression_lookup();
};
int PP_Expression::conditional_expression()
{
int value = logical_OR_expression();
if (test(PP_QUESTION)) {
int alt1 = conditional_expression();
int alt2 = test(PP_COLON) ? conditional_expression() : 0;
return value ? alt1 : alt2;
}
return value;
}
int PP_Expression::logical_OR_expression()
{
int value = logical_AND_expression();
if (test(PP_OROR))
return logical_OR_expression() || value;
return value;
}
int PP_Expression::logical_AND_expression()
{
int value = inclusive_OR_expression();
if (test(PP_ANDAND))
return logical_AND_expression() && value;
return value;
}
int PP_Expression::inclusive_OR_expression()
{
int value = exclusive_OR_expression();
if (test(PP_OR))
return value | inclusive_OR_expression();
return value;
}
int PP_Expression::exclusive_OR_expression()
{
int value = AND_expression();
if (test(PP_HAT))
return value ^ exclusive_OR_expression();
return value;
}
int PP_Expression::AND_expression()
{
int value = equality_expression();
if (test(PP_AND))
return value & AND_expression();
return value;
}
int PP_Expression::equality_expression()
{
int value = relational_expression();
switch (next()) {
case PP_EQEQ:
return value == equality_expression();
case PP_NE:
return value != equality_expression();
default:
prev();
return value;
}
}
int PP_Expression::relational_expression()
{
int value = shift_expression();
switch (next()) {
case PP_LANGLE:
return value < relational_expression();
case PP_RANGLE:
return value > relational_expression();
case PP_LE:
return value <= relational_expression();
case PP_GE:
return value >= relational_expression();
default:
prev();
return value;
}
}
int PP_Expression::shift_expression()
{
int value = additive_expression();
switch (next()) {
case PP_LTLT:
return value << shift_expression();
case PP_GTGT:
return value >> shift_expression();
default:
prev();
return value;
}
}
int PP_Expression::additive_expression()
{
int value = multiplicative_expression();
switch (next()) {
case PP_PLUS:
return value + additive_expression();
case PP_MINUS:
return value - additive_expression();
default:
prev();
return value;
}
}
int PP_Expression::multiplicative_expression()
{
int value = unary_expression();
switch (next()) {
case PP_STAR:
return value * multiplicative_expression();
case PP_PERCENT:
{
int remainder = multiplicative_expression();
return remainder ? value % remainder : 0;
}
case PP_SLASH:
{
int div = multiplicative_expression();
return div ? value / div : 0;
}
default:
prev();
return value;
};
}
int PP_Expression::unary_expression()
{
switch (next()) {
case PP_PLUS:
return unary_expression();
case PP_MINUS:
return -unary_expression();
case PP_NOT:
return !unary_expression();
case PP_TILDE:
return ~unary_expression();
case PP_MOC_TRUE:
return 1;
case PP_MOC_FALSE:
return 0;
default:
prev();
return primary_expression();
}
}
bool PP_Expression::unary_expression_lookup()
{
Token t = lookup();
return (primary_expression_lookup()
|| t == PP_PLUS
|| t == PP_MINUS
|| t == PP_NOT
|| t == PP_TILDE
|| t == PP_DEFINED);
}
int PP_Expression::primary_expression()
{
int value;
if (test(PP_LPAREN)) {
value = conditional_expression();
test(PP_RPAREN);
} else {
next();
value = lexem().toInt(0, 0);
}
return value;
}
bool PP_Expression::primary_expression_lookup()
{
Token t = lookup();
return (t == PP_IDENTIFIER
|| t == PP_INTEGER_LITERAL
|| t == PP_FLOATING_LITERAL
|| t == PP_MOC_TRUE
|| t == PP_MOC_FALSE
|| t == PP_LPAREN);
}
int Preprocessor::evaluateCondition()
{
PP_Expression expression;
expression.currentFilenames = currentFilenames;
substituteUntilNewline(expression.symbols);
return expression.value();
}
void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
currentFilenames.push(filename);
preprocessed.reserve(preprocessed.size() + symbols.size());
while (hasNext()) {
Token token = next();
switch (token) {
case PP_INCLUDE:
{
int lineNum = symbol().lineNum;
QByteArray include;
bool local = false;
if (test(PP_STRING_LITERAL)) {
local = lexem().startsWith('\"');
include = unquotedLexem();
} else
continue;
until(PP_NEWLINE);
// #### stringery
QFileInfo fi;
if (local)
fi.setFile(QFileInfo(QString::fromLocal8Bit(filename.constData())).dir(), QString::fromLocal8Bit(include.constData()));
for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
const IncludePath &p = Preprocessor::includes.at(j);
if (p.isFrameworkPath) {
const int slashPos = include.indexOf('/');
if (slashPos == -1)
continue;
QByteArray frameworkCandidate = include.left(slashPos);
frameworkCandidate.append(".framework/Headers/");
fi.setFile(QString::fromLocal8Bit(QByteArray(p.path + '/' + frameworkCandidate).constData()), QString::fromLocal8Bit(include.mid(slashPos + 1).constData()));
} else {
fi.setFile(QString::fromLocal8Bit(p.path.constData()), QString::fromLocal8Bit(include.constData()));
}
// try again, maybe there's a file later in the include paths with the same name
// (186067)
if (fi.isDir()) {
fi = QFileInfo();
continue;
}
}
if (!fi.exists() || fi.isDir())
continue;
include = fi.canonicalFilePath().toLocal8Bit();
if (Preprocessor::preprocessedIncludes.contains(include))
continue;
Preprocessor::preprocessedIncludes.insert(include);
QFile file(QString::fromLocal8Bit(include.constData()));
if (!file.open(QFile::ReadOnly))
continue;
QByteArray input = file.readAll();
file.close();
if (input.isEmpty())
continue;
Symbols saveSymbols = symbols;
int saveIndex = index;
// phase 1: get rid of backslash-newlines
input = cleaned(input);
// phase 2: tokenize for the preprocessor
symbols = tokenize(input);
input.clear();
index = 0;
// phase 3: preprocess conditions and substitute macros
preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
preprocess(include, preprocessed);
preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);
symbols = saveSymbols;
index = saveIndex;
continue;
}
case PP_DEFINE:
{
next(IDENTIFIER);
QByteArray name = lexem();
Macro macro;
macro.isVariadic = false;
Token t = next();
if (t == LPAREN) {
// we have a function macro
macro.isFunction = true;
parseDefineArguments(¯o);
} else if (t == PP_WHITESPACE){
macro.isFunction = false;
} else {
error("Moc: internal error");
}
int start = index;
until(PP_NEWLINE);
macro.symbols.reserve(index - start - 1);
// remove whitespace where there shouldn't be any:
// Before and after the macro, after a # and around ##
Token lastToken = HASH; // skip shitespace at the beginning
for (int i = start; i < index - 1; ++i) {
Token token = symbols.at(i).token;
if (token == PP_WHITESPACE || token == WHITESPACE) {
if (lastToken == PP_HASH || lastToken == HASH ||
lastToken == PP_HASHHASH ||
lastToken == PP_WHITESPACE || lastToken == WHITESPACE)
continue;
} else if (token == PP_HASHHASH) {
if (!macro.symbols.isEmpty() &&
(lastToken == PP_WHITESPACE || lastToken == WHITESPACE))
macro.symbols.pop_back();
}
macro.symbols.append(symbols.at(i));
lastToken = token;
}
// remove trailing whitespace
while (!macro.symbols.isEmpty() &&
(macro.symbols.last().token == PP_WHITESPACE || macro.symbols.last().token == WHITESPACE))
macro.symbols.pop_back();
if (!macro.symbols.isEmpty()) {
if (macro.symbols.first().token == PP_HASHHASH ||
macro.symbols.last().token == PP_HASHHASH) {
error("'##' cannot appear at either end of a macro expansion");
}
}
macros.insert(name, macro);
continue;
}
case PP_UNDEF: {
next(IDENTIFIER);
QByteArray name = lexem();
until(PP_NEWLINE);
macros.remove(name);
continue;
}
case PP_IDENTIFIER: {
// substitute macros
preprocessed += macroExpand(this, symbols, index, symbol().lineNum, true);
continue;
}
case PP_HASH:
until(PP_NEWLINE);
continue; // skip unknown preprocessor statement
case PP_IFDEF:
case PP_IFNDEF:
case PP_IF:
while (!evaluateCondition()) {
if (!skipBranch())
break;
if (test(PP_ELIF)) {
} else {
until(PP_NEWLINE);
break;
}
}
continue;
case PP_ELIF:
case PP_ELSE:
skipUntilEndif();
// fall through
case PP_ENDIF:
until(PP_NEWLINE);
continue;
case PP_NEWLINE:
continue;
case SIGNALS:
case SLOTS: {
Symbol sym = symbol();
if (macros.contains("QT_NO_KEYWORDS"))
sym.token = IDENTIFIER;
else
sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
preprocessed += sym;
} continue;
default:
break;
}
preprocessed += symbol();
}
currentFilenames.pop();
}
Symbols Preprocessor::preprocessed(const QByteArray &filename, QIODevice *file)
{
QByteArray input = file->readAll();
if (input.isEmpty())
return symbols;
// phase 1: get rid of backslash-newlines
input = cleaned(input);
// phase 2: tokenize for the preprocessor
symbols = tokenize(input);
#if 0
for (int j = 0; j < symbols.size(); ++j)
fprintf(stderr, "line %d: %s(%s)\n",
symbols[j].lineNum,
symbols[j].lexem().constData(),
tokenTypeName(symbols[j].token));
#endif
// phase 3: preprocess conditions and substitute macros
Symbols result;
preprocess(filename, result);
#if 0
for (int j = 0; j < result.size(); ++j)
fprintf(stderr, "line %d: %s(%s)\n",
result[j].lineNum,
result[j].lexem().constData(),
tokenTypeName(result[j].token));
#endif
return result;
}
void Preprocessor::parseDefineArguments(Macro *m)
{
Symbols arguments;
while (hasNext()) {
while (test(PP_WHITESPACE)) {}
Token t = next();
if (t == PP_RPAREN)
break;
if (t != PP_IDENTIFIER) {
QByteArray l = lexem();
if (l == "...") {
m->isVariadic = true;
arguments += Symbol(symbol().lineNum, PP_IDENTIFIER, "__VA_ARGS__");
while (test(PP_WHITESPACE)) {}
if (!test(PP_RPAREN))
error("missing ')' in macro argument list");
break;
} else if (!is_identifier(l.constData(), l.length())) {
qDebug() << l;
error("Unexpected character in macro argument list.");
}
}
Symbol arg = symbol();
if (arguments.contains(arg))
error("Duplicate macro parameter.");
arguments += symbol();
while (test(PP_WHITESPACE)) {}
t = next();
if (t == PP_RPAREN)
break;
if (t == PP_COMMA)
continue;
if (lexem() == "...") {
//GCC extension: #define FOO(x, y...) x(y)
// The last argument was already parsed. Just mark the macro as variadic.
m->isVariadic = true;
while (test(PP_WHITESPACE)) {}
if (!test(PP_RPAREN))
error("missing ')' in macro argument list");
break;
}
error("Unexpected character in macro argument list.");
}
m->arguments = arguments;
while (test(PP_WHITESPACE)) {}
}
void Preprocessor::until(Token t)
{
while(hasNext() && next() != t)
;
}
QT_END_NAMESPACE
| bsd-3-clause |
TeslaOS/android_external_skia | samplecode/SampleVertices.cpp | 84 | 6843 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkOSFile.h"
#include "SkStream.h"
static SkShader* make_shader0(SkIPoint* size) {
SkBitmap bm;
size->set(2, 2);
SkPMColor color0 = SkPreMultiplyARGB(0x80, 0x80, 0xff, 0x80);
SkPMColor color1 = SkPreMultiplyARGB(0x40, 0xff, 0x00, 0xff);
bm.allocN32Pixels(size->fX, size->fY);
bm.eraseColor(color0);
bm.lockPixels();
uint32_t* pixels = (uint32_t*) bm.getPixels();
pixels[0] = pixels[2] = color0;
pixels[1] = pixels[3] = color1;
bm.unlockPixels();
return SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
}
static SkShader* make_shader1(const SkIPoint& size) {
SkPoint pts[] = { { 0, 0 },
{ SkIntToScalar(size.fX), SkIntToScalar(size.fY) } };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorRED };
return SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors), SkShader::kMirror_TileMode);
}
class VerticesView : public SampleView {
SkShader* fShader0;
SkShader* fShader1;
public:
VerticesView() {
SkIPoint size;
fShader0 = make_shader0(&size);
fShader1 = make_shader1(size);
make_strip(&fRecs[0], size.fX, size.fY);
make_fan(&fRecs[1], size.fX, size.fY);
make_tris(&fRecs[2]);
fScale = SK_Scalar1;
this->setBGColor(SK_ColorGRAY);
}
virtual ~VerticesView() {
SkSafeUnref(fShader0);
SkSafeUnref(fShader1);
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Vertices");
return true;
}
return this->INHERITED::onQuery(evt);
}
SkScalar fScale;
virtual void onDrawContent(SkCanvas* canvas) {
SkPaint paint;
paint.setDither(true);
paint.setFilterLevel(SkPaint::kLow_FilterLevel);
for (size_t i = 0; i < SK_ARRAY_COUNT(fRecs); i++) {
canvas->save();
paint.setShader(NULL);
canvas->drawVertices(fRecs[i].fMode, fRecs[i].fCount,
fRecs[i].fVerts, fRecs[i].fTexs,
NULL, NULL, NULL, 0, paint);
canvas->translate(SkIntToScalar(250), 0);
paint.setShader(fShader0);
canvas->drawVertices(fRecs[i].fMode, fRecs[i].fCount,
fRecs[i].fVerts, fRecs[i].fTexs,
NULL, NULL, NULL, 0, paint);
canvas->translate(SkIntToScalar(250), 0);
paint.setShader(fShader1);
canvas->drawVertices(fRecs[i].fMode, fRecs[i].fCount,
fRecs[i].fVerts, fRecs[i].fTexs,
NULL, NULL, NULL, 0, paint);
canvas->restore();
canvas->translate(0, SkIntToScalar(250));
}
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned) SK_OVERRIDE {
return new Click(this);
}
virtual bool onClick(Click* click) {
// fCurrX = click->fICurr.fX;
// fCurrY = click->fICurr.fY;
this->inval(NULL);
return true;
}
private:
struct Rec {
SkCanvas::VertexMode fMode;
int fCount;
SkPoint* fVerts;
SkPoint* fTexs;
Rec() : fCount(0), fVerts(NULL), fTexs(NULL) {}
~Rec() { delete[] fVerts; delete[] fTexs; }
};
void make_tris(Rec* rec) {
int n = 10;
SkRandom rand;
rec->fMode = SkCanvas::kTriangles_VertexMode;
rec->fCount = n * 3;
rec->fVerts = new SkPoint[rec->fCount];
for (int i = 0; i < n; i++) {
SkPoint* v = &rec->fVerts[i*3];
for (int j = 0; j < 3; j++) {
v[j].set(rand.nextUScalar1() * 250, rand.nextUScalar1() * 250);
}
}
}
void make_fan(Rec* rec, int texWidth, int texHeight) {
const SkScalar tx = SkIntToScalar(texWidth);
const SkScalar ty = SkIntToScalar(texHeight);
const int n = 24;
rec->fMode = SkCanvas::kTriangleFan_VertexMode;
rec->fCount = n + 2;
rec->fVerts = new SkPoint[rec->fCount];
rec->fTexs = new SkPoint[rec->fCount];
SkPoint* v = rec->fVerts;
SkPoint* t = rec->fTexs;
v[0].set(0, 0);
t[0].set(0, 0);
for (int i = 0; i < n; i++) {
SkScalar cos;
SkScalar sin = SkScalarSinCos(SK_ScalarPI * 2 * i / n, &cos);
v[i+1].set(cos, sin);
t[i+1].set(i*tx/n, ty);
}
v[n+1] = v[1];
t[n+1].set(tx, ty);
SkMatrix m;
m.setScale(SkIntToScalar(100), SkIntToScalar(100));
m.postTranslate(SkIntToScalar(110), SkIntToScalar(110));
m.mapPoints(v, rec->fCount);
}
void make_strip(Rec* rec, int texWidth, int texHeight) {
const SkScalar tx = SkIntToScalar(texWidth);
const SkScalar ty = SkIntToScalar(texHeight);
const int n = 24;
rec->fMode = SkCanvas::kTriangleStrip_VertexMode;
rec->fCount = 2 * (n + 1);
rec->fVerts = new SkPoint[rec->fCount];
rec->fTexs = new SkPoint[rec->fCount];
SkPoint* v = rec->fVerts;
SkPoint* t = rec->fTexs;
for (int i = 0; i < n; i++) {
SkScalar cos;
SkScalar sin = SkScalarSinCos(SK_ScalarPI * 2 * i / n, &cos);
v[i*2 + 0].set(cos/2, sin/2);
v[i*2 + 1].set(cos, sin);
t[i*2 + 0].set(tx * i / n, ty);
t[i*2 + 1].set(tx * i / n, 0);
}
v[2*n + 0] = v[0];
v[2*n + 1] = v[1];
t[2*n + 0].set(tx, ty);
t[2*n + 1].set(tx, 0);
SkMatrix m;
m.setScale(SkIntToScalar(100), SkIntToScalar(100));
m.postTranslate(SkIntToScalar(110), SkIntToScalar(110));
m.mapPoints(v, rec->fCount);
}
Rec fRecs[3];
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new VerticesView; }
static SkViewRegister reg(MyFactory);
| bsd-3-clause |
rishilification/phantomjs | src/qt/qtbase/src/corelib/tools/qmessageauthenticationcode.cpp | 84 | 7925 | /****************************************************************************
**
** Copyright (C) 2013 Ruslan Nigmatullin <euroelessar@yandex.ru>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessageauthenticationcode.h"
#include "qvarlengtharray.h"
/*
These #defines replace the typedefs needed by the RFC6234 code. Normally
the typedefs would come from from stdint.h, but since this header is not
available on all platforms (MSVC 2008, for example), we #define them to the
Qt equivalents.
*/
#define uint64_t QT_PREPEND_NAMESPACE(quint64)
#define uint32_t QT_PREPEND_NAMESPACE(quint32)
#define uint8_t QT_PREPEND_NAMESPACE(quint8)
#define int_least16_t QT_PREPEND_NAMESPACE(qint16)
// Header from rfc6234 with 1 modification:
// sha1.h - commented out '#include <stdint.h>' on line 74
#include "../../3rdparty/rfc6234/sha.h"
#undef uint64_t
#undef uint32_t
#undef uint68_t
#undef int_least16_t
QT_BEGIN_NAMESPACE
static int qt_hash_block_size(QCryptographicHash::Algorithm method)
{
switch (method) {
case QCryptographicHash::Md4:
return 64;
case QCryptographicHash::Md5:
return 64;
case QCryptographicHash::Sha1:
return SHA1_Message_Block_Size;
case QCryptographicHash::Sha224:
return SHA224_Message_Block_Size;
case QCryptographicHash::Sha256:
return SHA256_Message_Block_Size;
case QCryptographicHash::Sha384:
return SHA384_Message_Block_Size;
case QCryptographicHash::Sha512:
return SHA512_Message_Block_Size;
case QCryptographicHash::Sha3_224:
return 144;
case QCryptographicHash::Sha3_256:
return 136;
case QCryptographicHash::Sha3_384:
return 104;
case QCryptographicHash::Sha3_512:
return 72;
}
return 0;
}
class QMessageAuthenticationCodePrivate
{
public:
QMessageAuthenticationCodePrivate(QCryptographicHash::Algorithm m)
: messageHash(m), method(m), messageHashInited(false)
{
}
QByteArray key;
QByteArray result;
QCryptographicHash messageHash;
QCryptographicHash::Algorithm method;
bool messageHashInited;
void initMessageHash();
};
void QMessageAuthenticationCodePrivate::initMessageHash()
{
if (messageHashInited)
return;
messageHashInited = true;
const int blockSize = qt_hash_block_size(method);
if (key.size() > blockSize) {
QCryptographicHash hash(method);
hash.addData(key);
key = hash.result();
hash.reset();
}
if (key.size() < blockSize) {
const int size = key.size();
key.resize(blockSize);
memset(key.data() + size, 0, blockSize - size);
}
QVarLengthArray<char> iKeyPad(blockSize);
const char * const keyData = key.constData();
for (int i = 0; i < blockSize; ++i)
iKeyPad[i] = keyData[i] ^ 0x36;
messageHash.addData(iKeyPad.data(), iKeyPad.size());
}
/*!
\class QMessageAuthenticationCode
\inmodule QtCore
\brief The QMessageAuthenticationCode class provides a way to generate
hash-based message authentication codes.
\since 5.1
\ingroup tools
\reentrant
QMessageAuthenticationCode supports all cryptographic hashes which are supported by
QCryptographicHash.
To generate message authentication code, pass hash algorithm QCryptographicHash::Algorithm
to constructor, then set key and message by setKey() and addData() functions. Result
can be acquired by result() function.
\snippet qmessageauthenticationcode/main.cpp 0
\dots
\snippet qmessageauthenticationcode/main.cpp 1
Alternatively, this effect can be achieved by providing message,
key and method to hash() method.
\snippet qmessageauthenticationcode/main.cpp 2
\sa QCryptographicHash
*/
/*!
Constructs an object that can be used to create a cryptographic hash from data
using method \a method and key \a key.
*/
QMessageAuthenticationCode::QMessageAuthenticationCode(QCryptographicHash::Algorithm method,
const QByteArray &key)
: d(new QMessageAuthenticationCodePrivate(method))
{
d->key = key;
}
/*!
Destroys the object.
*/
QMessageAuthenticationCode::~QMessageAuthenticationCode()
{
delete d;
}
/*!
Resets message data. Calling this method doesn't affect the key.
*/
void QMessageAuthenticationCode::reset()
{
d->result.clear();
d->messageHash.reset();
d->messageHashInited = false;
}
/*!
Sets secret \a key. Calling this method automatically resets the object state.
*/
void QMessageAuthenticationCode::setKey(const QByteArray &key)
{
reset();
d->key = key;
}
/*!
Adds the first \a length chars of \a data to the message.
*/
void QMessageAuthenticationCode::addData(const char *data, int length)
{
d->initMessageHash();
d->messageHash.addData(data, length);
}
/*!
\overload addData()
*/
void QMessageAuthenticationCode::addData(const QByteArray &data)
{
d->initMessageHash();
d->messageHash.addData(data);
}
/*!
Reads the data from the open QIODevice \a device until it ends
and adds it to message. Returns \c true if reading was successful.
\note \a device must be already opened.
*/
bool QMessageAuthenticationCode::addData(QIODevice *device)
{
d->initMessageHash();
return d->messageHash.addData(device);
}
/*!
Returns the final authentication code.
\sa QByteArray::toHex()
*/
QByteArray QMessageAuthenticationCode::result() const
{
if (!d->result.isEmpty())
return d->result;
d->initMessageHash();
const int blockSize = qt_hash_block_size(d->method);
QByteArray hashedMessage = d->messageHash.result();
QVarLengthArray<char> oKeyPad(blockSize);
const char * const keyData = d->key.constData();
for (int i = 0; i < blockSize; ++i)
oKeyPad[i] = keyData[i] ^ 0x5c;
QCryptographicHash hash(d->method);
hash.addData(oKeyPad.data(), oKeyPad.size());
hash.addData(hashedMessage);
d->result = hash.result();
return d->result;
}
/*!
Returns the authentication code for the message \a message using
the key \a key and the method \a method.
*/
QByteArray QMessageAuthenticationCode::hash(const QByteArray &message, const QByteArray &key,
QCryptographicHash::Algorithm method)
{
QMessageAuthenticationCode mac(method);
mac.setKey(key);
mac.addData(message);
return mac.result();
}
QT_END_NAMESPACE
| bsd-3-clause |
wuxiaowei907/annotated_redis_source | deps/jemalloc/src/chunk_dss.c | 340 | 4167 | #define JEMALLOC_CHUNK_DSS_C_
#include "jemalloc/internal/jemalloc_internal.h"
/******************************************************************************/
/* Data. */
const char *dss_prec_names[] = {
"disabled",
"primary",
"secondary",
"N/A"
};
/* Current dss precedence default, used when creating new arenas. */
static dss_prec_t dss_prec_default = DSS_PREC_DEFAULT;
/*
* Protects sbrk() calls. This avoids malloc races among threads, though it
* does not protect against races with threads that call sbrk() directly.
*/
static malloc_mutex_t dss_mtx;
/* Base address of the DSS. */
static void *dss_base;
/* Current end of the DSS, or ((void *)-1) if the DSS is exhausted. */
static void *dss_prev;
/* Current upper limit on DSS addresses. */
static void *dss_max;
/******************************************************************************/
#ifndef JEMALLOC_HAVE_SBRK
static void *
sbrk(intptr_t increment)
{
not_implemented();
return (NULL);
}
#endif
dss_prec_t
chunk_dss_prec_get(void)
{
dss_prec_t ret;
if (config_dss == false)
return (dss_prec_disabled);
malloc_mutex_lock(&dss_mtx);
ret = dss_prec_default;
malloc_mutex_unlock(&dss_mtx);
return (ret);
}
bool
chunk_dss_prec_set(dss_prec_t dss_prec)
{
if (config_dss == false)
return (true);
malloc_mutex_lock(&dss_mtx);
dss_prec_default = dss_prec;
malloc_mutex_unlock(&dss_mtx);
return (false);
}
void *
chunk_alloc_dss(size_t size, size_t alignment, bool *zero)
{
void *ret;
cassert(config_dss);
assert(size > 0 && (size & chunksize_mask) == 0);
assert(alignment > 0 && (alignment & chunksize_mask) == 0);
/*
* sbrk() uses a signed increment argument, so take care not to
* interpret a huge allocation request as a negative increment.
*/
if ((intptr_t)size < 0)
return (NULL);
malloc_mutex_lock(&dss_mtx);
if (dss_prev != (void *)-1) {
size_t gap_size, cpad_size;
void *cpad, *dss_next;
intptr_t incr;
/*
* The loop is necessary to recover from races with other
* threads that are using the DSS for something other than
* malloc.
*/
do {
/* Get the current end of the DSS. */
dss_max = sbrk(0);
/*
* Calculate how much padding is necessary to
* chunk-align the end of the DSS.
*/
gap_size = (chunksize - CHUNK_ADDR2OFFSET(dss_max)) &
chunksize_mask;
/*
* Compute how much chunk-aligned pad space (if any) is
* necessary to satisfy alignment. This space can be
* recycled for later use.
*/
cpad = (void *)((uintptr_t)dss_max + gap_size);
ret = (void *)ALIGNMENT_CEILING((uintptr_t)dss_max,
alignment);
cpad_size = (uintptr_t)ret - (uintptr_t)cpad;
dss_next = (void *)((uintptr_t)ret + size);
if ((uintptr_t)ret < (uintptr_t)dss_max ||
(uintptr_t)dss_next < (uintptr_t)dss_max) {
/* Wrap-around. */
malloc_mutex_unlock(&dss_mtx);
return (NULL);
}
incr = gap_size + cpad_size + size;
dss_prev = sbrk(incr);
if (dss_prev == dss_max) {
/* Success. */
dss_max = dss_next;
malloc_mutex_unlock(&dss_mtx);
if (cpad_size != 0)
chunk_unmap(cpad, cpad_size);
if (*zero) {
VALGRIND_MAKE_MEM_UNDEFINED(ret, size);
memset(ret, 0, size);
}
return (ret);
}
} while (dss_prev != (void *)-1);
}
malloc_mutex_unlock(&dss_mtx);
return (NULL);
}
bool
chunk_in_dss(void *chunk)
{
bool ret;
cassert(config_dss);
malloc_mutex_lock(&dss_mtx);
if ((uintptr_t)chunk >= (uintptr_t)dss_base
&& (uintptr_t)chunk < (uintptr_t)dss_max)
ret = true;
else
ret = false;
malloc_mutex_unlock(&dss_mtx);
return (ret);
}
bool
chunk_dss_boot(void)
{
cassert(config_dss);
if (malloc_mutex_init(&dss_mtx))
return (true);
dss_base = sbrk(0);
dss_prev = dss_base;
dss_max = dss_base;
return (false);
}
void
chunk_dss_prefork(void)
{
if (config_dss)
malloc_mutex_prefork(&dss_mtx);
}
void
chunk_dss_postfork_parent(void)
{
if (config_dss)
malloc_mutex_postfork_parent(&dss_mtx);
}
void
chunk_dss_postfork_child(void)
{
if (config_dss)
malloc_mutex_postfork_child(&dss_mtx);
}
/******************************************************************************/
| bsd-3-clause |
JCROM-Android/jcrom_external_chromium_org | native_client_sdk/src/libraries/third_party/pthreads-win32/pthread_attr_setstacksize.c | 342 | 3486 | /*
* pthread_attr_setstacksize.c
*
* Description:
* This translation unit implements operations on thread attribute objects.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* 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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
int
pthread_attr_setstacksize (pthread_attr_t * attr, size_t stacksize)
/*
* ------------------------------------------------------
* DOCPUBLIC
* This function specifies the size of the stack on
* which threads created with 'attr' will run.
*
* PARAMETERS
* attr
* pointer to an instance of pthread_attr_t
*
* stacksize
* stack size, in bytes.
*
*
* DESCRIPTION
* This function specifies the size of the stack on
* which threads created with 'attr' will run.
*
* NOTES:
* 1) Function supported only if this macro is
* defined:
*
* _POSIX_THREAD_ATTR_STACKSIZE
*
* 2) Find the default first (using
* pthread_attr_getstacksize), then increase
* by multiplying.
*
* 3) Only use if thread needs more than the
* default.
*
* RESULTS
* 0 successfully set stack size,
* EINVAL 'attr' is invalid or stacksize too
* small or too big.
* ENOSYS function not supported
*
* ------------------------------------------------------
*/
{
#if defined(_POSIX_THREAD_ATTR_STACKSIZE)
#if PTHREAD_STACK_MIN > 0
/* Verify that the stack size is within range. */
if (stacksize < PTHREAD_STACK_MIN)
{
return EINVAL;
}
#endif
if (ptw32_is_attr (attr) != 0)
{
return EINVAL;
}
/* Everything is okay. */
(*attr)->stacksize = stacksize;
return 0;
#else
return ENOSYS;
#endif /* _POSIX_THREAD_ATTR_STACKSIZE */
}
| bsd-3-clause |
shelsonjava/TeaJS | deps/v8/third_party/icu/source/test/intltest/msfmrgts.cpp | 367 | 37175 | /***********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2011, International Business Machines Corporation
* and others. All Rights Reserved.
***********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "msfmrgts.h"
#include "unicode/format.h"
#include "unicode/decimfmt.h"
#include "unicode/locid.h"
#include "unicode/msgfmt.h"
#include "unicode/numfmt.h"
#include "unicode/choicfmt.h"
#include "unicode/gregocal.h"
#include "putilimp.h"
// *****************************************************************************
// class MessageFormatRegressionTest
// *****************************************************************************
#define CASE(id,test) case id: name = #test; if (exec) { logln(#test "---"); logln((UnicodeString)""); test(); } break;
void
MessageFormatRegressionTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
TESTCASE_AUTO_BEGIN;
TESTCASE_AUTO(Test4074764)
//TESTCASE_AUTO(Test4058973) -- disabled/obsolete in ICU 4.8
TESTCASE_AUTO(Test4031438)
TESTCASE_AUTO(Test4052223)
TESTCASE_AUTO(Test4104976)
TESTCASE_AUTO(Test4106659)
TESTCASE_AUTO(Test4106660)
TESTCASE_AUTO(Test4111739)
TESTCASE_AUTO(Test4114743)
TESTCASE_AUTO(Test4116444)
TESTCASE_AUTO(Test4114739)
TESTCASE_AUTO(Test4113018)
TESTCASE_AUTO(Test4106661)
TESTCASE_AUTO(Test4094906)
TESTCASE_AUTO(Test4118592)
TESTCASE_AUTO(Test4118594)
TESTCASE_AUTO(Test4105380)
TESTCASE_AUTO(Test4120552)
TESTCASE_AUTO(Test4142938)
TESTCASE_AUTO(TestChoicePatternQuote)
TESTCASE_AUTO(Test4112104)
TESTCASE_AUTO(TestAPI)
TESTCASE_AUTO_END;
}
UBool
MessageFormatRegressionTest::failure(UErrorCode status, const char* msg, UBool possibleDataError)
{
if(U_FAILURE(status)) {
if (possibleDataError) {
dataerrln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status));
} else {
errln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status));
}
return TRUE;
}
return FALSE;
}
/* @bug 4074764
* Null exception when formatting pattern with MessageFormat
* with no parameters.
*/
void MessageFormatRegressionTest::Test4074764() {
UnicodeString pattern [] = {
"Message without param",
"Message with param:{0}",
"Longer Message with param {0}"
};
//difference between the two param strings are that
//in the first one, the param position is within the
//length of the string without param while it is not so
//in the other case.
UErrorCode status = U_ZERO_ERROR;
MessageFormat *messageFormatter = new MessageFormat("", status);
failure(status, "couldn't create MessageFormat");
//try {
//Apply pattern with param and print the result
messageFormatter->applyPattern(pattern[1], status);
failure(status, "messageFormat->applyPattern");
//Object[] params = {new UnicodeString("BUG"), new Date()};
Formattable params [] = {
Formattable(UnicodeString("BUG")),
Formattable(0, Formattable::kIsDate)
};
UnicodeString tempBuffer;
FieldPosition pos(FieldPosition::DONT_CARE);
tempBuffer = messageFormatter->format(params, 2, tempBuffer, pos, status);
if( tempBuffer != "Message with param:BUG" || failure(status, "messageFormat->format"))
errln("MessageFormat with one param test failed.");
logln("Formatted with one extra param : " + tempBuffer);
//Apply pattern without param and print the result
messageFormatter->applyPattern(pattern[0], status);
failure(status, "messageFormatter->applyPattern");
// {sfb} how much does this apply in C++?
// do we want to verify that the Formattable* array is not NULL,
// or is that the user's responsibility?
// additionally, what should be the item count?
// for bug testing purposes, assume that something was set to
// NULL by mistake, and that the length should be non-zero
//tempBuffer = messageFormatter->format(NULL, 1, tempBuffer, FieldPosition(FieldPosition::DONT_CARE), status);
tempBuffer.remove();
tempBuffer = messageFormatter->format(NULL, 0, tempBuffer, pos, status);
if( tempBuffer != "Message without param" || failure(status, "messageFormat->format"))
errln("MessageFormat with no param test failed.");
logln("Formatted with no params : " + tempBuffer);
tempBuffer.remove();
tempBuffer = messageFormatter->format(params, 2, tempBuffer, pos, status);
if (tempBuffer != "Message without param" || failure(status, "messageFormat->format"))
errln("Formatted with arguments > subsitution failed. result = " + tempBuffer);
logln("Formatted with extra params : " + tempBuffer);
//This statement gives an exception while formatting...
//If we use pattern[1] for the message with param,
//we get an NullPointerException in MessageFormat.java(617)
//If we use pattern[2] for the message with param,
//we get an StringArrayIndexOutOfBoundsException in MessageFormat.java(614)
//Both are due to maxOffset not being reset to -1
//in applyPattern() when the pattern does not
//contain any param.
/*} catch (Exception foo) {
errln("Exception when formatting with no params.");
}*/
delete messageFormatter;
}
/* @bug 4058973
* MessageFormat.toPattern has weird rounding behavior.
*
* ICU 4.8: This test is commented out because toPattern() has been changed to return
* the original pattern string, rather than reconstituting a new (equivalent) one.
* This trivially eliminates issues with rounding or any other pattern string differences.
*/
/*
void MessageFormatRegressionTest::Test4058973()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *fmt = new MessageFormat("{0,choice,0#no files|1#one file|1< {0,number,integer} files}", status);
failure(status, "new MessageFormat");
UnicodeString pat;
pat = fmt->toPattern(pat);
UnicodeString exp("{0,choice,0#no files|1#one file|1< {0,number,integer} files}");
if (pat != exp) {
errln("MessageFormat.toPattern failed");
errln("Exp: " + exp);
errln("Got: " + pat);
}
delete fmt;
}*/
/* @bug 4031438
* More robust message formats.
*/
void MessageFormatRegressionTest::Test4031438()
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString pattern1("Impossible {1} has occurred -- status code is {0} and message is {2}.");
UnicodeString pattern2("Double '' Quotes {0} test and quoted '{1}' test plus 'other {2} stuff'.");
MessageFormat *messageFormatter = new MessageFormat("", status);
failure(status, "new MessageFormat");
const UBool possibleDataError = TRUE;
//try {
logln("Apply with pattern : " + pattern1);
messageFormatter->applyPattern(pattern1, status);
failure(status, "messageFormat->applyPattern");
//Object[] params = {new Integer(7)};
Formattable params []= {
Formattable((int32_t)7)
};
UnicodeString tempBuffer;
FieldPosition pos(FieldPosition::DONT_CARE);
tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status);
if(tempBuffer != "Impossible {1} has occurred -- status code is 7 and message is {2}." || failure(status, "MessageFormat::format"))
dataerrln("Tests arguments < substitution failed");
logln("Formatted with 7 : " + tempBuffer);
ParsePosition pp(0);
int32_t count = 0;
Formattable *objs = messageFormatter->parse(tempBuffer, pp, count);
//if(objs[7/*params.length*/] != NULL)
// errln("Parse failed with more than expected arguments");
NumberFormat *fmt = 0;
UnicodeString temp, temp1;
for (int i = 0; i < count; i++) {
// convert to string if not already
Formattable obj = objs[i];
temp.remove();
if(obj.getType() == Formattable::kString)
temp = obj.getString(temp);
else {
fmt = NumberFormat::createInstance(status);
switch (obj.getType()) {
case Formattable::kLong: fmt->format(obj.getLong(), temp); break;
case Formattable::kInt64: fmt->format(obj.getInt64(), temp); break;
case Formattable::kDouble: fmt->format(obj.getDouble(), temp); break;
default: break;
}
}
// convert to string if not already
Formattable obj1 = params[i];
temp1.remove();
if(obj1.getType() == Formattable::kString)
temp1 = obj1.getString(temp1);
else {
fmt = NumberFormat::createInstance(status);
switch (obj1.getType()) {
case Formattable::kLong: fmt->format(obj1.getLong(), temp1); break;
case Formattable::kInt64: fmt->format(obj1.getInt64(), temp1); break;
case Formattable::kDouble: fmt->format(obj1.getDouble(), temp1); break;
default: break;
}
}
//if (objs[i] != NULL && objs[i].getString(temp1) != params[i].getString(temp2)) {
if (temp != temp1) {
errln("Parse failed on object " + objs[i].getString(temp1) + " at index : " + i);
}
}
delete fmt;
delete [] objs;
// {sfb} does this apply? no way to really pass a null Formattable,
// only a null array
/*tempBuffer = messageFormatter->format(null, tempBuffer, FieldPosition(FieldPosition::DONT_CARE), status);
if (tempBuffer != "Impossible {1} has occurred -- status code is {0} and message is {2}." || failure(status, "messageFormat->format"))
errln("Tests with no arguments failed");
logln("Formatted with null : " + tempBuffer);*/
logln("Apply with pattern : " + pattern2);
messageFormatter->applyPattern(pattern2, status);
failure(status, "messageFormatter->applyPattern", possibleDataError);
tempBuffer.remove();
tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status);
if (tempBuffer != "Double ' Quotes 7 test and quoted {1} test plus 'other {2} stuff'.")
dataerrln("quote format test (w/ params) failed. - %s", u_errorName(status));
logln("Formatted with params : " + tempBuffer);
/*tempBuffer = messageFormatter->format(null);
if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff."))
errln("quote format test (w/ null) failed.");
logln("Formatted with null : " + tempBuffer);
logln("toPattern : " + messageFormatter.toPattern());*/
/*} catch (Exception foo) {
errln("Exception when formatting in bug 4031438. "+foo.getMessage());
}*/
delete messageFormatter;
}
void MessageFormatRegressionTest::Test4052223()
{
ParsePosition pos(0);
if (pos.getErrorIndex() != -1) {
errln("ParsePosition.getErrorIndex initialization failed.");
}
UErrorCode status = U_ZERO_ERROR;
MessageFormat *fmt = new MessageFormat("There are {0} apples growing on the {1} tree.", status);
failure(status, "new MessageFormat");
UnicodeString str("There is one apple growing on the peach tree.");
int32_t count = 0;
fmt->parse(str, pos, count);
logln(UnicodeString("unparsable string , should fail at ") + pos.getErrorIndex());
if (pos.getErrorIndex() == -1)
errln("Bug 4052223 failed : parsing string " + str);
pos.setErrorIndex(4);
if (pos.getErrorIndex() != 4)
errln(UnicodeString("setErrorIndex failed, got ") + pos.getErrorIndex() + " instead of 4");
ChoiceFormat *f = new ChoiceFormat(
"-1#are negative|0#are no or fraction|1#is one|1.0<is 1+|2#are two|2<are more than 2.", status);
failure(status, "new ChoiceFormat");
pos.setIndex(0);
pos.setErrorIndex(-1);
Formattable obj;
f->parse("are negative", obj, pos);
if (pos.getErrorIndex() != -1 && obj.getDouble() == -1.0)
errln(UnicodeString("Parse with \"are negative\" failed, at ") + pos.getErrorIndex());
pos.setIndex(0);
pos.setErrorIndex(-1);
f->parse("are no or fraction ", obj, pos);
if (pos.getErrorIndex() != -1 && obj.getDouble() == 0.0)
errln(UnicodeString("Parse with \"are no or fraction\" failed, at ") + pos.getErrorIndex());
pos.setIndex(0);
pos.setErrorIndex(-1);
f->parse("go postal", obj, pos);
if (pos.getErrorIndex() == -1 && ! uprv_isNaN(obj.getDouble()))
errln(UnicodeString("Parse with \"go postal\" failed, at ") + pos.getErrorIndex());
delete fmt;
delete f;
}
/* @bug 4104976
* ChoiceFormat.equals(null) throws NullPointerException
*/
// {sfb} not really applicable in C++?? (kind of silly)
void MessageFormatRegressionTest::Test4104976()
{
double limits [] = {1, 20};
UnicodeString formats [] = {
UnicodeString("xyz"),
UnicodeString("abc")
};
int32_t formats_length = (int32_t)(sizeof(formats)/sizeof(formats[0]));
UErrorCode status = U_ZERO_ERROR;
ChoiceFormat *cf = new ChoiceFormat(limits, formats, formats_length);
failure(status, "new ChoiceFormat");
//try {
log("Compares to null is always false, returned : ");
logln(cf == NULL ? "TRUE" : "FALSE");
/*} catch (Exception foo) {
errln("ChoiceFormat.equals(null) throws exception.");
}*/
delete cf;
}
/* @bug 4106659
* ChoiceFormat.ctor(double[], String[]) doesn't check
* whether lengths of input arrays are equal.
*/
// {sfb} again, not really applicable in C++
void MessageFormatRegressionTest::Test4106659()
{
/*
double limits [] = {
1, 2, 3
};
UnicodeString formats [] = {
"one", "two"
};
ChoiceFormat *cf = NULL;
//try {
// cf = new ChoiceFormat(limits, formats, 3);
//} catch (Exception foo) {
// logln("ChoiceFormat constructor should check for the array lengths");
// cf = null;
//}
//if (cf != null)
// errln(cf->format(5));
//
delete cf;
*/
}
/* @bug 4106660
* ChoiceFormat.ctor(double[], String[]) allows unordered double array.
* This is not a bug, added javadoc to emphasize the use of limit
* array must be in ascending order.
*/
void MessageFormatRegressionTest::Test4106660()
{
double limits [] = {3, 1, 2};
UnicodeString formats [] = {
UnicodeString("Three"),
UnicodeString("One"),
UnicodeString("Two")
};
ChoiceFormat *cf = new ChoiceFormat(limits, formats, 3);
double d = 5.0;
UnicodeString str;
FieldPosition pos(FieldPosition::DONT_CARE);
str = cf->format(d, str, pos);
if (str != "Two")
errln( (UnicodeString) "format(" + d + ") = " + str);
delete cf;
}
/* @bug 4111739
* MessageFormat is incorrectly serialized/deserialized.
*/
// {sfb} doesn't apply in C++
void MessageFormatRegressionTest::Test4111739()
{
/*MessageFormat format1 = null;
MessageFormat format2 = null;
ObjectOutputStream ostream = null;
ByteArrayOutputStream baos = null;
ObjectInputStream istream = null;
try {
baos = new ByteArrayOutputStream();
ostream = new ObjectOutputStream(baos);
} catch(IOException e) {
errln("Unexpected exception : " + e.getMessage());
return;
}
try {
format1 = new MessageFormat("pattern{0}");
ostream.writeObject(format1);
ostream.flush();
byte bytes[] = baos.toByteArray();
istream = new ObjectInputStream(new ByteArrayInputStream(bytes));
format2 = (MessageFormat)istream.readObject();
} catch(Exception e) {
errln("Unexpected exception : " + e.getMessage());
}
if (!format1.equals(format2)) {
errln("MessageFormats before and after serialization are not" +
" equal\nformat1 = " + format1 + "(" + format1.toPattern() + ")\nformat2 = " +
format2 + "(" + format2.toPattern() + ")");
} else {
logln("Serialization for MessageFormat is OK.");
}*/
}
/* @bug 4114743
* MessageFormat.applyPattern allows illegal patterns.
*/
void MessageFormatRegressionTest::Test4114743()
{
UnicodeString originalPattern("initial pattern");
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat(originalPattern, status);
failure(status, "new MessageFormat");
//try {
UnicodeString illegalPattern("ab { '}' de");
mf->applyPattern(illegalPattern, status);
if( ! U_FAILURE(status))
errln("illegal pattern: \"" + illegalPattern + "\"");
/*} catch (IllegalArgumentException foo) {
if (!originalPattern.equals(mf.toPattern()))
errln("pattern after: \"" + mf.toPattern() + "\"");
}*/
delete mf;
}
/* @bug 4116444
* MessageFormat.parse has different behavior in case of null.
*/
void MessageFormatRegressionTest::Test4116444()
{
UnicodeString patterns [] = {
(UnicodeString)"",
(UnicodeString)"one",
(UnicodeString) "{0,date,short}"
};
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat("", status);
failure(status, "new MessageFormat");
for (int i = 0; i < 3; i++) {
UnicodeString pattern = patterns[i];
mf->applyPattern(pattern, status);
failure(status, "mf->applyPattern", TRUE);
//try {
int32_t count = 0;
ParsePosition pp(0);
Formattable *array = mf->parse(UnicodeString(""), pp, count);
logln("pattern: \"" + pattern + "\"");
log(" parsedObjects: ");
if (array != NULL) {
log("{");
for (int j = 0; j < count; j++) {
//if (array[j] != null)
UnicodeString dummy;
dataerrln("\"" + array[j].getString(dummy) + "\"");
//else
// log("null");
if (j < count- 1)
log(",");
}
log("}") ;
delete[] array;
} else {
log("null");
}
logln("");
/*} catch (Exception e) {
errln("pattern: \"" + pattern + "\"");
errln(" Exception: " + e.getMessage());
}*/
}
delete mf;
}
/* @bug 4114739 (FIX and add javadoc)
* MessageFormat.format has undocumented behavior about empty format objects.
*/
// {sfb} doesn't apply in C++?
void MessageFormatRegressionTest::Test4114739()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat("<{0}>", status);
failure(status, "new MessageFormat");
Formattable *objs1 = NULL;
//Formattable objs2 [] = {};
//Formattable *objs3 [] = {NULL};
//try {
UnicodeString pat;
UnicodeString res;
logln("pattern: \"" + mf->toPattern(pat) + "\"");
log("format(null) : ");
FieldPosition pos(FieldPosition::DONT_CARE);
logln("\"" + mf->format(objs1, 0, res, pos, status) + "\"");
failure(status, "mf->format");
/*log("format({}) : ");
logln("\"" + mf->format(objs2, 0, res, FieldPosition(FieldPosition::DONT_CARE), status) + "\"");
failure(status, "mf->format");
log("format({null}) :");
logln("\"" + mf->format(objs3, 0, res, FieldPosition(FieldPosition::DONT_CARE), status) + "\"");
failure(status, "mf->format");*/
/*} catch (Exception e) {
errln("Exception thrown for null argument tests.");
}*/
delete mf;
}
/* @bug 4113018
* MessageFormat.applyPattern works wrong with illegal patterns.
*/
void MessageFormatRegressionTest::Test4113018()
{
UnicodeString originalPattern("initial pattern");
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat(originalPattern, status);
failure(status, "new messageFormat");
UnicodeString illegalPattern("format: {0, xxxYYY}");
UnicodeString pat;
logln("pattern before: \"" + mf->toPattern(pat) + "\"");
logln("illegal pattern: \"" + illegalPattern + "\"");
//try {
mf->applyPattern(illegalPattern, status);
if( ! U_FAILURE(status))
errln("Should have thrown IllegalArgumentException for pattern : " + illegalPattern);
/*} catch (IllegalArgumentException e) {
if (!originalPattern.equals(mf.toPattern()))
errln("pattern after: \"" + mf.toPattern() + "\"");
}*/
delete mf;
}
/* @bug 4106661
* ChoiceFormat is silent about the pattern usage in javadoc.
*/
void MessageFormatRegressionTest::Test4106661()
{
UErrorCode status = U_ZERO_ERROR;
ChoiceFormat *fmt = new ChoiceFormat(
"-1#are negative| 0#are no or fraction | 1#is one |1.0<is 1+ |2#are two |2<are more than 2.", status);
failure(status, "new ChoiceFormat");
UnicodeString pat;
logln("Formatter Pattern : " + fmt->toPattern(pat));
FieldPosition bogus(FieldPosition::DONT_CARE);
UnicodeString str;
// Will this work for -inf?
logln("Format with -INF : " + fmt->format(Formattable(-uprv_getInfinity()), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 1.0 : " + fmt->format(Formattable(1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with NaN : " + fmt->format(Formattable(uprv_getNaN()), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with +INF : " + fmt->format(Formattable(uprv_getInfinity()), str, bogus, status));
failure(status, "fmt->format");
delete fmt;
}
/* @bug 4094906
* ChoiceFormat should accept \u221E as eq. to INF.
*/
void MessageFormatRegressionTest::Test4094906()
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString pattern("-");
pattern += (UChar) 0x221E;
pattern += "<are negative|0<are no or fraction|1#is one|1<is 1+|";
pattern += (UChar) 0x221E;
pattern += "<are many.";
ChoiceFormat *fmt = new ChoiceFormat(pattern, status);
failure(status, "new ChoiceFormat");
UnicodeString pat;
if (fmt->toPattern(pat) != pattern) {
errln( (UnicodeString) "Formatter Pattern : " + pat);
errln( (UnicodeString) "Expected Pattern : " + pattern);
}
FieldPosition bogus(FieldPosition::DONT_CARE);
UnicodeString str;
// Will this work for -inf?
logln("Format with -INF : " + fmt->format(Formattable(-uprv_getInfinity()), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 1.0 : " + fmt->format(Formattable(1.0), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with NaN : " + fmt->format(Formattable(uprv_getNaN()), str, bogus, status));
failure(status, "fmt->format");
str.remove();
logln("Format with +INF : " + fmt->format(Formattable(uprv_getInfinity()), str, bogus, status));
failure(status, "fmt->format");
delete fmt;
}
/* @bug 4118592
* MessageFormat.parse fails with ChoiceFormat.
*/
void MessageFormatRegressionTest::Test4118592()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat("", status);
failure(status, "new messageFormat");
UnicodeString pattern("{0,choice,1#YES|2#NO}");
UnicodeString prefix("");
Formattable *objs = 0;
for (int i = 0; i < 5; i++) {
UnicodeString formatted;
formatted = prefix + "YES";
mf->applyPattern(prefix + pattern, status);
failure(status, "mf->applyPattern");
prefix += "x";
//Object[] objs = mf.parse(formatted, new ParsePosition(0));
int32_t count = 0;
ParsePosition pp(0);
objs = mf->parse(formatted, pp, count);
UnicodeString pat;
logln(UnicodeString("") + i + ". pattern :\"" + mf->toPattern(pat) + "\"");
log(" \"" + formatted + "\" parsed as ");
if (objs == NULL)
logln(" null");
else {
UnicodeString temp;
if(objs[0].getType() == Formattable::kString)
logln((UnicodeString)" " + objs[0].getString(temp));
else
logln((UnicodeString)" " + (objs[0].getType() == Formattable::kLong ? objs[0].getLong() : objs[0].getDouble()));
delete[] objs;
}
}
delete mf;
}
/* @bug 4118594
* MessageFormat.parse fails for some patterns.
*/
void MessageFormatRegressionTest::Test4118594()
{
UErrorCode status = U_ZERO_ERROR;
const UBool possibleDataError = TRUE;
MessageFormat *mf = new MessageFormat("{0}, {0}, {0}", status);
failure(status, "new MessageFormat");
UnicodeString forParsing("x, y, z");
//Object[] objs = mf.parse(forParsing, new ParsePosition(0));
int32_t count = 0;
ParsePosition pp(0);
Formattable *objs = mf->parse(forParsing, pp, count);
UnicodeString pat;
logln("pattern: \"" + mf->toPattern(pat) + "\"");
logln("text for parsing: \"" + forParsing + "\"");
UnicodeString str;
if (objs[0].getString(str) != "z")
errln("argument0: \"" + objs[0].getString(str) + "\"");
mf->applyPattern("{0,number,#.##}, {0,number,#.#}", status);
failure(status, "mf->applyPattern", possibleDataError);
//Object[] oldobjs = {new Double(3.1415)};
Formattable oldobjs [] = {Formattable(3.1415)};
UnicodeString result;
FieldPosition pos(FieldPosition::DONT_CARE);
result = mf->format( oldobjs, 1, result, pos, status );
failure(status, "mf->format", possibleDataError);
pat.remove();
logln("pattern: \"" + mf->toPattern(pat) + "\"");
logln("text for parsing: \"" + result + "\"");
// result now equals "3.14, 3.1"
if (result != "3.14, 3.1")
dataerrln("result = " + result + " - " + u_errorName(status));
//Object[] newobjs = mf.parse(result, new ParsePosition(0));
int32_t count1 = 0;
pp.setIndex(0);
Formattable *newobjs = mf->parse(result, pp, count1);
// newobjs now equals {new Double(3.1)}
if (newobjs == NULL) {
dataerrln("Error calling MessageFormat::parse");
} else {
if (newobjs[0].getDouble() != 3.1)
errln( UnicodeString("newobjs[0] = ") + newobjs[0].getDouble());
}
delete [] objs;
delete [] newobjs;
delete mf;
}
/* @bug 4105380
* When using ChoiceFormat, MessageFormat is not good for I18n.
*/
void MessageFormatRegressionTest::Test4105380()
{
UnicodeString patternText1("The disk \"{1}\" contains {0}.");
UnicodeString patternText2("There are {0} on the disk \"{1}\"");
UErrorCode status = U_ZERO_ERROR;
const UBool possibleDataError = TRUE;
MessageFormat *form1 = new MessageFormat(patternText1, status);
failure(status, "new MessageFormat");
MessageFormat *form2 = new MessageFormat(patternText2, status);
failure(status, "new MessageFormat");
double filelimits [] = {0,1,2};
UnicodeString filepart [] = {
(UnicodeString)"no files",
(UnicodeString)"one file",
(UnicodeString)"{0,number} files"
};
ChoiceFormat *fileform = new ChoiceFormat(filelimits, filepart, 3);
form1->setFormat(1, *fileform);
form2->setFormat(0, *fileform);
//Object[] testArgs = {new Long(12373), "MyDisk"};
Formattable testArgs [] = {
Formattable((int32_t)12373),
Formattable((UnicodeString)"MyDisk")
};
FieldPosition bogus(FieldPosition::DONT_CARE);
UnicodeString result;
logln(form1->format(testArgs, 2, result, bogus, status));
failure(status, "form1->format", possibleDataError);
result.remove();
logln(form2->format(testArgs, 2, result, bogus, status));
failure(status, "form1->format", possibleDataError);
delete form1;
delete form2;
delete fileform;
}
/* @bug 4120552
* MessageFormat.parse incorrectly sets errorIndex.
*/
void MessageFormatRegressionTest::Test4120552()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat("pattern", status);
failure(status, "new MessageFormat");
UnicodeString texts[] = {
(UnicodeString)"pattern",
(UnicodeString)"pat",
(UnicodeString)"1234"
};
UnicodeString pat;
logln("pattern: \"" + mf->toPattern(pat) + "\"");
for (int i = 0; i < 3; i++) {
ParsePosition pp(0);
//Object[] objs = mf.parse(texts[i], pp);
int32_t count = 0;
Formattable *objs = mf->parse(texts[i], pp, count);
log(" text for parsing: \"" + texts[i] + "\"");
if (objs == NULL) {
logln(" (incorrectly formatted string)");
if (pp.getErrorIndex() == -1)
errln(UnicodeString("Incorrect error index: ") + pp.getErrorIndex());
} else {
logln(" (correctly formatted string)");
delete[] objs;
}
}
delete mf;
}
/**
* @bug 4142938
* MessageFormat handles single quotes in pattern wrong.
* This is actually a problem in ChoiceFormat; it doesn't
* understand single quotes.
*/
void MessageFormatRegressionTest::Test4142938()
{
UnicodeString pat = CharsToUnicodeString("''Vous'' {0,choice,0#n''|1#}avez s\\u00E9lectionn\\u00E9 "
"{0,choice,0#aucun|1#{0}} client{0,choice,0#s|1#|2#s} "
"personnel{0,choice,0#s|1#|2#s}.");
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat(pat, status);
failure(status, "new MessageFormat");
UnicodeString PREFIX [] = {
CharsToUnicodeString("'Vous' n'avez s\\u00E9lectionn\\u00E9 aucun clients personnels."),
CharsToUnicodeString("'Vous' avez s\\u00E9lectionn\\u00E9 "),
CharsToUnicodeString("'Vous' avez s\\u00E9lectionn\\u00E9 ")
};
UnicodeString SUFFIX [] = {
UnicodeString(),
UNICODE_STRING(" client personnel.", 18),
UNICODE_STRING(" clients personnels.", 20)
};
for (int i=0; i<3; i++) {
UnicodeString out;
//out = mf->format(new Object[]{new Integer(i)});
Formattable objs [] = {
Formattable((int32_t)i)
};
FieldPosition pos(FieldPosition::DONT_CARE);
out = mf->format(objs, 1, out, pos, status);
if (!failure(status, "mf->format", TRUE)) {
if (SUFFIX[i] == "") {
if (out != PREFIX[i])
errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"");
}
else {
if (!out.startsWith(PREFIX[i]) ||
!out.endsWith(SUFFIX[i]))
errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"...\"" +
SUFFIX[i] + "\"");
}
}
}
delete mf;
}
/**
* @bug 4142938
* Test the applyPattern and toPattern handling of single quotes
* by ChoiceFormat. (This is in here because this was a bug reported
* against MessageFormat.) The single quote is used to quote the
* pattern characters '|', '#', '<', and '\u2264'. Two quotes in a row
* is a quote literal.
*/
void MessageFormatRegressionTest::TestChoicePatternQuote()
{
// ICU 4.8 ChoiceFormat (like PluralFormat & SelectFormat)
// returns the chosen string unmodified, so that it is usable in a MessageFormat.
// We modified the test strings accordingly.
// Note: Without further formatting/trimming/etc., it is not possible
// to get a single apostrophe as the last character of a non-final choice sub-message
// because the single apostrophe before the pipe '|' would start quoted text.
// Normally, ChoiceFormat is used inside a MessageFormat, where a double apostrophe
// can be used in that case and will be formatted as a single one.
// (Better: Use a "real" apostrophe, U+2019.)
UnicodeString DATA [] = {
// Pattern 0 value 1 value
// {sfb} hacked - changed \u2264 to = (copied from Character Map)
"0#can't|1#can", "can't", "can",
"0#pound(#)='#''|1#xyz", "pound(#)='#''", "xyz",
"0#1<2 '| 1=1'|1#'", "1<2 '| 1=1'", "'",
};
for (int i=0; i<9; i+=3) {
//try {
UErrorCode status = U_ZERO_ERROR;
ChoiceFormat *cf = new ChoiceFormat(DATA[i], status);
failure(status, "new ChoiceFormat");
for (int j=0; j<=1; ++j) {
UnicodeString out;
FieldPosition pos(FieldPosition::DONT_CARE);
out = cf->format((double)j, out, pos);
if (out != DATA[i+1+j])
errln("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " +
out + "; want \"" + DATA[i+1+j] + "\"");
}
UnicodeString pat;
pat = cf->toPattern(pat);
UnicodeString pat2;
ChoiceFormat *cf2 = new ChoiceFormat(pat, status);
pat2 = cf2->toPattern(pat2);
if (pat != pat2)
errln("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + "\"");
else
logln("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + "\"");
/*}
catch (IllegalArgumentException e) {
errln("Fail: Pattern \"" + DATA[i] + "\" -> " + e);
}*/
delete cf;
delete cf2;
}
}
/**
* @bug 4112104
* MessageFormat.equals(null) throws a NullPointerException. The JLS states
* that it should return false.
*/
void MessageFormatRegressionTest::Test4112104()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *format = new MessageFormat("", status);
failure(status, "new MessageFormat");
//try {
// This should NOT throw an exception
if (format == NULL) {
// It also should return false
errln("MessageFormat.equals(null) returns false");
}
/*}
catch (NullPointerException e) {
errln("MessageFormat.equals(null) throws " + e);
}*/
delete format;
}
void MessageFormatRegressionTest::TestAPI() {
UErrorCode status = U_ZERO_ERROR;
MessageFormat *format = new MessageFormat("", status);
failure(status, "new MessageFormat");
// Test adoptFormat
MessageFormat *fmt = new MessageFormat("",status);
format->adoptFormat("some_name",fmt,status); // Must at least pass a valid identifier.
failure(status, "adoptFormat");
// Test getFormat
format->setFormat((int32_t)0,*fmt);
format->getFormat("some_other_name",status); // Must at least pass a valid identifier.
failure(status, "getFormat");
delete format;
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| bsd-3-clause |
zhulin2609/phantomjs | src/qt/qtwebkit/Source/WebKit2/Shared/WebPageCreationParameters.cpp | 113 | 5072 | /*
* Copyright (C) 2010, 2011 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. 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.
*/
#include "config.h"
#include "WebPageCreationParameters.h"
#include "WebCoreArgumentCoders.h"
namespace WebKit {
void WebPageCreationParameters::encode(CoreIPC::ArgumentEncoder& encoder) const
{
encoder << viewSize;
encoder << isActive;
encoder << isFocused;
encoder << isVisible;
encoder << isInWindow;
encoder << store;
encoder.encodeEnum(drawingAreaType);
encoder << pageGroupData;
encoder << drawsBackground;
encoder << drawsTransparentBackground;
encoder << underlayColor;
encoder << areMemoryCacheClientCallsEnabled;
encoder << useFixedLayout;
encoder << fixedLayoutSize;
encoder.encodeEnum(paginationMode);
encoder << paginationBehavesLikeColumns;
encoder << pageLength;
encoder << gapBetweenPages;
encoder << userAgent;
encoder << sessionState;
encoder << highestUsedBackForwardItemID;
encoder << canRunBeforeUnloadConfirmPanel;
encoder << canRunModal;
encoder << deviceScaleFactor;
encoder << mediaVolume;
encoder << mayStartMediaWhenInWindow;
encoder << minimumLayoutSize;
encoder.encodeEnum(scrollPinningBehavior);
#if PLATFORM(MAC)
encoder.encodeEnum(layerHostingMode);
encoder << colorSpace;
#endif
}
bool WebPageCreationParameters::decode(CoreIPC::ArgumentDecoder& decoder, WebPageCreationParameters& parameters)
{
if (!decoder.decode(parameters.viewSize))
return false;
if (!decoder.decode(parameters.isActive))
return false;
if (!decoder.decode(parameters.isFocused))
return false;
if (!decoder.decode(parameters.isVisible))
return false;
if (!decoder.decode(parameters.isInWindow))
return false;
if (!decoder.decode(parameters.store))
return false;
if (!decoder.decodeEnum(parameters.drawingAreaType))
return false;
if (!decoder.decode(parameters.pageGroupData))
return false;
if (!decoder.decode(parameters.drawsBackground))
return false;
if (!decoder.decode(parameters.drawsTransparentBackground))
return false;
if (!decoder.decode(parameters.underlayColor))
return false;
if (!decoder.decode(parameters.areMemoryCacheClientCallsEnabled))
return false;
if (!decoder.decode(parameters.useFixedLayout))
return false;
if (!decoder.decode(parameters.fixedLayoutSize))
return false;
if (!decoder.decodeEnum(parameters.paginationMode))
return false;
if (!decoder.decode(parameters.paginationBehavesLikeColumns))
return false;
if (!decoder.decode(parameters.pageLength))
return false;
if (!decoder.decode(parameters.gapBetweenPages))
return false;
if (!decoder.decode(parameters.userAgent))
return false;
if (!decoder.decode(parameters.sessionState))
return false;
if (!decoder.decode(parameters.highestUsedBackForwardItemID))
return false;
if (!decoder.decode(parameters.canRunBeforeUnloadConfirmPanel))
return false;
if (!decoder.decode(parameters.canRunModal))
return false;
if (!decoder.decode(parameters.deviceScaleFactor))
return false;
if (!decoder.decode(parameters.mediaVolume))
return false;
if (!decoder.decode(parameters.mayStartMediaWhenInWindow))
return false;
if (!decoder.decode(parameters.minimumLayoutSize))
return false;
if (!decoder.decodeEnum(parameters.scrollPinningBehavior))
return false;
#if PLATFORM(MAC)
if (!decoder.decodeEnum(parameters.layerHostingMode))
return false;
if (!decoder.decode(parameters.colorSpace))
return false;
#endif
return true;
}
} // namespace WebKit
| bsd-3-clause |
klim-iv/phantomjs-qt5 | src/webkit/Source/WebCore/platform/text/TextEncodingDetectorICU.cpp | 113 | 4946 | /*
* Copyright (C) 2008, 2009 Google Inc. 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.
* * Neither the name of Google Inc. 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 "config.h"
#include "TextEncodingDetector.h"
#include "TextEncoding.h"
#include "unicode/ucnv.h"
#include "unicode/ucsdet.h"
namespace WebCore {
bool detectTextEncoding(const char* data, size_t len,
const char* hintEncodingName,
TextEncoding* detectedEncoding)
{
*detectedEncoding = TextEncoding();
int matchesCount = 0;
UErrorCode status = U_ZERO_ERROR;
UCharsetDetector* detector = ucsdet_open(&status);
if (U_FAILURE(status))
return false;
ucsdet_enableInputFilter(detector, true);
ucsdet_setText(detector, data, static_cast<int32_t>(len), &status);
if (U_FAILURE(status))
return false;
// FIXME: A few things we can do other than improving
// the ICU detector itself.
// 1. Use ucsdet_detectAll and pick the most likely one given
// "the context" (parent-encoding, referrer encoding, etc).
// 2. 'Emulate' Firefox/IE's non-Universal detectors (e.g.
// Chinese, Japanese, Russian, Korean and Hebrew) by picking the
// encoding with a highest confidence among the detector-specific
// limited set of candidate encodings.
// Below is a partial implementation of the first part of what's outlined
// above.
const UCharsetMatch** matches = ucsdet_detectAll(detector, &matchesCount, &status);
if (U_FAILURE(status)) {
ucsdet_close(detector);
return false;
}
const char* encoding = 0;
if (hintEncodingName) {
TextEncoding hintEncoding(hintEncodingName);
// 10 is the minimum confidence value consistent with the codepoint
// allocation in a given encoding. The size of a chunk passed to
// us varies even for the same html file (apparently depending on
// the network load). When we're given a rather short chunk, we
// don't have a sufficiently reliable signal other than the fact that
// the chunk is consistent with a set of encodings. So, instead of
// setting an arbitrary threshold, we have to scan all the encodings
// consistent with the data.
const int32_t kThresold = 10;
for (int i = 0; i < matchesCount; ++i) {
int32_t confidence = ucsdet_getConfidence(matches[i], &status);
if (U_FAILURE(status)) {
status = U_ZERO_ERROR;
continue;
}
if (confidence < kThresold)
break;
const char* matchEncoding = ucsdet_getName(matches[i], &status);
if (U_FAILURE(status)) {
status = U_ZERO_ERROR;
continue;
}
if (TextEncoding(matchEncoding) == hintEncoding) {
encoding = hintEncodingName;
break;
}
}
}
// If no match is found so far, just pick the top match.
// This can happen, say, when a parent frame in EUC-JP refers to
// a child frame in Shift_JIS and both frames do NOT specify the encoding
// making us resort to auto-detection (when it IS turned on).
if (!encoding && matchesCount > 0)
encoding = ucsdet_getName(matches[0], &status);
if (U_SUCCESS(status)) {
*detectedEncoding = TextEncoding(encoding);
ucsdet_close(detector);
return true;
}
ucsdet_close(detector);
return false;
}
}
| bsd-3-clause |
liorvh/phantomjs | src/qt/qtwebkit/Source/WebCore/html/DOMURL.cpp | 113 | 5307 | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
* Copyright (C) 2012 Motorola Mobility Inc.
*
* 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 APPLE AND ITS 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 APPLE 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.
*/
#include "config.h"
#if ENABLE(BLOB)
#include "DOMURL.h"
#include "ActiveDOMObject.h"
#include "Blob.h"
#include "BlobURL.h"
#include "KURL.h"
#include "MemoryCache.h"
#include "PublicURLManager.h"
#include "ResourceRequest.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "ThreadableBlobRegistry.h"
#include <wtf/MainThread.h>
#if ENABLE(MEDIA_SOURCE)
#include "MediaSource.h"
#include "MediaSourceRegistry.h"
#endif
#if ENABLE(MEDIA_STREAM)
#include "MediaStream.h"
#include "MediaStreamRegistry.h"
#endif
namespace WebCore {
#if ENABLE(MEDIA_SOURCE)
String DOMURL::createObjectURL(ScriptExecutionContext* scriptExecutionContext, MediaSource* source)
{
// Since WebWorkers cannot obtain MediaSource objects, we should be on the main thread.
ASSERT(isMainThread());
if (!scriptExecutionContext || !source)
return String();
KURL publicURL = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
if (publicURL.isEmpty())
return String();
MediaSourceRegistry::registry().registerMediaSourceURL(publicURL, source);
scriptExecutionContext->publicURLManager().sourceURLs().add(publicURL.string());
return publicURL.string();
}
#endif
#if ENABLE(MEDIA_STREAM)
String DOMURL::createObjectURL(ScriptExecutionContext* scriptExecutionContext, MediaStream* stream)
{
if (!scriptExecutionContext || !stream)
return String();
KURL publicURL = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
if (publicURL.isEmpty())
return String();
// Since WebWorkers cannot obtain Stream objects, we should be on the main thread.
ASSERT(isMainThread());
MediaStreamRegistry::registry().registerMediaStreamURL(publicURL, stream);
scriptExecutionContext->publicURLManager().streamURLs().add(publicURL.string());
return publicURL.string();
}
#endif
String DOMURL::createObjectURL(ScriptExecutionContext* scriptExecutionContext, Blob* blob)
{
if (!scriptExecutionContext || !blob)
return String();
KURL publicURL = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
if (publicURL.isEmpty())
return String();
ThreadableBlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), publicURL, blob->url());
scriptExecutionContext->publicURLManager().blobURLs().add(publicURL.string());
return publicURL.string();
}
void DOMURL::revokeObjectURL(ScriptExecutionContext* scriptExecutionContext, const String& urlString)
{
if (!scriptExecutionContext)
return;
KURL url(KURL(), urlString);
ResourceRequest request(url);
#if ENABLE(CACHE_PARTITIONING)
request.setCachePartition(scriptExecutionContext->topOrigin()->cachePartition());
#endif
MemoryCache::removeRequestFromCache(scriptExecutionContext, request);
HashSet<String>& blobURLs = scriptExecutionContext->publicURLManager().blobURLs();
if (blobURLs.contains(url.string())) {
ThreadableBlobRegistry::unregisterBlobURL(url);
blobURLs.remove(url.string());
}
#if ENABLE(MEDIA_SOURCE)
HashSet<String>& sourceURLs = scriptExecutionContext->publicURLManager().sourceURLs();
if (sourceURLs.contains(url.string())) {
MediaSourceRegistry::registry().unregisterMediaSourceURL(url);
sourceURLs.remove(url.string());
}
#endif
#if ENABLE(MEDIA_STREAM)
HashSet<String>& streamURLs = scriptExecutionContext->publicURLManager().streamURLs();
if (streamURLs.contains(url.string())) {
// FIXME: make sure of this assertion below. Raise a spec question if required.
// Since WebWorkers cannot obtain Stream objects, we should be on the main thread.
ASSERT(isMainThread());
MediaStreamRegistry::registry().unregisterMediaStreamURL(url);
streamURLs.remove(url.string());
}
#endif
}
} // namespace WebCore
#endif // ENABLE(BLOB)
| bsd-3-clause |
gnu3ra/SCC15HPCRepast | INSTALLATION/boost_1_54_0/libs/msm/doc/PDF/examples/OrthogonalDeferredEuml.cpp | 114 | 12042 | // Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. 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 <vector>
#include <iostream>
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/euml/euml.hpp>
using namespace std;
using namespace boost::msm::front::euml;
namespace msm = boost::msm;
// entry/exit/action/guard logging functors
#include "logging_functors.h"
namespace // Concrete FSM implementation
{
// events
BOOST_MSM_EUML_EVENT(play)
BOOST_MSM_EUML_EVENT(end_pause)
BOOST_MSM_EUML_EVENT(stop)
BOOST_MSM_EUML_EVENT(pause)
BOOST_MSM_EUML_EVENT(open_close)
BOOST_MSM_EUML_EVENT(next_song)
BOOST_MSM_EUML_EVENT(previous_song)
BOOST_MSM_EUML_EVENT(end_error)
BOOST_MSM_EUML_EVENT(error_found)
// A "complicated" event type that carries some data.
BOOST_MSM_EUML_DECLARE_ATTRIBUTE(std::string,cd_name)
BOOST_MSM_EUML_DECLARE_ATTRIBUTE(DiskTypeEnum,cd_type)
BOOST_MSM_EUML_ATTRIBUTES((attributes_ << cd_name << cd_type ), cd_detected_attributes)
BOOST_MSM_EUML_EVENT_WITH_ATTRIBUTES(cd_detected,cd_detected_attributes)
// Flags. Allow information about a property of the current state
BOOST_MSM_EUML_FLAG(PlayingPaused)
BOOST_MSM_EUML_FLAG(CDLoaded)
BOOST_MSM_EUML_FLAG(FirstSongPlaying)
// Concrete FSM implementation
// The list of FSM states
BOOST_MSM_EUML_STATE(( Empty_Entry,
Empty_Exit,
attributes_ << no_attributes_,
configure_ << play // defer play
),
Empty)
BOOST_MSM_EUML_STATE(( Open_Entry,
Open_Exit,
attributes_ << no_attributes_,
configure_<< CDLoaded << play // defer play, flag state with CDLoaded
),
Open)
BOOST_MSM_EUML_STATE(( Stopped_Entry,
Stopped_Exit,
attributes_ << no_attributes_,
configure_<< CDLoaded // flag state with CDLoaded
),
Stopped)
// state not defining any entry or exit
BOOST_MSM_EUML_STATE(( no_action,
no_action,
attributes_ << no_attributes_,
configure_<< PlayingPaused << CDLoaded // flag state with CDLoaded and PlayingPaused
),
Paused)
BOOST_MSM_EUML_STATE(( AllOk_Entry,AllOk_Exit ),AllOk)
// a terminate state
//BOOST_MSM_EUML_TERMINATE_STATE(( ErrorMode_Entry,ErrorMode_Exit ),ErrorMode)
// or as an interrupt state
BOOST_MSM_EUML_INTERRUPT_STATE(( end_error,ErrorMode_Entry,ErrorMode_Exit ),ErrorMode)
// Playing is now a state machine itself.
// It has 3 substates
BOOST_MSM_EUML_STATE(( Song1_Entry,
Song1_Exit,
attributes_ << no_attributes_,
configure_<< FirstSongPlaying ),Song1)
BOOST_MSM_EUML_STATE(( Song2_Entry,Song2_Exit ),Song2)
BOOST_MSM_EUML_STATE(( Song3_Entry,Song3_Exit ),Song3)
// Playing has a transition table
BOOST_MSM_EUML_TRANSITION_TABLE((
// +------------------------------------------------------------------------------+
Song2 == Song1 + next_song / start_next_song,
Song1 == Song2 + previous_song / start_prev_song,
Song3 == Song2 + next_song / start_next_song,
Song2 == Song3 + previous_song / start_prev_song
// +------------------------------------------------------------------------------+
),playing_transition_table )
BOOST_MSM_EUML_DECLARE_STATE_MACHINE( (playing_transition_table, //STT
init_ << Song1, // Init State
no_action, // entry
no_action, // exit
attributes_ << no_attributes_, //attributes
configure_<< PlayingPaused << CDLoaded //flags
),Playing_)
// choice of back-end
typedef msm::back::state_machine<Playing_> Playing_type;
Playing_type const Playing;
// guard conditions
BOOST_MSM_EUML_ACTION(good_disk_format)
{
template <class FSM,class EVT,class SourceState,class TargetState>
bool operator()(EVT const& evt,FSM&,SourceState& ,TargetState& )
{
// to test a guard condition, let's say we understand only CDs, not DVD
if (evt.get_attribute(cd_type)!=DISK_CD)
{
std::cout << "wrong disk, sorry" << std::endl;
// just for logging, does not block any transition
return true;
}
std::cout << "good disk" << std::endl;
return true;
}
};
// replaces the old transition table
BOOST_MSM_EUML_TRANSITION_TABLE((
Playing == Stopped + play / start_playback ,
Playing == Paused + end_pause / resume_playback,
// +------------------------------------------------------------------------------+
Empty == Open + open_close / close_drawer,
// +------------------------------------------------------------------------------+
Open == Empty + open_close / open_drawer,
Open == Paused + open_close / stop_and_open,
Open == Stopped + open_close / open_drawer,
Open == Playing + open_close / stop_and_open,
// +------------------------------------------------------------------------------+
Paused == Playing + pause / pause_playback,
// +------------------------------------------------------------------------------+
Stopped == Playing + stop / stop_playback,
Stopped == Paused + stop / stop_playback,
Stopped == Empty + cd_detected [good_disk_format&&
(event_(cd_type)==Int_<DISK_CD>())]
/ (store_cd_info,process_(play)),
Stopped == Stopped + stop,
ErrorMode == AllOk + error_found / report_error,
AllOk == ErrorMode+ end_error / report_end_error
// +------------------------------------------------------------------------------+
),transition_table)
// create a state machine "on the fly"
BOOST_MSM_EUML_DECLARE_STATE_MACHINE(( transition_table, //STT
init_ << Empty<< AllOk, // Init State
no_action, // Entry
no_action, // Exit
attributes_ << no_attributes_, // Attributes
configure_ << no_configure_, // configuration
Log_No_Transition // no_transition handler
),
player_) //fsm name
// choice of back-end
typedef msm::back::state_machine<player_> player;
//
// Testing utilities.
//
static char const* const state_names[] = { "Stopped", "Paused", "Open", "Empty", "Playing","AllOk","ErrorMode" };
void pstate(player const& p)
{
// we have now several active states, which we show
for (unsigned int i=0;i<player::nr_regions::value;++i)
{
std::cout << " -> " << state_names[p.current_state()[i]] << std::endl;
}
}
void test()
{
player p;
// needed to start the highest-level SM. This will call on_entry and mark the start of the SM
p.start();
// tests some flags
std::cout << "CDLoaded active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(CDLoaded)>() << std::endl; //=> false (no CD yet)
// go to Open, call on_exit on Empty, then action, then on_entry on Open
p.process_event(open_close); pstate(p);
p.process_event(open_close); pstate(p);
// will be rejected, wrong disk type
p.process_event(
cd_detected("louie, louie",DISK_DVD)); pstate(p);
p.process_event(
cd_detected("louie, louie",DISK_CD)); pstate(p);
// no need to call play as the previous event does it in its action method
//p.process_event(play);
// at this point, Play is active
std::cout << "PlayingPaused active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(PlayingPaused)>() << std::endl;//=> true
std::cout << "FirstSong active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(FirstSongPlaying)>() << std::endl;//=> true
// make transition happen inside it. Player has no idea about this event but it's ok.
p.process_event(next_song);pstate(p); //2nd song active
p.process_event(next_song);pstate(p);//3rd song active
p.process_event(previous_song);pstate(p);//2nd song active
std::cout << "FirstSong active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(FirstSongPlaying)>() << std::endl;//=> false
std::cout << "PlayingPaused active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(PlayingPaused)>() << std::endl;//=> true
// at this point, Play is active
p.process_event(pause); pstate(p);
std::cout << "PlayingPaused active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(PlayingPaused)>() << std::endl;//=> true
// go back to Playing
p.process_event(end_pause); pstate(p);
p.process_event(pause); pstate(p);
p.process_event(stop); pstate(p);
std::cout << "PlayingPaused active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(PlayingPaused)>() << std::endl;//=> false
std::cout << "CDLoaded active:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(CDLoaded)>() << std::endl;//=> true
// by default, the flags are OR'ed but you can also use AND. Then the flag must be present in
// all of the active states
std::cout << "CDLoaded active with AND:" << std::boolalpha
<< p.is_flag_active<BOOST_MSM_EUML_FLAG_NAME(CDLoaded),player::Flag_AND>() << std::endl;//=> false
// event leading to the same state
// no action method called as none is defined in the transition table
p.process_event(stop); pstate(p);
// event leading to a terminal/interrupt state
p.process_event(error_found); pstate(p);
// try generating more events
std::cout << "Trying to generate another event" << std::endl; // will not work, fsm is terminated or interrupted
p.process_event(play);pstate(p);
std::cout << "Trying to end the error" << std::endl; // will work only if ErrorMode is interrupt state
p.process_event(end_error);pstate(p);
std::cout << "Trying to generate another event" << std::endl; // will work only if ErrorMode is interrupt state
p.process_event(play);pstate(p);
}
}
int main()
{
test();
return 0;
}
| bsd-3-clause |
Tomtomgo/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/graphics/cg/FloatSizeCG.cpp | 114 | 1739 | /*
* Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
* Copyright (C) 2005 Nokia. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "FloatSize.h"
#if USE(CG)
#include <ApplicationServices/ApplicationServices.h>
namespace WebCore {
FloatSize::FloatSize(const CGSize& s) : m_width(s.width), m_height(s.height)
{
}
FloatSize::operator CGSize() const
{
return CGSizeMake(m_width, m_height);
}
}
#endif // USE(CG)
| bsd-3-clause |
attilahorvath/phantomjs | src/qt/qtwebkit/Source/WebKit2/Shared/linux/WebMemorySamplerLinux.cpp | 116 | 7796 | /*
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
* Copyright (C) 2012 Samsung Electronics
*
* 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 APPLE INC. AND ITS 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 APPLE INC. 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.
*/
#include "config.h"
#include "WebMemorySampler.h"
#if ENABLE(MEMORY_SAMPLER)
#include "NotImplemented.h"
#include <JavaScriptCore/MemoryStatistics.h>
#include <WebCore/JSDOMWindow.h>
#include <runtime/JSLock.h>
#include <runtime/Operations.h>
#include <string.h>
#include <sys/sysinfo.h>
#include <wtf/CurrentTime.h>
#include <wtf/text/WTFString.h>
using namespace WebCore;
using namespace JSC;
using namespace WTF;
namespace WebKit {
struct ApplicationMemoryStats {
size_t totalProgramSize;
size_t residentSetSize;
size_t sharedSize;
size_t textSize;
size_t librarySize;
size_t dataStackSize;
size_t dirtyPageSize;
};
static const unsigned int maxBuffer = 128;
static const unsigned int maxProcessPath = 35;
static inline String nextToken(FILE* file)
{
ASSERT(file);
if (!file)
return String();
char buffer[maxBuffer] = {0, };
unsigned int index = 0;
while (index < maxBuffer) {
char ch = fgetc(file);
if (ch == EOF || (isASCIISpace(ch) && index)) // Break on non-initial ASCII space.
break;
if (!isASCIISpace(ch)) {
buffer[index] = ch;
index++;
}
}
return String(buffer);
}
static inline void appendKeyValuePair(WebMemoryStatistics& stats, const String& key, size_t value)
{
stats.keys.append(key);
stats.values.append(value);
}
static ApplicationMemoryStats sampleMemoryAllocatedForApplication()
{
ApplicationMemoryStats applicationStats;
char processPath[maxProcessPath];
snprintf(processPath, maxProcessPath, "/proc/self/statm");
FILE* statmFileDescriptor = fopen(processPath, "r");
if (!statmFileDescriptor)
return applicationStats;
applicationStats.totalProgramSize = nextToken(statmFileDescriptor).toInt();
applicationStats.residentSetSize = nextToken(statmFileDescriptor).toInt();
applicationStats.sharedSize = nextToken(statmFileDescriptor).toInt();
applicationStats.textSize = nextToken(statmFileDescriptor).toInt();
applicationStats.librarySize = nextToken(statmFileDescriptor).toInt();
applicationStats.dataStackSize = nextToken(statmFileDescriptor).toInt();
applicationStats.dirtyPageSize = nextToken(statmFileDescriptor).toInt();
fclose(statmFileDescriptor);
return applicationStats;
}
String WebMemorySampler::processName() const
{
char processPath[maxProcessPath];
snprintf(processPath, maxProcessPath, "/proc/self/status");
FILE* statusFileDescriptor = fopen(processPath, "r");
if (!statusFileDescriptor)
return String();
nextToken(statusFileDescriptor);
String processName = nextToken(statusFileDescriptor);
fclose(statusFileDescriptor);
return processName;
}
WebMemoryStatistics WebMemorySampler::sampleWebKit() const
{
WebMemoryStatistics webKitMemoryStats;
double now = currentTime();
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Timestamp"), now);
ApplicationMemoryStats applicationStats = sampleMemoryAllocatedForApplication();
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Program Size"), applicationStats.totalProgramSize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("RSS"), applicationStats.residentSetSize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Shared"), applicationStats.sharedSize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Text"), applicationStats.textSize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Library"), applicationStats.librarySize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Data/Stack"), applicationStats.dataStackSize);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Dirty"), applicationStats.dirtyPageSize);
size_t totalBytesInUse = 0;
size_t totalBytesCommitted = 0;
#if ENABLE(GLOBAL_FASTMALLOC_NEW)
FastMallocStatistics fastMallocStatistics = WTF::fastMallocStatistics();
size_t fastMallocBytesInUse = fastMallocStatistics.committedVMBytes - fastMallocStatistics.freeListBytes;
size_t fastMallocBytesCommitted = fastMallocStatistics.committedVMBytes;
totalBytesInUse += fastMallocBytesInUse;
totalBytesCommitted += fastMallocBytesCommitted;
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Fast Malloc In Use"), fastMallocBytesInUse);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Fast Malloc Committed Memory"), fastMallocBytesCommitted);
#endif
size_t jscHeapBytesInUse = JSDOMWindow::commonVM()->heap.size();
size_t jscHeapBytesCommitted = JSDOMWindow::commonVM()->heap.capacity();
totalBytesInUse += jscHeapBytesInUse;
totalBytesCommitted += jscHeapBytesCommitted;
GlobalMemoryStatistics globalMemoryStats = globalMemoryStatistics();
totalBytesInUse += globalMemoryStats.stackBytes + globalMemoryStats.JITBytes;
totalBytesCommitted += globalMemoryStats.stackBytes + globalMemoryStats.JITBytes;
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Heap In Use"), jscHeapBytesInUse);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Heap Commited Memory"), jscHeapBytesCommitted);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript Stack Bytes"), globalMemoryStats.stackBytes);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("JavaScript JIT Bytes"), globalMemoryStats.JITBytes);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Memory In Use"), totalBytesInUse);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Committed Memory"), totalBytesCommitted);
struct sysinfo systemInfo;
if (!sysinfo(&systemInfo)) {
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("System Total Bytes"), systemInfo.totalram);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Available Bytes"), systemInfo.freeram);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Shared Bytes"), systemInfo.sharedram);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Buffer Bytes"), systemInfo.bufferram);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Total Swap Bytes"), systemInfo.totalswap);
appendKeyValuePair(webKitMemoryStats, ASCIILiteral("Available Swap Bytes"), systemInfo.freeswap);
}
return webKitMemoryStats;
}
void WebMemorySampler::sendMemoryPressureEvent()
{
notImplemented();
}
}
#endif
| bsd-3-clause |
petermat/phantomjs | src/qt/qtwebkit/Source/JavaScriptCore/dfg/DFGVirtualRegisterAllocationPhase.cpp | 118 | 6156 | /*
* Copyright (C) 2011 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "DFGVirtualRegisterAllocationPhase.h"
#if ENABLE(DFG_JIT)
#include "DFGGraph.h"
#include "DFGScoreBoard.h"
#include "JSCellInlines.h"
namespace JSC { namespace DFG {
class VirtualRegisterAllocationPhase : public Phase {
public:
VirtualRegisterAllocationPhase(Graph& graph)
: Phase(graph, "virtual register allocation")
{
}
bool run()
{
#if DFG_ENABLE(DEBUG_VERBOSE)
dataLogF("Preserved vars: ");
m_graph.m_preservedVars.dump(WTF::dataFile());
dataLogF("\n");
#endif
ScoreBoard scoreBoard(m_graph.m_preservedVars);
scoreBoard.assertClear();
#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
bool needsNewLine = false;
#endif
for (size_t blockIndex = 0; blockIndex < m_graph.m_blocks.size(); ++blockIndex) {
BasicBlock* block = m_graph.m_blocks[blockIndex].get();
if (!block)
continue;
if (!block->isReachable)
continue;
for (size_t indexInBlock = 0; indexInBlock < block->size(); ++indexInBlock) {
Node* node = block->at(indexInBlock);
#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
if (needsNewLine)
dataLogF("\n");
dataLogF(" @%u:", node->index());
needsNewLine = true;
#endif
if (!node->shouldGenerate())
continue;
switch (node->op()) {
case Phi:
case Flush:
case PhantomLocal:
continue;
case GetLocal:
ASSERT(!node->child1()->hasResult());
break;
default:
break;
}
// First, call use on all of the current node's children, then
// allocate a VirtualRegister for this node. We do so in this
// order so that if a child is on its last use, and a
// VirtualRegister is freed, then it may be reused for node.
if (node->flags() & NodeHasVarArgs) {
for (unsigned childIdx = node->firstChild(); childIdx < node->firstChild() + node->numChildren(); childIdx++)
scoreBoard.useIfHasResult(m_graph.m_varArgChildren[childIdx]);
} else {
scoreBoard.useIfHasResult(node->child1());
scoreBoard.useIfHasResult(node->child2());
scoreBoard.useIfHasResult(node->child3());
}
if (!node->hasResult())
continue;
VirtualRegister virtualRegister = scoreBoard.allocate();
#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
dataLogF(
" Assigning virtual register %u to node %u.",
virtualRegister, node->index());
#endif
node->setVirtualRegister(virtualRegister);
// 'mustGenerate' nodes have their useCount artificially elevated,
// call use now to account for this.
if (node->mustGenerate())
scoreBoard.use(node);
}
scoreBoard.assertClear();
}
#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
if (needsNewLine)
dataLogF("\n");
#endif
// 'm_numCalleeRegisters' is the number of locals and temporaries allocated
// for the function (and checked for on entry). Since we perform a new and
// different allocation of temporaries, more registers may now be required.
unsigned calleeRegisters = scoreBoard.highWatermark() + m_graph.m_parameterSlots;
size_t inlineCallFrameCount = codeBlock()->inlineCallFrames().size();
for (size_t i = 0; i < inlineCallFrameCount; i++) {
InlineCallFrame& inlineCallFrame = codeBlock()->inlineCallFrames()[i];
CodeBlock* codeBlock = baselineCodeBlockForInlineCallFrame(&inlineCallFrame);
unsigned requiredCalleeRegisters = inlineCallFrame.stackOffset + codeBlock->m_numCalleeRegisters;
if (requiredCalleeRegisters > calleeRegisters)
calleeRegisters = requiredCalleeRegisters;
}
if ((unsigned)codeBlock()->m_numCalleeRegisters < calleeRegisters)
codeBlock()->m_numCalleeRegisters = calleeRegisters;
#if DFG_ENABLE(DEBUG_VERBOSE)
dataLogF("Num callee registers: %u\n", calleeRegisters);
#endif
return true;
}
};
bool performVirtualRegisterAllocation(Graph& graph)
{
SamplingRegion samplingRegion("DFG Virtual Register Allocation Phase");
return runPhase<VirtualRegisterAllocationPhase>(graph);
}
} } // namespace JSC::DFG
#endif // ENABLE(DFG_JIT)
| bsd-3-clause |
jorik041/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/PlatformSpeechSynthesisVoice.cpp | 119 | 2373 | /*
* Copyright (C) 2013 Apple Computer, Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "PlatformSpeechSynthesisVoice.h"
#if ENABLE(SPEECH_SYNTHESIS)
namespace WebCore {
PassRefPtr<PlatformSpeechSynthesisVoice> PlatformSpeechSynthesisVoice::create(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault)
{
return adoptRef(new PlatformSpeechSynthesisVoice(voiceURI, name, lang, localService, isDefault));
}
PassRefPtr<PlatformSpeechSynthesisVoice> PlatformSpeechSynthesisVoice::create()
{
return adoptRef(new PlatformSpeechSynthesisVoice());
}
PlatformSpeechSynthesisVoice::PlatformSpeechSynthesisVoice(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault)
: m_voiceURI(voiceURI)
, m_name(name)
, m_lang(lang)
, m_localService(localService)
, m_default(isDefault)
{
}
PlatformSpeechSynthesisVoice::PlatformSpeechSynthesisVoice()
: m_localService(false)
, m_default(false)
{
}
} // namespace WebCore
#endif // ENABLE(SPEECH_SYNTHESIS)
| bsd-3-clause |
mapbased/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/LinkHash.cpp | 123 | 10607 | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "KURL.h"
#include "LinkHash.h"
#include <wtf/text/AtomicString.h>
#include <wtf/text/StringHash.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
template <typename CharacterType>
static inline size_t findSlashDotDotSlash(const CharacterType* characters, size_t length, size_t position)
{
if (length < 4)
return notFound;
size_t loopLimit = length - 3;
for (size_t i = position; i < loopLimit; ++i) {
if (characters[i] == '/' && characters[i + 1] == '.' && characters[i + 2] == '.' && characters[i + 3] == '/')
return i;
}
return notFound;
}
template <typename CharacterType>
static inline size_t findSlashSlash(const CharacterType* characters, size_t length, size_t position)
{
if (length < 2)
return notFound;
size_t loopLimit = length - 1;
for (size_t i = position; i < loopLimit; ++i) {
if (characters[i] == '/' && characters[i + 1] == '/')
return i;
}
return notFound;
}
template <typename CharacterType>
static inline size_t findSlashDotSlash(const CharacterType* characters, size_t length, size_t position)
{
if (length < 3)
return notFound;
size_t loopLimit = length - 2;
for (size_t i = position; i < loopLimit; ++i) {
if (characters[i] == '/' && characters[i + 1] == '.' && characters[i + 2] == '/')
return i;
}
return notFound;
}
template <typename CharacterType>
static inline bool containsColonSlashSlash(const CharacterType* characters, unsigned length)
{
if (length < 3)
return false;
unsigned loopLimit = length - 2;
for (unsigned i = 0; i < loopLimit; ++i) {
if (characters[i] == ':' && characters[i + 1] == '/' && characters[i + 2] == '/')
return true;
}
return false;
}
template <typename CharacterType>
static inline void squeezeOutNullCharacters(Vector<CharacterType, 512>& string)
{
size_t size = string.size();
size_t i = 0;
for (i = 0; i < size; ++i) {
if (!string[i])
break;
}
if (i == size)
return;
size_t j = i;
for (++i; i < size; ++i) {
if (CharacterType character = string[i])
string[j++] = character;
}
ASSERT(j < size);
string.shrink(j);
}
template <typename CharacterType>
static void cleanSlashDotDotSlashes(Vector<CharacterType, 512>& path, size_t firstSlash)
{
size_t slash = firstSlash;
do {
size_t previousSlash = slash ? reverseFind(path.data(), path.size(), '/', slash - 1) : notFound;
// Don't remove the host, i.e. http://foo.org/../foo.html
if (previousSlash == notFound || (previousSlash > 3 && path[previousSlash - 2] == ':' && path[previousSlash - 1] == '/')) {
path[slash] = 0;
path[slash + 1] = 0;
path[slash + 2] = 0;
} else {
for (size_t i = previousSlash; i < slash + 3; ++i)
path[i] = 0;
}
slash += 3;
} while ((slash = findSlashDotDotSlash(path.data(), path.size(), slash)) != notFound);
squeezeOutNullCharacters(path);
}
template <typename CharacterType>
static void mergeDoubleSlashes(Vector<CharacterType, 512>& path, size_t firstSlash)
{
size_t refPos = find(path.data(), path.size(), '#');
if (!refPos || refPos == notFound)
refPos = path.size();
size_t slash = firstSlash;
while (slash < refPos) {
if (!slash || path[slash - 1] != ':')
path[slash++] = 0;
else
slash += 2;
if ((slash = findSlashSlash(path.data(), path.size(), slash)) == notFound)
break;
}
squeezeOutNullCharacters(path);
}
template <typename CharacterType>
static void cleanSlashDotSlashes(Vector<CharacterType, 512>& path, size_t firstSlash)
{
size_t slash = firstSlash;
do {
path[slash] = 0;
path[slash + 1] = 0;
slash += 2;
} while ((slash = findSlashDotSlash(path.data(), path.size(), slash)) != notFound);
squeezeOutNullCharacters(path);
}
template <typename CharacterType>
static inline void cleanPath(Vector<CharacterType, 512>& path)
{
// FIXME: Should not do this in the query or anchor part of the URL.
size_t firstSlash = findSlashDotDotSlash(path.data(), path.size(), 0);
if (firstSlash != notFound)
cleanSlashDotDotSlashes(path, firstSlash);
// FIXME: Should not do this in the query part.
firstSlash = findSlashSlash(path.data(), path.size(), 0);
if (firstSlash != notFound)
mergeDoubleSlashes(path, firstSlash);
// FIXME: Should not do this in the query or anchor part.
firstSlash = findSlashDotSlash(path.data(), path.size(), 0);
if (firstSlash != notFound)
cleanSlashDotSlashes(path, firstSlash);
}
template <typename CharacterType>
static inline bool matchLetter(CharacterType c, char lowercaseLetter)
{
return (c | 0x20) == lowercaseLetter;
}
template <typename CharacterType>
static inline bool needsTrailingSlash(const CharacterType* characters, unsigned length)
{
if (length < 6)
return false;
if (!matchLetter(characters[0], 'h')
|| !matchLetter(characters[1], 't')
|| !matchLetter(characters[2], 't')
|| !matchLetter(characters[3], 'p'))
return false;
if (!(characters[4] == ':'
|| (matchLetter(characters[4], 's') && characters[5] == ':')))
return false;
unsigned pos = characters[4] == ':' ? 5 : 6;
// Skip initial two slashes if present.
if (pos + 1 < length && characters[pos] == '/' && characters[pos + 1] == '/')
pos += 2;
// Find next slash.
while (pos < length && characters[pos] != '/')
++pos;
return pos == length;
}
template <typename CharacterType>
static ALWAYS_INLINE LinkHash visitedLinkHashInline(const CharacterType* url, unsigned length)
{
return AlreadyHashed::avoidDeletedValue(StringHasher::computeHash(url, length));
}
LinkHash visitedLinkHash(const String& url)
{
unsigned length = url.length();
if (length && url.is8Bit())
return visitedLinkHashInline(url.characters8(), length);
return visitedLinkHashInline(url.characters(), length);
}
LinkHash visitedLinkHash(const UChar* url, unsigned length)
{
return visitedLinkHashInline(url, length);
}
template <typename CharacterType>
static ALWAYS_INLINE void visitedURLInline(const KURL& base, const CharacterType* characters, unsigned length, Vector<CharacterType, 512>& buffer)
{
if (!length)
return;
// This is a poor man's completeURL. Faster with less memory allocation.
// FIXME: It's missing a lot of what completeURL does and a lot of what KURL does.
// For example, it does not handle international domain names properly.
// FIXME: It is wrong that we do not do further processing on strings that have "://" in them:
// 1) The "://" could be in the query or anchor.
// 2) The URL's path could have a "/./" or a "/../" or a "//" sequence in it.
// FIXME: needsTrailingSlash does not properly return true for a URL that has no path, but does
// have a query or anchor.
bool hasColonSlashSlash = containsColonSlashSlash(characters, length);
if (hasColonSlashSlash && !needsTrailingSlash(characters, length)) {
buffer.append(characters, length);
return;
}
if (hasColonSlashSlash) {
// FIXME: This is incorrect for URLs that have a query or anchor; the "/" needs to go at the
// end of the path, *before* the query or anchor.
buffer.append(characters, length);
buffer.append('/');
return;
}
if (!length)
buffer.append(base.string().getCharactersWithUpconvert<CharacterType>(), base.string().length());
else {
switch (characters[0]) {
case '/':
buffer.append(base.string().getCharactersWithUpconvert<CharacterType>(), base.pathStart());
break;
case '#':
buffer.append(base.string().getCharactersWithUpconvert<CharacterType>(), base.pathEnd());
break;
default:
buffer.append(base.string().getCharactersWithUpconvert<CharacterType>(), base.pathAfterLastSlash());
break;
}
}
buffer.append(characters, length);
cleanPath(buffer);
if (needsTrailingSlash(buffer.data(), buffer.size())) {
// FIXME: This is incorrect for URLs that have a query or anchor; the "/" needs to go at the
// end of the path, *before* the query or anchor.
buffer.append('/');
}
return;
}
void visitedURL(const KURL& base, const AtomicString& attributeURL, Vector<UChar, 512>& buffer)
{
return visitedURLInline(base, attributeURL.characters(), attributeURL.length(), buffer);
}
LinkHash visitedLinkHash(const KURL& base, const AtomicString& attributeURL)
{
if (attributeURL.isEmpty())
return 0;
if (!base.string().isEmpty() && base.string().is8Bit() && attributeURL.is8Bit()) {
Vector<LChar, 512> url;
visitedURLInline(base, attributeURL.characters8(), attributeURL.length(), url);
if (url.isEmpty())
return 0;
return visitedLinkHashInline(url.data(), url.size());
}
Vector<UChar, 512> url;
visitedURLInline(base, attributeURL.characters(), attributeURL.length(), url);
if (url.isEmpty())
return 0;
return visitedLinkHashInline(url.data(), url.size());
}
} // namespace WebCore
| bsd-3-clause |
sharma1nitish/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/network/blackberry/ResourceErrorBlackBerry.cpp | 123 | 1050 | /*
* Copyright (C) 2010 Research In Motion Limited. All rights reserved.
*
* 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 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include "ResourceError.h"
namespace WebCore {
const char* const ResourceError::httpErrorDomain = "HTTP";
const char* const ResourceError::platformErrorDomain = "BlackBerryPlatform";
} // namespace WebCore
| bsd-3-clause |
chauhanmohit/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/JSInjectedScriptManager.cpp | 124 | 3917 | /*
* Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
* Copyright (C) 2012 Google Inc. 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.
* * Neither the name of Google Inc. 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 "config.h"
#if ENABLE(INSPECTOR)
#include "InjectedScriptManager.h"
#include "BindingSecurity.h"
#include "ExceptionCode.h"
#include "JSDOMWindow.h"
#include "JSDOMWindowCustom.h"
#include "JSInjectedScriptHost.h"
#include "JSMainThreadExecState.h"
#include "ScriptObject.h"
#include <parser/SourceCode.h>
#include <runtime/JSLock.h>
using namespace JSC;
namespace WebCore {
ScriptObject InjectedScriptManager::createInjectedScript(const String& source, ScriptState* scriptState, int id)
{
JSLockHolder lock(scriptState);
SourceCode sourceCode = makeSource(source);
JSDOMGlobalObject* globalObject = jsCast<JSDOMGlobalObject*>(scriptState->lexicalGlobalObject());
JSValue globalThisValue = scriptState->globalThisValue();
JSValue evaluationException;
JSValue evaluationReturnValue;
if (isMainThread())
evaluationReturnValue = JSMainThreadExecState::evaluate(scriptState, sourceCode, globalThisValue, &evaluationException);
else {
JSC::JSLockHolder lock(scriptState);
evaluationReturnValue = JSC::evaluate(scriptState, sourceCode, globalThisValue, &evaluationException);
}
if (evaluationException)
return ScriptObject();
JSValue functionValue = evaluationReturnValue;
CallData callData;
CallType callType = getCallData(functionValue, callData);
if (callType == CallTypeNone)
return ScriptObject();
MarkedArgumentBuffer args;
args.append(toJS(scriptState, globalObject, m_injectedScriptHost.get()));
args.append(globalThisValue);
args.append(jsNumber(id));
JSValue result = JSC::call(scriptState, functionValue, callType, callData, globalThisValue, args);
if (result.isObject())
return ScriptObject(scriptState, result.getObject());
return ScriptObject();
}
bool InjectedScriptManager::canAccessInspectedWindow(ScriptState* scriptState)
{
JSLockHolder lock(scriptState);
JSDOMWindow* inspectedWindow = toJSDOMWindow(scriptState->lexicalGlobalObject());
if (!inspectedWindow)
return false;
return BindingSecurity::shouldAllowAccessToDOMWindow(scriptState, inspectedWindow->impl(), DoNotReportSecurityError);
}
} // namespace WebCore
#endif // ENABLE(INSPECTOR)
| bsd-3-clause |
lattwood/phantomjs | src/qt/qtwebkit/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest_Bundle.cpp | 127 | 2611 | /*
* Copyright (C) 2011 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. 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.
*/
#include "config.h"
#include "InjectedBundleTest.h"
#include "PlatformUtilities.h"
#include <WebKit2/WKBundlePage.h>
namespace TestWebKitAPI {
class CanHandleRequestTest : public InjectedBundleTest {
public:
CanHandleRequestTest(const std::string& identifier);
private:
virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody);
};
static InjectedBundleTest::Register<CanHandleRequestTest> registrar("CanHandleRequestTest");
CanHandleRequestTest::CanHandleRequestTest(const std::string& identifier)
: InjectedBundleTest(identifier)
{
}
static bool canHandleURL(const char* url)
{
return WKBundlePageCanHandleRequest(adoptWK(WKURLRequestCreateWithWKURL(adoptWK(WKURLCreateWithUTF8CString(url)).get())).get());
}
static bool runTest()
{
return canHandleURL("about:blank") && canHandleURL("emptyscheme://") && !canHandleURL("notascheme://");
}
void CanHandleRequestTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef)
{
if (!WKStringIsEqualToUTF8CString(messageName, "CheckCanHandleRequest"))
return;
WKBundlePostMessage(bundle, Util::toWK("DidCheckCanHandleRequest").get(), adoptWK(WKBooleanCreate(runTest())).get());
}
} // namespace TestWebKitAPI
| bsd-3-clause |
AlbandeCrevoisier/ldd-athens | linux-socfpga/drivers/media/usb/stk1160/stk1160-v4l.c | 130 | 21322 | /*
* STK1160 driver
*
* Copyright (C) 2012 Ezequiel Garcia
* <elezegarcia--a.t--gmail.com>
*
* Based on Easycap driver by R.M. Thomas
* Copyright (C) 2010 R.M. Thomas
* <rmthomas--a.t--sciolus.org>
*
* This program 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 2 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.
*
*/
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <media/videobuf2-vmalloc.h>
#include <media/i2c/saa7115.h>
#include "stk1160.h"
#include "stk1160-reg.h"
static bool keep_buffers;
module_param(keep_buffers, bool, 0644);
MODULE_PARM_DESC(keep_buffers, "don't release buffers upon stop streaming");
enum stk1160_decimate_mode {
STK1160_DECIMATE_MORE_THAN_HALF,
STK1160_DECIMATE_LESS_THAN_HALF,
};
struct stk1160_decimate_ctrl {
bool col_en, row_en;
enum stk1160_decimate_mode col_mode, row_mode;
unsigned int col_n, row_n;
};
/* supported video standards */
static struct stk1160_fmt format[] = {
{
.name = "16 bpp YUY2, 4:2:2, packed",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = 16,
}
};
/*
* Helper to find the next divisor that results in modulo being zero.
* This is required to guarantee valid decimation unit counts.
*/
static unsigned int
div_round_integer(unsigned int x, unsigned int y)
{
for (;; y++) {
if (x % y == 0)
return x / y;
}
}
static void stk1160_set_std(struct stk1160 *dev)
{
int i;
static struct regval std525[] = {
/* 720x480 */
/* Frame start */
{STK116_CFSPO_STX_L, 0x0000},
{STK116_CFSPO_STX_H, 0x0000},
{STK116_CFSPO_STY_L, 0x0003},
{STK116_CFSPO_STY_H, 0x0000},
/* Frame end */
{STK116_CFEPO_ENX_L, 0x05a0},
{STK116_CFEPO_ENX_H, 0x0005},
{STK116_CFEPO_ENY_L, 0x00f3},
{STK116_CFEPO_ENY_H, 0x0000},
{0xffff, 0xffff}
};
static struct regval std625[] = {
/* 720x576 */
/* TODO: Each line of frame has some junk at the end */
/* Frame start */
{STK116_CFSPO, 0x0000},
{STK116_CFSPO+1, 0x0000},
{STK116_CFSPO+2, 0x0001},
{STK116_CFSPO+3, 0x0000},
/* Frame end */
{STK116_CFEPO, 0x05a0},
{STK116_CFEPO+1, 0x0005},
{STK116_CFEPO+2, 0x0121},
{STK116_CFEPO+3, 0x0001},
{0xffff, 0xffff}
};
if (dev->norm & V4L2_STD_525_60) {
stk1160_dbg("registers to NTSC like standard\n");
for (i = 0; std525[i].reg != 0xffff; i++)
stk1160_write_reg(dev, std525[i].reg, std525[i].val);
} else {
stk1160_dbg("registers to PAL like standard\n");
for (i = 0; std625[i].reg != 0xffff; i++)
stk1160_write_reg(dev, std625[i].reg, std625[i].val);
}
}
static void stk1160_set_fmt(struct stk1160 *dev,
struct stk1160_decimate_ctrl *ctrl)
{
u32 val = 0;
if (ctrl) {
/*
* Since the format is UYVY, the device must skip or send
* a number of rows/columns multiple of four. This way, the
* colour format is preserved. The STK1160_DEC_UNIT_SIZE bit
* does exactly this.
*/
val |= STK1160_DEC_UNIT_SIZE;
val |= ctrl->col_en ? STK1160_H_DEC_EN : 0;
val |= ctrl->row_en ? STK1160_V_DEC_EN : 0;
val |= ctrl->col_mode ==
STK1160_DECIMATE_MORE_THAN_HALF ?
STK1160_H_DEC_MODE : 0;
val |= ctrl->row_mode ==
STK1160_DECIMATE_MORE_THAN_HALF ?
STK1160_V_DEC_MODE : 0;
/* Horizontal count units */
stk1160_write_reg(dev, STK1160_DMCTRL_H_UNITS, ctrl->col_n);
/* Vertical count units */
stk1160_write_reg(dev, STK1160_DMCTRL_V_UNITS, ctrl->row_n);
stk1160_dbg("decimate 0x%x, column units %d, row units %d\n",
val, ctrl->col_n, ctrl->row_n);
}
/* Decimation control */
stk1160_write_reg(dev, STK1160_DMCTRL, val);
}
/*
* Set a new alternate setting.
* Returns true is dev->max_pkt_size has changed, false otherwise.
*/
static bool stk1160_set_alternate(struct stk1160 *dev)
{
int i, prev_alt = dev->alt;
unsigned int min_pkt_size;
bool new_pkt_size;
/*
* If we don't set right alternate,
* then we will get a green screen with junk.
*/
min_pkt_size = STK1160_MIN_PKT_SIZE;
for (i = 0; i < dev->num_alt; i++) {
/* stop when the selected alt setting offers enough bandwidth */
if (dev->alt_max_pkt_size[i] >= min_pkt_size) {
dev->alt = i;
break;
/*
* otherwise make sure that we end up with the maximum bandwidth
* because the min_pkt_size equation might be wrong...
*/
} else if (dev->alt_max_pkt_size[i] >
dev->alt_max_pkt_size[dev->alt])
dev->alt = i;
}
stk1160_dbg("setting alternate %d\n", dev->alt);
if (dev->alt != prev_alt) {
stk1160_dbg("minimum isoc packet size: %u (alt=%d)\n",
min_pkt_size, dev->alt);
stk1160_dbg("setting alt %d with wMaxPacketSize=%u\n",
dev->alt, dev->alt_max_pkt_size[dev->alt]);
usb_set_interface(dev->udev, 0, dev->alt);
}
new_pkt_size = dev->max_pkt_size != dev->alt_max_pkt_size[dev->alt];
dev->max_pkt_size = dev->alt_max_pkt_size[dev->alt];
return new_pkt_size;
}
static int stk1160_start_streaming(struct stk1160 *dev)
{
bool new_pkt_size;
int rc = 0;
int i;
/* Check device presence */
if (!dev->udev)
return -ENODEV;
if (mutex_lock_interruptible(&dev->v4l_lock))
return -ERESTARTSYS;
/*
* For some reason it is mandatory to set alternate *first*
* and only *then* initialize isoc urbs.
* Someone please explain me why ;)
*/
new_pkt_size = stk1160_set_alternate(dev);
/*
* We (re)allocate isoc urbs if:
* there is no allocated isoc urbs, OR
* a new dev->max_pkt_size is detected
*/
if (!dev->isoc_ctl.num_bufs || new_pkt_size) {
rc = stk1160_alloc_isoc(dev);
if (rc < 0)
goto out_stop_hw;
}
/* submit urbs and enables IRQ */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_KERNEL);
if (rc) {
stk1160_err("cannot submit urb[%d] (%d)\n", i, rc);
goto out_uninit;
}
}
/* Start saa711x */
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
dev->sequence = 0;
/* Start stk1160 */
stk1160_write_reg(dev, STK1160_DCTRL, 0xb3);
stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
stk1160_dbg("streaming started\n");
mutex_unlock(&dev->v4l_lock);
return 0;
out_uninit:
stk1160_uninit_isoc(dev);
out_stop_hw:
usb_set_interface(dev->udev, 0, 0);
stk1160_clear_queue(dev);
mutex_unlock(&dev->v4l_lock);
return rc;
}
/* Must be called with v4l_lock hold */
static void stk1160_stop_hw(struct stk1160 *dev)
{
/* If the device is not physically present, there is nothing to do */
if (!dev->udev)
return;
/* set alternate 0 */
dev->alt = 0;
stk1160_dbg("setting alternate %d\n", dev->alt);
usb_set_interface(dev->udev, 0, 0);
/* Stop stk1160 */
stk1160_write_reg(dev, STK1160_DCTRL, 0x00);
stk1160_write_reg(dev, STK1160_DCTRL+3, 0x00);
/* Stop saa711x */
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
}
static int stk1160_stop_streaming(struct stk1160 *dev)
{
if (mutex_lock_interruptible(&dev->v4l_lock))
return -ERESTARTSYS;
/*
* Once URBs are cancelled, the URB complete handler
* won't be running. This is required to safely release the
* current buffer (dev->isoc_ctl.buf).
*/
stk1160_cancel_isoc(dev);
/*
* It is possible to keep buffers around using a module parameter.
* This is intended to avoid memory fragmentation.
*/
if (!keep_buffers)
stk1160_free_isoc(dev);
stk1160_stop_hw(dev);
stk1160_clear_queue(dev);
stk1160_dbg("streaming stopped\n");
mutex_unlock(&dev->v4l_lock);
return 0;
}
static struct v4l2_file_operations stk1160_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.poll = vb2_fop_poll,
.mmap = vb2_fop_mmap,
.unlocked_ioctl = video_ioctl2,
};
/*
* vidioc ioctls
*/
static int vidioc_querycap(struct file *file,
void *priv, struct v4l2_capability *cap)
{
struct stk1160 *dev = video_drvdata(file);
strcpy(cap->driver, "stk1160");
strcpy(cap->card, "stk1160");
usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
cap->device_caps =
V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_STREAMING |
V4L2_CAP_READWRITE;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index != 0)
return -EINVAL;
strlcpy(f->description, format[f->index].name, sizeof(f->description));
f->pixelformat = format[f->index].fourcc;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
f->fmt.pix.pixelformat = dev->fmt->fourcc;
f->fmt.pix.bytesperline = dev->width * 2;
f->fmt.pix.sizeimage = dev->height * f->fmt.pix.bytesperline;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int stk1160_try_fmt(struct stk1160 *dev, struct v4l2_format *f,
struct stk1160_decimate_ctrl *ctrl)
{
unsigned int width, height;
unsigned int base_width, base_height;
unsigned int col_n, row_n;
enum stk1160_decimate_mode col_mode, row_mode;
bool col_en, row_en;
base_width = 720;
base_height = (dev->norm & V4L2_STD_525_60) ? 480 : 576;
/* Minimum width and height is 5% the frame size */
width = clamp_t(unsigned int, f->fmt.pix.width,
base_width / 20, base_width);
height = clamp_t(unsigned int, f->fmt.pix.height,
base_height / 20, base_height);
/* Let's set default no decimation values */
col_n = 0;
row_n = 0;
col_en = false;
row_en = false;
f->fmt.pix.width = base_width;
f->fmt.pix.height = base_height;
row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
if (width < base_width && width > base_width / 2) {
/*
* The device will send count units for each
* unit skipped. This means count unit is:
*
* n = width / (frame width - width)
*
* And the width is:
*
* width = (n / n + 1) * frame width
*/
col_n = div_round_integer(width, base_width - width);
if (col_n > 0 && col_n <= 255) {
col_en = true;
col_mode = STK1160_DECIMATE_LESS_THAN_HALF;
f->fmt.pix.width = (base_width * col_n) / (col_n + 1);
}
} else if (width <= base_width / 2) {
/*
* The device will skip count units for each
* unit sent. This means count is:
*
* n = (frame width / width) - 1
*
* And the width is:
*
* width = frame width / (n + 1)
*/
col_n = div_round_integer(base_width, width) - 1;
if (col_n > 0 && col_n <= 255) {
col_en = true;
col_mode = STK1160_DECIMATE_MORE_THAN_HALF;
f->fmt.pix.width = base_width / (col_n + 1);
}
}
if (height < base_height && height > base_height / 2) {
row_n = div_round_integer(height, base_height - height);
if (row_n > 0 && row_n <= 255) {
row_en = true;
row_mode = STK1160_DECIMATE_LESS_THAN_HALF;
f->fmt.pix.height = (base_height * row_n) / (row_n + 1);
}
} else if (height <= base_height / 2) {
row_n = div_round_integer(base_height, height) - 1;
if (row_n > 0 && row_n <= 255) {
row_en = true;
row_mode = STK1160_DECIMATE_MORE_THAN_HALF;
f->fmt.pix.height = base_height / (row_n + 1);
}
}
f->fmt.pix.pixelformat = dev->fmt->fourcc;
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
f->fmt.pix.bytesperline = f->fmt.pix.width * 2;
f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
if (ctrl) {
ctrl->col_en = col_en;
ctrl->col_n = col_n;
ctrl->col_mode = col_mode;
ctrl->row_en = row_en;
ctrl->row_n = row_n;
ctrl->row_mode = row_mode;
}
stk1160_dbg("width %d, height %d\n",
f->fmt.pix.width, f->fmt.pix.height);
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
return stk1160_try_fmt(dev, f, NULL);
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct stk1160 *dev = video_drvdata(file);
struct vb2_queue *q = &dev->vb_vidq;
struct stk1160_decimate_ctrl ctrl;
int rc;
if (vb2_is_busy(q))
return -EBUSY;
rc = stk1160_try_fmt(dev, f, &ctrl);
if (rc < 0)
return rc;
dev->width = f->fmt.pix.width;
dev->height = f->fmt.pix.height;
stk1160_set_fmt(dev, &ctrl);
return 0;
}
static int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *norm)
{
struct stk1160 *dev = video_drvdata(file);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, querystd, norm);
return 0;
}
static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
{
struct stk1160 *dev = video_drvdata(file);
*norm = dev->norm;
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
{
struct stk1160 *dev = video_drvdata(file);
struct vb2_queue *q = &dev->vb_vidq;
if (dev->norm == norm)
return 0;
if (vb2_is_busy(q))
return -EBUSY;
/* Check device presence */
if (!dev->udev)
return -ENODEV;
/* We need to set this now, before we call stk1160_set_std */
dev->width = 720;
dev->height = (norm & V4L2_STD_525_60) ? 480 : 576;
dev->norm = norm;
stk1160_set_std(dev);
/* Calling with NULL disables frame decimation */
stk1160_set_fmt(dev, NULL);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
dev->norm);
return 0;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct stk1160 *dev = video_drvdata(file);
if (i->index > STK1160_MAX_INPUT)
return -EINVAL;
/* S-Video special handling */
if (i->index == STK1160_SVIDEO_INPUT)
sprintf(i->name, "S-Video");
else
sprintf(i->name, "Composite%d", i->index);
i->type = V4L2_INPUT_TYPE_CAMERA;
i->std = dev->vdev.tvnorms;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct stk1160 *dev = video_drvdata(file);
*i = dev->ctl_input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct stk1160 *dev = video_drvdata(file);
if (i > STK1160_MAX_INPUT)
return -EINVAL;
dev->ctl_input = i;
stk1160_select_input(dev);
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int vidioc_g_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct stk1160 *dev = video_drvdata(file);
int rc;
u8 val;
/* Match host */
rc = stk1160_read_reg(dev, reg->reg, &val);
reg->val = val;
reg->size = 1;
return rc;
}
static int vidioc_s_register(struct file *file, void *priv,
const struct v4l2_dbg_register *reg)
{
struct stk1160 *dev = video_drvdata(file);
/* Match host */
return stk1160_write_reg(dev, reg->reg, reg->val);
}
#endif
static const struct v4l2_ioctl_ops stk1160_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_querystd = vidioc_querystd,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
/* vb2 takes care of these */
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_expbuf = vb2_ioctl_expbuf,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = vidioc_g_register,
.vidioc_s_register = vidioc_s_register,
#endif
};
/********************************************************************/
/*
* Videobuf2 operations
*/
static int queue_setup(struct vb2_queue *vq,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
unsigned long size;
size = dev->width * dev->height * 2;
/*
* Here we can change the number of buffers being requested.
* So, we set a minimum and a maximum like this:
*/
*nbuffers = clamp_t(unsigned int, *nbuffers,
STK1160_MIN_VIDEO_BUFFERS, STK1160_MAX_VIDEO_BUFFERS);
/* This means a packed colorformat */
*nplanes = 1;
sizes[0] = size;
stk1160_dbg("%s: buffer count %d, each %ld bytes\n",
__func__, *nbuffers, size);
return 0;
}
static void buffer_queue(struct vb2_buffer *vb)
{
unsigned long flags;
struct stk1160 *dev = vb2_get_drv_priv(vb->vb2_queue);
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct stk1160_buffer *buf =
container_of(vbuf, struct stk1160_buffer, vb);
spin_lock_irqsave(&dev->buf_lock, flags);
if (!dev->udev) {
/*
* If the device is disconnected return the buffer to userspace
* directly. The next QBUF call will fail with -ENODEV.
*/
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
} else {
buf->mem = vb2_plane_vaddr(vb, 0);
buf->length = vb2_plane_size(vb, 0);
buf->bytesused = 0;
buf->pos = 0;
/*
* If buffer length is less from expected then we return
* the buffer to userspace directly.
*/
if (buf->length < dev->width * dev->height * 2)
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
else
list_add_tail(&buf->list, &dev->avail_bufs);
}
spin_unlock_irqrestore(&dev->buf_lock, flags);
}
static int start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
return stk1160_start_streaming(dev);
}
/* abort streaming and wait for last buffer */
static void stop_streaming(struct vb2_queue *vq)
{
struct stk1160 *dev = vb2_get_drv_priv(vq);
stk1160_stop_streaming(dev);
}
static struct vb2_ops stk1160_video_qops = {
.queue_setup = queue_setup,
.buf_queue = buffer_queue,
.start_streaming = start_streaming,
.stop_streaming = stop_streaming,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
};
static struct video_device v4l_template = {
.name = "stk1160",
.tvnorms = V4L2_STD_525_60 | V4L2_STD_625_50,
.fops = &stk1160_fops,
.ioctl_ops = &stk1160_ioctl_ops,
.release = video_device_release_empty,
};
/********************************************************************/
/* Must be called with both v4l_lock and vb_queue_lock hold */
void stk1160_clear_queue(struct stk1160 *dev)
{
struct stk1160_buffer *buf;
unsigned long flags;
/* Release all active buffers */
spin_lock_irqsave(&dev->buf_lock, flags);
while (!list_empty(&dev->avail_bufs)) {
buf = list_first_entry(&dev->avail_bufs,
struct stk1160_buffer, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
stk1160_dbg("buffer [%p/%d] aborted\n",
buf, buf->vb.vb2_buf.index);
}
/* It's important to release the current buffer */
if (dev->isoc_ctl.buf) {
buf = dev->isoc_ctl.buf;
dev->isoc_ctl.buf = NULL;
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
stk1160_dbg("buffer [%p/%d] aborted\n",
buf, buf->vb.vb2_buf.index);
}
spin_unlock_irqrestore(&dev->buf_lock, flags);
}
int stk1160_vb2_setup(struct stk1160 *dev)
{
int rc;
struct vb2_queue *q;
q = &dev->vb_vidq;
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct stk1160_buffer);
q->ops = &stk1160_video_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
rc = vb2_queue_init(q);
if (rc < 0)
return rc;
/* initialize video dma queue */
INIT_LIST_HEAD(&dev->avail_bufs);
return 0;
}
int stk1160_video_register(struct stk1160 *dev)
{
int rc;
/* Initialize video_device with a template structure */
dev->vdev = v4l_template;
dev->vdev.queue = &dev->vb_vidq;
/*
* Provide mutexes for v4l2 core and for videobuf2 queue.
* It will be used to protect *only* v4l2 ioctls.
*/
dev->vdev.lock = &dev->v4l_lock;
dev->vdev.queue->lock = &dev->vb_queue_lock;
/* This will be used to set video_device parent */
dev->vdev.v4l2_dev = &dev->v4l2_dev;
/* NTSC is default */
dev->norm = V4L2_STD_NTSC_M;
dev->width = 720;
dev->height = 480;
/* set default format */
dev->fmt = &format[0];
stk1160_set_std(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std,
dev->norm);
video_set_drvdata(&dev->vdev, dev);
rc = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
if (rc < 0) {
stk1160_err("video_register_device failed (%d)\n", rc);
return rc;
}
v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
video_device_node_name(&dev->vdev));
return 0;
}
| bsd-3-clause |
aospx-kitkat/platform_external_chromium_org | third_party/sqlite/src/ext/fts3/fts3_porter.c | 136 | 17321 | /*
** 2006 September 30
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Implementation of the full-text-search tokenizer that implements
** a Porter stemmer.
*/
/*
** The code in this file is only compiled if:
**
** * The FTS3 module is being built as an extension
** (in which case SQLITE_CORE is not defined), or
**
** * The FTS3 module is being built into the core of
** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
#include "fts3Int.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "fts3_tokenizer.h"
/*
** Class derived from sqlite3_tokenizer
*/
typedef struct porter_tokenizer {
sqlite3_tokenizer base; /* Base class */
} porter_tokenizer;
/*
** Class derived from sqlit3_tokenizer_cursor
*/
typedef struct porter_tokenizer_cursor {
sqlite3_tokenizer_cursor base;
const char *zInput; /* input we are tokenizing */
int nInput; /* size of the input */
int iOffset; /* current position in zInput */
int iToken; /* index of next token to be returned */
char *zToken; /* storage for current token */
int nAllocated; /* space allocated to zToken buffer */
} porter_tokenizer_cursor;
/*
** Create a new tokenizer instance.
*/
static int porterCreate(
int argc, const char * const *argv,
sqlite3_tokenizer **ppTokenizer
){
porter_tokenizer *t;
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
if( t==NULL ) return SQLITE_NOMEM;
memset(t, 0, sizeof(*t));
*ppTokenizer = &t->base;
return SQLITE_OK;
}
/*
** Destroy a tokenizer
*/
static int porterDestroy(sqlite3_tokenizer *pTokenizer){
sqlite3_free(pTokenizer);
return SQLITE_OK;
}
/*
** Prepare to begin tokenizing a particular string. The input
** string to be tokenized is zInput[0..nInput-1]. A cursor
** used to incrementally tokenize this string is returned in
** *ppCursor.
*/
static int porterOpen(
sqlite3_tokenizer *pTokenizer, /* The tokenizer */
const char *zInput, int nInput, /* String to be tokenized */
sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
){
porter_tokenizer_cursor *c;
UNUSED_PARAMETER(pTokenizer);
c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
if( c==NULL ) return SQLITE_NOMEM;
c->zInput = zInput;
if( zInput==0 ){
c->nInput = 0;
}else if( nInput<0 ){
c->nInput = (int)strlen(zInput);
}else{
c->nInput = nInput;
}
c->iOffset = 0; /* start tokenizing at the beginning */
c->iToken = 0;
c->zToken = NULL; /* no space allocated, yet. */
c->nAllocated = 0;
*ppCursor = &c->base;
return SQLITE_OK;
}
/*
** Close a tokenization cursor previously opened by a call to
** porterOpen() above.
*/
static int porterClose(sqlite3_tokenizer_cursor *pCursor){
porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
sqlite3_free(c->zToken);
sqlite3_free(c);
return SQLITE_OK;
}
/*
** Vowel or consonant
*/
static const char vOrCType[] = {
0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
1, 1, 1, 2, 1
};
/*
** isConsonant() and isVowel() determine if their first character in
** the string they point to is a consonant or a vowel, according
** to Porter ruls.
**
** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
** 'Y' is a consonant unless it follows another consonant,
** in which case it is a vowel.
**
** In these routine, the letters are in reverse order. So the 'y' rule
** is that 'y' is a consonant unless it is followed by another
** consonent.
*/
static int isVowel(const char*);
static int isConsonant(const char *z){
int j;
char x = *z;
if( x==0 ) return 0;
assert( x>='a' && x<='z' );
j = vOrCType[x-'a'];
if( j<2 ) return j;
return z[1]==0 || isVowel(z + 1);
}
static int isVowel(const char *z){
int j;
char x = *z;
if( x==0 ) return 0;
assert( x>='a' && x<='z' );
j = vOrCType[x-'a'];
if( j<2 ) return 1-j;
return isConsonant(z + 1);
}
/*
** Let any sequence of one or more vowels be represented by V and let
** C be sequence of one or more consonants. Then every word can be
** represented as:
**
** [C] (VC){m} [V]
**
** In prose: A word is an optional consonant followed by zero or
** vowel-consonant pairs followed by an optional vowel. "m" is the
** number of vowel consonant pairs. This routine computes the value
** of m for the first i bytes of a word.
**
** Return true if the m-value for z is 1 or more. In other words,
** return true if z contains at least one vowel that is followed
** by a consonant.
**
** In this routine z[] is in reverse order. So we are really looking
** for an instance of of a consonant followed by a vowel.
*/
static int m_gt_0(const char *z){
while( isVowel(z) ){ z++; }
if( *z==0 ) return 0;
while( isConsonant(z) ){ z++; }
return *z!=0;
}
/* Like mgt0 above except we are looking for a value of m which is
** exactly 1
*/
static int m_eq_1(const char *z){
while( isVowel(z) ){ z++; }
if( *z==0 ) return 0;
while( isConsonant(z) ){ z++; }
if( *z==0 ) return 0;
while( isVowel(z) ){ z++; }
if( *z==0 ) return 1;
while( isConsonant(z) ){ z++; }
return *z==0;
}
/* Like mgt0 above except we are looking for a value of m>1 instead
** or m>0
*/
static int m_gt_1(const char *z){
while( isVowel(z) ){ z++; }
if( *z==0 ) return 0;
while( isConsonant(z) ){ z++; }
if( *z==0 ) return 0;
while( isVowel(z) ){ z++; }
if( *z==0 ) return 0;
while( isConsonant(z) ){ z++; }
return *z!=0;
}
/*
** Return TRUE if there is a vowel anywhere within z[0..n-1]
*/
static int hasVowel(const char *z){
while( isConsonant(z) ){ z++; }
return *z!=0;
}
/*
** Return TRUE if the word ends in a double consonant.
**
** The text is reversed here. So we are really looking at
** the first two characters of z[].
*/
static int doubleConsonant(const char *z){
return isConsonant(z) && z[0]==z[1];
}
/*
** Return TRUE if the word ends with three letters which
** are consonant-vowel-consonent and where the final consonant
** is not 'w', 'x', or 'y'.
**
** The word is reversed here. So we are really checking the
** first three letters and the first one cannot be in [wxy].
*/
static int star_oh(const char *z){
return
isConsonant(z) &&
z[0]!='w' && z[0]!='x' && z[0]!='y' &&
isVowel(z+1) &&
isConsonant(z+2);
}
/*
** If the word ends with zFrom and xCond() is true for the stem
** of the word that preceeds the zFrom ending, then change the
** ending to zTo.
**
** The input word *pz and zFrom are both in reverse order. zTo
** is in normal order.
**
** Return TRUE if zFrom matches. Return FALSE if zFrom does not
** match. Not that TRUE is returned even if xCond() fails and
** no substitution occurs.
*/
static int stem(
char **pz, /* The word being stemmed (Reversed) */
const char *zFrom, /* If the ending matches this... (Reversed) */
const char *zTo, /* ... change the ending to this (not reversed) */
int (*xCond)(const char*) /* Condition that must be true */
){
char *z = *pz;
while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
if( *zFrom!=0 ) return 0;
if( xCond && !xCond(z) ) return 1;
while( *zTo ){
*(--z) = *(zTo++);
}
*pz = z;
return 1;
}
/*
** This is the fallback stemmer used when the porter stemmer is
** inappropriate. The input word is copied into the output with
** US-ASCII case folding. If the input word is too long (more
** than 20 bytes if it contains no digits or more than 6 bytes if
** it contains digits) then word is truncated to 20 or 6 bytes
** by taking 10 or 3 bytes from the beginning and end.
*/
static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
int i, mx, j;
int hasDigit = 0;
for(i=0; i<nIn; i++){
char c = zIn[i];
if( c>='A' && c<='Z' ){
zOut[i] = c - 'A' + 'a';
}else{
if( c>='0' && c<='9' ) hasDigit = 1;
zOut[i] = c;
}
}
mx = hasDigit ? 3 : 10;
if( nIn>mx*2 ){
for(j=mx, i=nIn-mx; i<nIn; i++, j++){
zOut[j] = zOut[i];
}
i = j;
}
zOut[i] = 0;
*pnOut = i;
}
/*
** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
** zOut is at least big enough to hold nIn bytes. Write the actual
** size of the output word (exclusive of the '\0' terminator) into *pnOut.
**
** Any upper-case characters in the US-ASCII character set ([A-Z])
** are converted to lower case. Upper-case UTF characters are
** unchanged.
**
** Words that are longer than about 20 bytes are stemmed by retaining
** a few bytes from the beginning and the end of the word. If the
** word contains digits, 3 bytes are taken from the beginning and
** 3 bytes from the end. For long words without digits, 10 bytes
** are taken from each end. US-ASCII case folding still applies.
**
** If the input word contains not digits but does characters not
** in [a-zA-Z] then no stemming is attempted and this routine just
** copies the input into the input into the output with US-ASCII
** case folding.
**
** Stemming never increases the length of the word. So there is
** no chance of overflowing the zOut buffer.
*/
static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
int i, j;
char zReverse[28];
char *z, *z2;
if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
/* The word is too big or too small for the porter stemmer.
** Fallback to the copy stemmer */
copy_stemmer(zIn, nIn, zOut, pnOut);
return;
}
for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
char c = zIn[i];
if( c>='A' && c<='Z' ){
zReverse[j] = c + 'a' - 'A';
}else if( c>='a' && c<='z' ){
zReverse[j] = c;
}else{
/* The use of a character not in [a-zA-Z] means that we fallback
** to the copy stemmer */
copy_stemmer(zIn, nIn, zOut, pnOut);
return;
}
}
memset(&zReverse[sizeof(zReverse)-5], 0, 5);
z = &zReverse[j+1];
/* Step 1a */
if( z[0]=='s' ){
if(
!stem(&z, "sess", "ss", 0) &&
!stem(&z, "sei", "i", 0) &&
!stem(&z, "ss", "ss", 0)
){
z++;
}
}
/* Step 1b */
z2 = z;
if( stem(&z, "dee", "ee", m_gt_0) ){
/* Do nothing. The work was all in the test */
}else if(
(stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
&& z!=z2
){
if( stem(&z, "ta", "ate", 0) ||
stem(&z, "lb", "ble", 0) ||
stem(&z, "zi", "ize", 0) ){
/* Do nothing. The work was all in the test */
}else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
z++;
}else if( m_eq_1(z) && star_oh(z) ){
*(--z) = 'e';
}
}
/* Step 1c */
if( z[0]=='y' && hasVowel(z+1) ){
z[0] = 'i';
}
/* Step 2 */
switch( z[1] ){
case 'a':
stem(&z, "lanoita", "ate", m_gt_0) ||
stem(&z, "lanoit", "tion", m_gt_0);
break;
case 'c':
stem(&z, "icne", "ence", m_gt_0) ||
stem(&z, "icna", "ance", m_gt_0);
break;
case 'e':
stem(&z, "rezi", "ize", m_gt_0);
break;
case 'g':
stem(&z, "igol", "log", m_gt_0);
break;
case 'l':
stem(&z, "ilb", "ble", m_gt_0) ||
stem(&z, "illa", "al", m_gt_0) ||
stem(&z, "iltne", "ent", m_gt_0) ||
stem(&z, "ile", "e", m_gt_0) ||
stem(&z, "ilsuo", "ous", m_gt_0);
break;
case 'o':
stem(&z, "noitazi", "ize", m_gt_0) ||
stem(&z, "noita", "ate", m_gt_0) ||
stem(&z, "rota", "ate", m_gt_0);
break;
case 's':
stem(&z, "msila", "al", m_gt_0) ||
stem(&z, "ssenevi", "ive", m_gt_0) ||
stem(&z, "ssenluf", "ful", m_gt_0) ||
stem(&z, "ssensuo", "ous", m_gt_0);
break;
case 't':
stem(&z, "itila", "al", m_gt_0) ||
stem(&z, "itivi", "ive", m_gt_0) ||
stem(&z, "itilib", "ble", m_gt_0);
break;
}
/* Step 3 */
switch( z[0] ){
case 'e':
stem(&z, "etaci", "ic", m_gt_0) ||
stem(&z, "evita", "", m_gt_0) ||
stem(&z, "ezila", "al", m_gt_0);
break;
case 'i':
stem(&z, "itici", "ic", m_gt_0);
break;
case 'l':
stem(&z, "laci", "ic", m_gt_0) ||
stem(&z, "luf", "", m_gt_0);
break;
case 's':
stem(&z, "ssen", "", m_gt_0);
break;
}
/* Step 4 */
switch( z[1] ){
case 'a':
if( z[0]=='l' && m_gt_1(z+2) ){
z += 2;
}
break;
case 'c':
if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
z += 4;
}
break;
case 'e':
if( z[0]=='r' && m_gt_1(z+2) ){
z += 2;
}
break;
case 'i':
if( z[0]=='c' && m_gt_1(z+2) ){
z += 2;
}
break;
case 'l':
if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
z += 4;
}
break;
case 'n':
if( z[0]=='t' ){
if( z[2]=='a' ){
if( m_gt_1(z+3) ){
z += 3;
}
}else if( z[2]=='e' ){
stem(&z, "tneme", "", m_gt_1) ||
stem(&z, "tnem", "", m_gt_1) ||
stem(&z, "tne", "", m_gt_1);
}
}
break;
case 'o':
if( z[0]=='u' ){
if( m_gt_1(z+2) ){
z += 2;
}
}else if( z[3]=='s' || z[3]=='t' ){
stem(&z, "noi", "", m_gt_1);
}
break;
case 's':
if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
z += 3;
}
break;
case 't':
stem(&z, "eta", "", m_gt_1) ||
stem(&z, "iti", "", m_gt_1);
break;
case 'u':
if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
z += 3;
}
break;
case 'v':
case 'z':
if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
z += 3;
}
break;
}
/* Step 5a */
if( z[0]=='e' ){
if( m_gt_1(z+1) ){
z++;
}else if( m_eq_1(z+1) && !star_oh(z+1) ){
z++;
}
}
/* Step 5b */
if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
z++;
}
/* z[] is now the stemmed word in reverse order. Flip it back
** around into forward order and return.
*/
*pnOut = i = (int)strlen(z);
zOut[i] = 0;
while( *z ){
zOut[--i] = *(z++);
}
}
/*
** Characters that can be part of a token. We assume any character
** whose value is greater than 0x80 (any UTF character) can be
** part of a token. In other words, delimiters all must have
** values of 0x7f or lower.
*/
static const char porterIdChar[] = {
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
};
#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
/*
** Extract the next token from a tokenization cursor. The cursor must
** have been opened by a prior call to porterOpen().
*/
static int porterNext(
sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
const char **pzToken, /* OUT: *pzToken is the token text */
int *pnBytes, /* OUT: Number of bytes in token */
int *piStartOffset, /* OUT: Starting offset of token */
int *piEndOffset, /* OUT: Ending offset of token */
int *piPosition /* OUT: Position integer of token */
){
porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
const char *z = c->zInput;
while( c->iOffset<c->nInput ){
int iStartOffset, ch;
/* Scan past delimiter characters */
while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
c->iOffset++;
}
/* Count non-delimiter characters. */
iStartOffset = c->iOffset;
while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
c->iOffset++;
}
if( c->iOffset>iStartOffset ){
int n = c->iOffset-iStartOffset;
if( n>c->nAllocated ){
char *pNew;
c->nAllocated = n+20;
pNew = sqlite3_realloc(c->zToken, c->nAllocated);
if( !pNew ) return SQLITE_NOMEM;
c->zToken = pNew;
}
porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
*pzToken = c->zToken;
*piStartOffset = iStartOffset;
*piEndOffset = c->iOffset;
*piPosition = c->iToken++;
return SQLITE_OK;
}
}
return SQLITE_DONE;
}
/*
** The set of routines that implement the porter-stemmer tokenizer
*/
static const sqlite3_tokenizer_module porterTokenizerModule = {
0,
porterCreate,
porterDestroy,
porterOpen,
porterClose,
porterNext,
};
/*
** Allocate a new porter tokenizer. Return a pointer to the new
** tokenizer in *ppModule
*/
void sqlite3Fts3PorterTokenizerModule(
sqlite3_tokenizer_module const**ppModule
){
*ppModule = &porterTokenizerModule;
}
#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
| bsd-3-clause |
VanirAOSP/external_chromium_org | third_party/sqlite/src/src/vtab.c | 140 | 29459 | /*
** 2006 June 10
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to help implement virtual tables.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
#include "sqliteInt.h"
/*
** The actual function that does the work of creating a new module.
** This function implements the sqlite3_create_module() and
** sqlite3_create_module_v2() interfaces.
*/
static int createModule(
sqlite3 *db, /* Database in which module is registered */
const char *zName, /* Name assigned to this module */
const sqlite3_module *pModule, /* The definition of the module */
void *pAux, /* Context pointer for xCreate/xConnect */
void (*xDestroy)(void *) /* Module destructor function */
){
int rc, nName;
Module *pMod;
sqlite3_mutex_enter(db->mutex);
nName = sqlite3Strlen30(zName);
pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
if( pMod ){
Module *pDel;
char *zCopy = (char *)(&pMod[1]);
memcpy(zCopy, zName, nName+1);
pMod->zName = zCopy;
pMod->pModule = pModule;
pMod->pAux = pAux;
pMod->xDestroy = xDestroy;
pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
if( pDel && pDel->xDestroy ){
pDel->xDestroy(pDel->pAux);
}
sqlite3DbFree(db, pDel);
if( pDel==pMod ){
db->mallocFailed = 1;
}
sqlite3ResetInternalSchema(db, -1);
}else if( xDestroy ){
xDestroy(pAux);
}
rc = sqlite3ApiExit(db, SQLITE_OK);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module(
sqlite3 *db, /* Database in which module is registered */
const char *zName, /* Name assigned to this module */
const sqlite3_module *pModule, /* The definition of the module */
void *pAux /* Context pointer for xCreate/xConnect */
){
return createModule(db, zName, pModule, pAux, 0);
}
/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module_v2(
sqlite3 *db, /* Database in which module is registered */
const char *zName, /* Name assigned to this module */
const sqlite3_module *pModule, /* The definition of the module */
void *pAux, /* Context pointer for xCreate/xConnect */
void (*xDestroy)(void *) /* Module destructor function */
){
return createModule(db, zName, pModule, pAux, xDestroy);
}
/*
** Lock the virtual table so that it cannot be disconnected.
** Locks nest. Every lock should have a corresponding unlock.
** If an unlock is omitted, resources leaks will occur.
**
** If a disconnect is attempted while a virtual table is locked,
** the disconnect is deferred until all locks have been removed.
*/
void sqlite3VtabLock(VTable *pVTab){
pVTab->nRef++;
}
/*
** pTab is a pointer to a Table structure representing a virtual-table.
** Return a pointer to the VTable object used by connection db to access
** this virtual-table, if one has been created, or NULL otherwise.
*/
VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
VTable *pVtab;
assert( IsVirtual(pTab) );
for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
return pVtab;
}
/*
** Decrement the ref-count on a virtual table object. When the ref-count
** reaches zero, call the xDisconnect() method to delete the object.
*/
void sqlite3VtabUnlock(VTable *pVTab){
sqlite3 *db = pVTab->db;
assert( db );
assert( pVTab->nRef>0 );
assert( sqlite3SafetyCheckOk(db) );
pVTab->nRef--;
if( pVTab->nRef==0 ){
sqlite3_vtab *p = pVTab->pVtab;
if( p ){
p->pModule->xDisconnect(p);
}
sqlite3DbFree(db, pVTab);
}
}
/*
** Table p is a virtual table. This function moves all elements in the
** p->pVTable list to the sqlite3.pDisconnect lists of their associated
** database connections to be disconnected at the next opportunity.
** Except, if argument db is not NULL, then the entry associated with
** connection db is left in the p->pVTable list.
*/
static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
VTable *pRet = 0;
VTable *pVTable = p->pVTable;
p->pVTable = 0;
/* Assert that the mutex (if any) associated with the BtShared database
** that contains table p is held by the caller. See header comments
** above function sqlite3VtabUnlockList() for an explanation of why
** this makes it safe to access the sqlite3.pDisconnect list of any
** database connection that may have an entry in the p->pVTable list.
*/
assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
while( pVTable ){
sqlite3 *db2 = pVTable->db;
VTable *pNext = pVTable->pNext;
assert( db2 );
if( db2==db ){
pRet = pVTable;
p->pVTable = pRet;
pRet->pNext = 0;
}else{
pVTable->pNext = db2->pDisconnect;
db2->pDisconnect = pVTable;
}
pVTable = pNext;
}
assert( !db || pRet );
return pRet;
}
/*
** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
**
** This function may only be called when the mutexes associated with all
** shared b-tree databases opened using connection db are held by the
** caller. This is done to protect the sqlite3.pDisconnect list. The
** sqlite3.pDisconnect list is accessed only as follows:
**
** 1) By this function. In this case, all BtShared mutexes and the mutex
** associated with the database handle itself must be held.
**
** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
** the sqlite3.pDisconnect list. In this case either the BtShared mutex
** associated with the database the virtual table is stored in is held
** or, if the virtual table is stored in a non-sharable database, then
** the database handle mutex is held.
**
** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
** by multiple threads. It is thread-safe.
*/
void sqlite3VtabUnlockList(sqlite3 *db){
VTable *p = db->pDisconnect;
db->pDisconnect = 0;
assert( sqlite3BtreeHoldsAllMutexes(db) );
assert( sqlite3_mutex_held(db->mutex) );
if( p ){
sqlite3ExpirePreparedStatements(db);
do {
VTable *pNext = p->pNext;
sqlite3VtabUnlock(p);
p = pNext;
}while( p );
}
}
/*
** Clear any and all virtual-table information from the Table record.
** This routine is called, for example, just before deleting the Table
** record.
**
** Since it is a virtual-table, the Table structure contains a pointer
** to the head of a linked list of VTable structures. Each VTable
** structure is associated with a single sqlite3* user of the schema.
** The reference count of the VTable structure associated with database
** connection db is decremented immediately (which may lead to the
** structure being xDisconnected and free). Any other VTable structures
** in the list are moved to the sqlite3.pDisconnect list of the associated
** database connection.
*/
void sqlite3VtabClear(sqlite3 *db, Table *p){
if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
if( p->azModuleArg ){
int i;
for(i=0; i<p->nModuleArg; i++){
sqlite3DbFree(db, p->azModuleArg[i]);
}
sqlite3DbFree(db, p->azModuleArg);
}
}
/*
** Add a new module argument to pTable->azModuleArg[].
** The string is not copied - the pointer is stored. The
** string will be freed automatically when the table is
** deleted.
*/
static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
int i = pTable->nModuleArg++;
int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
char **azModuleArg;
azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
if( azModuleArg==0 ){
int j;
for(j=0; j<i; j++){
sqlite3DbFree(db, pTable->azModuleArg[j]);
}
sqlite3DbFree(db, zArg);
sqlite3DbFree(db, pTable->azModuleArg);
pTable->nModuleArg = 0;
}else{
azModuleArg[i] = zArg;
azModuleArg[i+1] = 0;
}
pTable->azModuleArg = azModuleArg;
}
/*
** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
** statement. The module name has been parsed, but the optional list
** of parameters that follow the module name are still pending.
*/
void sqlite3VtabBeginParse(
Parse *pParse, /* Parsing context */
Token *pName1, /* Name of new table, or database name */
Token *pName2, /* Name of new table or NULL */
Token *pModuleName /* Name of the module for the virtual table */
){
int iDb; /* The database the table is being created in */
Table *pTable; /* The new virtual table */
sqlite3 *db; /* Database connection */
sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
pTable = pParse->pNewTable;
if( pTable==0 ) return;
assert( 0==pTable->pIndex );
db = pParse->db;
iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
assert( iDb>=0 );
pTable->tabFlags |= TF_Virtual;
pTable->nModuleArg = 0;
addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Creating a virtual table invokes the authorization callback twice.
** The first invocation, to obtain permission to INSERT a row into the
** sqlite_master table, has already been made by sqlite3StartTable().
** The second call, to obtain permission to create the table, is made now.
*/
if( pTable->azModuleArg ){
sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
}
#endif
}
/*
** This routine takes the module argument that has been accumulating
** in pParse->zArg[] and appends it to the list of arguments on the
** virtual table currently under construction in pParse->pTable.
*/
static void addArgumentToVtab(Parse *pParse){
if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
const char *z = (const char*)pParse->sArg.z;
int n = pParse->sArg.n;
sqlite3 *db = pParse->db;
addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
}
}
/*
** The parser calls this routine after the CREATE VIRTUAL TABLE statement
** has been completely parsed.
*/
void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
Table *pTab = pParse->pNewTable; /* The table being constructed */
sqlite3 *db = pParse->db; /* The database connection */
if( pTab==0 ) return;
addArgumentToVtab(pParse);
pParse->sArg.z = 0;
if( pTab->nModuleArg<1 ) return;
/* If the CREATE VIRTUAL TABLE statement is being entered for the
** first time (in other words if the virtual table is actually being
** created now instead of just being read out of sqlite_master) then
** do additional initialization work and store the statement text
** in the sqlite_master table.
*/
if( !db->init.busy ){
char *zStmt;
char *zWhere;
int iDb;
Vdbe *v;
/* Compute the complete text of the CREATE VIRTUAL TABLE statement */
if( pEnd ){
pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
}
zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
/* A slot for the record has already been allocated in the
** SQLITE_MASTER table. We just need to update that slot with all
** the information we've collected.
**
** The VM register number pParse->regRowid holds the rowid of an
** entry in the sqlite_master table tht was created for this vtab
** by sqlite3StartTable().
*/
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3NestedParse(pParse,
"UPDATE %Q.%s "
"SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
"WHERE rowid=#%d",
db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
pTab->zName,
pTab->zName,
zStmt,
pParse->regRowid
);
sqlite3DbFree(db, zStmt);
v = sqlite3GetVdbe(pParse);
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
}
/* If we are rereading the sqlite_master table create the in-memory
** record of the table. The xConnect() method is not called until
** the first time the virtual table is used in an SQL statement. This
** allows a schema that contains virtual tables to be loaded before
** the required virtual table implementations are registered. */
else {
Table *pOld;
Schema *pSchema = pTab->pSchema;
const char *zName = pTab->zName;
int nName = sqlite3Strlen30(zName);
assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
if( pOld ){
db->mallocFailed = 1;
assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
return;
}
pParse->pNewTable = 0;
}
}
/*
** The parser calls this routine when it sees the first token
** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite3VtabArgInit(Parse *pParse){
addArgumentToVtab(pParse);
pParse->sArg.z = 0;
pParse->sArg.n = 0;
}
/*
** The parser calls this routine for each token after the first token
** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
void sqlite3VtabArgExtend(Parse *pParse, Token *p){
Token *pArg = &pParse->sArg;
if( pArg->z==0 ){
pArg->z = p->z;
pArg->n = p->n;
}else{
assert(pArg->z < p->z);
pArg->n = (int)(&p->z[p->n] - pArg->z);
}
}
/*
** Invoke a virtual table constructor (either xCreate or xConnect). The
** pointer to the function to invoke is passed as the fourth parameter
** to this procedure.
*/
static int vtabCallConstructor(
sqlite3 *db,
Table *pTab,
Module *pMod,
int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
char **pzErr
){
VTable *pVTable;
int rc;
const char *const*azArg = (const char *const*)pTab->azModuleArg;
int nArg = pTab->nModuleArg;
char *zErr = 0;
char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
if( !zModuleName ){
return SQLITE_NOMEM;
}
pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
if( !pVTable ){
sqlite3DbFree(db, zModuleName);
return SQLITE_NOMEM;
}
pVTable->db = db;
pVTable->pMod = pMod;
assert( !db->pVTab );
assert( xConstruct );
db->pVTab = pTab;
/* Invoke the virtual table constructor */
rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
if( SQLITE_OK!=rc ){
if( zErr==0 ){
*pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
}else {
*pzErr = sqlite3MPrintf(db, "%s", zErr);
sqlite3_free(zErr);
}
sqlite3DbFree(db, pVTable);
}else if( ALWAYS(pVTable->pVtab) ){
/* Justification of ALWAYS(): A correct vtab constructor must allocate
** the sqlite3_vtab object if successful. */
pVTable->pVtab->pModule = pMod->pModule;
pVTable->nRef = 1;
if( db->pVTab ){
const char *zFormat = "vtable constructor did not declare schema: %s";
*pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
sqlite3VtabUnlock(pVTable);
rc = SQLITE_ERROR;
}else{
int iCol;
/* If everything went according to plan, link the new VTable structure
** into the linked list headed by pTab->pVTable. Then loop through the
** columns of the table to see if any of them contain the token "hidden".
** If so, set the Column.isHidden flag and remove the token from
** the type string. */
pVTable->pNext = pTab->pVTable;
pTab->pVTable = pVTable;
for(iCol=0; iCol<pTab->nCol; iCol++){
char *zType = pTab->aCol[iCol].zType;
int nType;
int i = 0;
if( !zType ) continue;
nType = sqlite3Strlen30(zType);
if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
for(i=0; i<nType; i++){
if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
&& (zType[i+7]=='\0' || zType[i+7]==' ')
){
i++;
break;
}
}
}
if( i<nType ){
int j;
int nDel = 6 + (zType[i+6] ? 1 : 0);
for(j=i; (j+nDel)<=nType; j++){
zType[j] = zType[j+nDel];
}
if( zType[i]=='\0' && i>0 ){
assert(zType[i-1]==' ');
zType[i-1] = '\0';
}
pTab->aCol[iCol].isHidden = 1;
}
}
}
}
sqlite3DbFree(db, zModuleName);
db->pVTab = 0;
return rc;
}
/*
** This function is invoked by the parser to call the xConnect() method
** of the virtual table pTab. If an error occurs, an error code is returned
** and an error left in pParse.
**
** This call is a no-op if table pTab is not a virtual table.
*/
int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
sqlite3 *db = pParse->db;
const char *zMod;
Module *pMod;
int rc;
assert( pTab );
if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
return SQLITE_OK;
}
/* Locate the required virtual table module */
zMod = pTab->azModuleArg[0];
pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
if( !pMod ){
const char *zModule = pTab->azModuleArg[0];
sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
rc = SQLITE_ERROR;
}else{
char *zErr = 0;
rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
if( rc!=SQLITE_OK ){
sqlite3ErrorMsg(pParse, "%s", zErr);
}
sqlite3DbFree(db, zErr);
}
return rc;
}
/*
** Add the virtual table pVTab to the array sqlite3.aVTrans[].
*/
static int addToVTrans(sqlite3 *db, VTable *pVTab){
const int ARRAY_INCR = 5;
/* Grow the sqlite3.aVTrans array if required */
if( (db->nVTrans%ARRAY_INCR)==0 ){
VTable **aVTrans;
int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
if( !aVTrans ){
return SQLITE_NOMEM;
}
memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
db->aVTrans = aVTrans;
}
/* Add pVtab to the end of sqlite3.aVTrans */
db->aVTrans[db->nVTrans++] = pVTab;
sqlite3VtabLock(pVTab);
return SQLITE_OK;
}
/*
** This function is invoked by the vdbe to call the xCreate method
** of the virtual table named zTab in database iDb.
**
** If an error occurs, *pzErr is set to point an an English language
** description of the error and an SQLITE_XXX error code is returned.
** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
*/
int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
int rc = SQLITE_OK;
Table *pTab;
Module *pMod;
const char *zMod;
pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
/* Locate the required virtual table module */
zMod = pTab->azModuleArg[0];
pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
/* If the module has been registered and includes a Create method,
** invoke it now. If the module has not been registered, return an
** error. Otherwise, do nothing.
*/
if( !pMod ){
*pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
rc = SQLITE_ERROR;
}else{
rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
}
/* Justification of ALWAYS(): The xConstructor method is required to
** create a valid sqlite3_vtab if it returns SQLITE_OK. */
if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
}
return rc;
}
/*
** This function is used to set the schema of a virtual table. It is only
** valid to call this function from within the xCreate() or xConnect() of a
** virtual table module.
*/
int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
Parse *pParse;
int rc = SQLITE_OK;
Table *pTab;
char *zErr = 0;
sqlite3_mutex_enter(db->mutex);
pTab = db->pVTab;
if( !pTab ){
sqlite3Error(db, SQLITE_MISUSE, 0);
sqlite3_mutex_leave(db->mutex);
return SQLITE_MISUSE_BKPT;
}
assert( (pTab->tabFlags & TF_Virtual)!=0 );
pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
if( pParse==0 ){
rc = SQLITE_NOMEM;
}else{
pParse->declareVtab = 1;
pParse->db = db;
pParse->nQueryLoop = 1;
if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
&& pParse->pNewTable
&& !db->mallocFailed
&& !pParse->pNewTable->pSelect
&& (pParse->pNewTable->tabFlags & TF_Virtual)==0
){
if( !pTab->aCol ){
pTab->aCol = pParse->pNewTable->aCol;
pTab->nCol = pParse->pNewTable->nCol;
pParse->pNewTable->nCol = 0;
pParse->pNewTable->aCol = 0;
}
db->pVTab = 0;
}else{
sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
sqlite3DbFree(db, zErr);
rc = SQLITE_ERROR;
}
pParse->declareVtab = 0;
if( pParse->pVdbe ){
sqlite3VdbeFinalize(pParse->pVdbe);
}
sqlite3DeleteTable(db, pParse->pNewTable);
sqlite3StackFree(db, pParse);
}
assert( (rc&0xff)==rc );
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** This function is invoked by the vdbe to call the xDestroy method
** of the virtual table named zTab in database iDb. This occurs
** when a DROP TABLE is mentioned.
**
** This call is a no-op if zTab is not a virtual table.
*/
int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
int rc = SQLITE_OK;
Table *pTab;
pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
VTable *p = vtabDisconnectAll(db, pTab);
assert( rc==SQLITE_OK );
rc = p->pMod->pModule->xDestroy(p->pVtab);
/* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
if( rc==SQLITE_OK ){
assert( pTab->pVTable==p && p->pNext==0 );
p->pVtab = 0;
pTab->pVTable = 0;
sqlite3VtabUnlock(p);
}
}
return rc;
}
/*
** This function invokes either the xRollback or xCommit method
** of each of the virtual tables in the sqlite3.aVTrans array. The method
** called is identified by the second argument, "offset", which is
** the offset of the method to call in the sqlite3_module structure.
**
** The array is cleared after invoking the callbacks.
*/
static void callFinaliser(sqlite3 *db, int offset){
int i;
if( db->aVTrans ){
for(i=0; i<db->nVTrans; i++){
VTable *pVTab = db->aVTrans[i];
sqlite3_vtab *p = pVTab->pVtab;
if( p ){
int (*x)(sqlite3_vtab *);
x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
if( x ) x(p);
}
sqlite3VtabUnlock(pVTab);
}
sqlite3DbFree(db, db->aVTrans);
db->nVTrans = 0;
db->aVTrans = 0;
}
}
/*
** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
** array. Return the error code for the first error that occurs, or
** SQLITE_OK if all xSync operations are successful.
**
** Set *pzErrmsg to point to a buffer that should be released using
** sqlite3DbFree() containing an error message, if one is available.
*/
int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
int i;
int rc = SQLITE_OK;
VTable **aVTrans = db->aVTrans;
db->aVTrans = 0;
for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
int (*x)(sqlite3_vtab *);
sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
rc = x(pVtab);
sqlite3DbFree(db, *pzErrmsg);
*pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
sqlite3_free(pVtab->zErrMsg);
}
}
db->aVTrans = aVTrans;
return rc;
}
/*
** Invoke the xRollback method of all virtual tables in the
** sqlite3.aVTrans array. Then clear the array itself.
*/
int sqlite3VtabRollback(sqlite3 *db){
callFinaliser(db, offsetof(sqlite3_module,xRollback));
return SQLITE_OK;
}
/*
** Invoke the xCommit method of all virtual tables in the
** sqlite3.aVTrans array. Then clear the array itself.
*/
int sqlite3VtabCommit(sqlite3 *db){
callFinaliser(db, offsetof(sqlite3_module,xCommit));
return SQLITE_OK;
}
/*
** If the virtual table pVtab supports the transaction interface
** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
** not currently open, invoke the xBegin method now.
**
** If the xBegin call is successful, place the sqlite3_vtab pointer
** in the sqlite3.aVTrans array.
*/
int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
int rc = SQLITE_OK;
const sqlite3_module *pModule;
/* Special case: If db->aVTrans is NULL and db->nVTrans is greater
** than zero, then this function is being called from within a
** virtual module xSync() callback. It is illegal to write to
** virtual module tables in this case, so return SQLITE_LOCKED.
*/
if( sqlite3VtabInSync(db) ){
return SQLITE_LOCKED;
}
if( !pVTab ){
return SQLITE_OK;
}
pModule = pVTab->pVtab->pModule;
if( pModule->xBegin ){
int i;
/* If pVtab is already in the aVTrans array, return early */
for(i=0; i<db->nVTrans; i++){
if( db->aVTrans[i]==pVTab ){
return SQLITE_OK;
}
}
/* Invoke the xBegin method */
rc = pModule->xBegin(pVTab->pVtab);
if( rc==SQLITE_OK ){
rc = addToVTrans(db, pVTab);
}
}
return rc;
}
/*
** The first parameter (pDef) is a function implementation. The
** second parameter (pExpr) is the first argument to this function.
** If pExpr is a column in a virtual table, then let the virtual
** table implementation have an opportunity to overload the function.
**
** This routine is used to allow virtual table implementations to
** overload MATCH, LIKE, GLOB, and REGEXP operators.
**
** Return either the pDef argument (indicating no change) or a
** new FuncDef structure that is marked as ephemeral using the
** SQLITE_FUNC_EPHEM flag.
*/
FuncDef *sqlite3VtabOverloadFunction(
sqlite3 *db, /* Database connection for reporting malloc problems */
FuncDef *pDef, /* Function to possibly overload */
int nArg, /* Number of arguments to the function */
Expr *pExpr /* First argument to the function */
){
Table *pTab;
sqlite3_vtab *pVtab;
sqlite3_module *pMod;
void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
void *pArg = 0;
FuncDef *pNew;
int rc = 0;
char *zLowerName;
unsigned char *z;
/* Check to see the left operand is a column in a virtual table */
if( NEVER(pExpr==0) ) return pDef;
if( pExpr->op!=TK_COLUMN ) return pDef;
pTab = pExpr->pTab;
if( NEVER(pTab==0) ) return pDef;
if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
pVtab = sqlite3GetVTable(db, pTab)->pVtab;
assert( pVtab!=0 );
assert( pVtab->pModule!=0 );
pMod = (sqlite3_module *)pVtab->pModule;
if( pMod->xFindFunction==0 ) return pDef;
/* Call the xFindFunction method on the virtual table implementation
** to see if the implementation wants to overload this function
*/
zLowerName = sqlite3DbStrDup(db, pDef->zName);
if( zLowerName ){
for(z=(unsigned char*)zLowerName; *z; z++){
*z = sqlite3UpperToLower[*z];
}
rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
sqlite3DbFree(db, zLowerName);
}
if( rc==0 ){
return pDef;
}
/* Create a new ephemeral function definition for the overloaded
** function */
pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
+ sqlite3Strlen30(pDef->zName) + 1);
if( pNew==0 ){
return pDef;
}
*pNew = *pDef;
pNew->zName = (char *)&pNew[1];
memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
pNew->xFunc = xFunc;
pNew->pUserData = pArg;
pNew->flags |= SQLITE_FUNC_EPHEM;
return pNew;
}
/*
** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
** array so that an OP_VBegin will get generated for it. Add pTab to the
** array if it is missing. If pTab is already in the array, this routine
** is a no-op.
*/
void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
int i, n;
Table **apVtabLock;
assert( IsVirtual(pTab) );
for(i=0; i<pToplevel->nVtabLock; i++){
if( pTab==pToplevel->apVtabLock[i] ) return;
}
n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
if( apVtabLock ){
pToplevel->apVtabLock = apVtabLock;
pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
}else{
pToplevel->db->mallocFailed = 1;
}
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */
| bsd-3-clause |
AALEKH/go | test/bench/shootout/threadring.c | 191 | 3324 | /*
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 "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" 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.
*/
/*
* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
* contributed by Premysl Hruby
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <limits.h>
// PTHREAD_STACK_MIN undeclared on mingw
#ifndef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 65535
#endif
#define THREADS (503)
struct stack {
char x[PTHREAD_STACK_MIN];
};
/* staticaly initialize mutex[0] mutex */
static pthread_mutex_t mutex[THREADS];
static int data[THREADS];
static struct stack stacks[THREADS];
/* stacks must be defined staticaly, or my i386 box run of virtual memory for this
* process while creating thread +- #400 */
static void* thread(void *num)
{
int l = (int)(uintptr_t)num;
int r = (l+1) % THREADS;
int token;
while(1) {
pthread_mutex_lock(mutex + l);
token = data[l];
if (token) {
data[r] = token - 1;
pthread_mutex_unlock(mutex + r);
}
else {
printf("%i\n", l+1);
exit(0);
}
}
}
int main(int argc, char **argv)
{
int i;
pthread_t cthread;
pthread_attr_t stack_attr;
if (argc != 2)
exit(255);
data[0] = atoi(argv[1]);
pthread_attr_init(&stack_attr);
for (i = 0; i < THREADS; i++) {
pthread_mutex_init(mutex + i, NULL);
pthread_mutex_lock(mutex + i);
#if defined(__MINGW32__) || defined(__MINGW64__)
pthread_attr_setstackaddr(&stack_attr, &stacks[i]);
pthread_attr_setstacksize(&stack_attr, sizeof(struct stack));
#else
pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack));
#endif
pthread_create(&cthread, &stack_attr, thread, (void*)(uintptr_t)i);
}
pthread_mutex_unlock(mutex + 0);
pthread_join(cthread, NULL);
}
| bsd-3-clause |
xin3liang/platform_external_chromium_org | third_party/simplejson/_speedups.c | 210 | 89288 | #include "Python.h"
#include "structmember.h"
#if PY_VERSION_HEX < 0x02070000 && !defined(PyOS_string_to_double)
#define PyOS_string_to_double json_PyOS_string_to_double
static double
json_PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception);
static double
json_PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) {
double x;
assert(endptr == NULL);
assert(overflow_exception == NULL);
PyFPE_START_PROTECT("json_PyOS_string_to_double", return -1.0;)
x = PyOS_ascii_atof(s);
PyFPE_END_PROTECT(x)
return x;
}
#endif
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_SIZE)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#endif
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PyInt_FromSsize_t PyInt_FromLong
#define PyInt_AsSsize_t PyInt_AsLong
#endif
#ifndef Py_IS_FINITE
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
#endif
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#define DEFAULT_ENCODING "utf-8"
#define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
#define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
#define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
#define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
static PyTypeObject PyScannerType;
static PyTypeObject PyEncoderType;
typedef struct _PyScannerObject {
PyObject_HEAD
PyObject *encoding;
PyObject *strict;
PyObject *object_hook;
PyObject *pairs_hook;
PyObject *parse_float;
PyObject *parse_int;
PyObject *parse_constant;
PyObject *memo;
} PyScannerObject;
static PyMemberDef scanner_members[] = {
{"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
{"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
{"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
{"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, pairs_hook), READONLY, "object_pairs_hook"},
{"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
{"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
{"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
{NULL}
};
typedef struct _PyEncoderObject {
PyObject_HEAD
PyObject *markers;
PyObject *defaultfn;
PyObject *encoder;
PyObject *indent;
PyObject *key_separator;
PyObject *item_separator;
PyObject *sort_keys;
PyObject *skipkeys;
PyObject *key_memo;
PyObject *Decimal;
int fast_encode;
int allow_nan;
int use_decimal;
int namedtuple_as_object;
int tuple_as_array;
int bigint_as_string;
PyObject *item_sort_key;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
{"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
{"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
{"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
{"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
{"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
{"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
{"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
{"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
{"key_memo", T_OBJECT, offsetof(PyEncoderObject, key_memo), READONLY, "key_memo"},
{"item_sort_key", T_OBJECT, offsetof(PyEncoderObject, item_sort_key), READONLY, "item_sort_key"},
{NULL}
};
static PyObject *
maybe_quote_bigint(PyObject *encoded, PyObject *obj);
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
static PyObject *
ascii_escape_unicode(PyObject *pystr);
static PyObject *
ascii_escape_str(PyObject *pystr);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
void init_speedups(void);
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
static PyObject *
scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
scanner_dealloc(PyObject *self);
static int
scanner_clear(PyObject *self);
static PyObject *
encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
encoder_dealloc(PyObject *self);
static int
encoder_clear(PyObject *self);
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
static PyObject *
_encoded_const(PyObject *obj);
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj);
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj);
static int
_is_namedtuple(PyObject *obj);
#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
#define MIN_EXPANSION 6
#ifdef Py_UNICODE_WIDE
#define MAX_EXPANSION (2 * MIN_EXPANSION)
#else
#define MAX_EXPANSION MIN_EXPANSION
#endif
static PyObject *
maybe_quote_bigint(PyObject *encoded, PyObject *obj)
{
static PyObject *big_long = NULL;
static PyObject *small_long = NULL;
if (big_long == NULL) {
big_long = PyLong_FromLongLong(1LL << 53);
if (big_long == NULL) {
Py_DECREF(encoded);
return NULL;
}
}
if (small_long == NULL) {
small_long = PyLong_FromLongLong(-1LL << 53);
if (small_long == NULL) {
Py_DECREF(encoded);
return NULL;
}
}
if (PyObject_RichCompareBool(obj, big_long, Py_GE) ||
PyObject_RichCompareBool(obj, small_long, Py_LE)) {
PyObject* quoted = PyString_FromFormat("\"%s\"",
PyString_AsString(encoded));
Py_DECREF(encoded);
encoded = quoted;
}
return encoded;
}
static int
_is_namedtuple(PyObject *obj)
{
int rval = 0;
PyObject *_asdict = PyObject_GetAttrString(obj, "_asdict");
if (_asdict == NULL) {
PyErr_Clear();
return 0;
}
rval = PyCallable_Check(_asdict);
Py_DECREF(_asdict);
return rval;
}
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
{
/* PyObject to Py_ssize_t converter */
*size_ptr = PyInt_AsSsize_t(o);
if (*size_ptr == -1 && PyErr_Occurred())
return 0;
return 1;
}
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
{
/* Py_ssize_t to PyObject converter */
return PyInt_FromSsize_t(*size_ptr);
}
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
{
/* Escape unicode code point c to ASCII escape sequences
in char *output. output must have at least 12 bytes unused to
accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
output[chars++] = '\\';
switch (c) {
case '\\': output[chars++] = (char)c; break;
case '"': output[chars++] = (char)c; break;
case '\b': output[chars++] = 'b'; break;
case '\f': output[chars++] = 'f'; break;
case '\n': output[chars++] = 'n'; break;
case '\r': output[chars++] = 'r'; break;
case '\t': output[chars++] = 't'; break;
default:
#ifdef Py_UNICODE_WIDE
if (c >= 0x10000) {
/* UTF-16 surrogate pair */
Py_UNICODE v = c - 0x10000;
c = 0xd800 | ((v >> 10) & 0x3ff);
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
c = 0xdc00 | (v & 0x3ff);
output[chars++] = '\\';
}
#endif
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
}
return chars;
}
static PyObject *
ascii_escape_unicode(PyObject *pystr)
{
/* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t max_output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
Py_UNICODE *input_unicode;
input_chars = PyUnicode_GET_SIZE(pystr);
input_unicode = PyUnicode_AS_UNICODE(pystr);
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
max_output_size = 2 + (input_chars * MAX_EXPANSION);
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
chars = 0;
output[chars++] = '"';
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = input_unicode[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
if (output_size - chars < (1 + MAX_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
Py_ssize_t new_output_size = output_size * 2;
/* This is an upper bound */
if (new_output_size > max_output_size) {
new_output_size = max_output_size;
}
/* Make sure that the output size changed before resizing */
if (new_output_size != output_size) {
output_size = new_output_size;
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static PyObject *
ascii_escape_str(PyObject *pystr)
{
/* Take a PyString pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
char *input_str;
input_chars = PyString_GET_SIZE(pystr);
input_str = PyString_AS_STRING(pystr);
/* Fast path for a string that's already ASCII */
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (!S_CHAR(c)) {
/* If we have to escape something, scan the string for unicode */
Py_ssize_t j;
for (j = i; j < input_chars; j++) {
c = (Py_UNICODE)(unsigned char)input_str[j];
if (c > 0x7f) {
/* We hit a non-ASCII character, bail to unicode mode */
PyObject *uni;
uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
if (uni == NULL) {
return NULL;
}
rval = ascii_escape_unicode(uni);
Py_DECREF(uni);
return rval;
}
}
break;
}
}
if (i == input_chars) {
/* Input is already ASCII */
output_size = 2 + input_chars;
}
else {
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
}
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
output[0] = '"';
/* We know that everything up to i is ASCII already */
chars = i + 1;
memcpy(&output[1], input_str, i);
for (; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
/* An ASCII char can't possibly expand to a surrogate! */
if (output_size - chars < (1 + MIN_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
output_size *= 2;
if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
output_size = 2 + (input_chars * MIN_EXPANSION);
}
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
{
/* Use the Python function simplejson.decoder.errmsg to raise a nice
looking ValueError exception */
static PyObject *JSONDecodeError = NULL;
PyObject *exc;
if (JSONDecodeError == NULL) {
PyObject *decoder = PyImport_ImportModule("simplejson.decoder");
if (decoder == NULL)
return;
JSONDecodeError = PyObject_GetAttrString(decoder, "JSONDecodeError");
Py_DECREF(decoder);
if (JSONDecodeError == NULL)
return;
}
exc = PyObject_CallFunction(JSONDecodeError, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
if (exc) {
PyErr_SetObject(JSONDecodeError, exc);
Py_DECREF(exc);
}
}
static PyObject *
join_list_unicode(PyObject *lst)
{
/* return u''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
join_list_string(PyObject *lst)
{
/* return ''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
PyObject *pyidx;
/*
steal a reference to rval, returns (rval, idx)
*/
if (rval == NULL) {
return NULL;
}
pyidx = PyInt_FromSsize_t(idx);
if (pyidx == NULL) {
Py_DECREF(rval);
return NULL;
}
tpl = PyTuple_New(2);
if (tpl == NULL) {
Py_DECREF(pyidx);
Py_DECREF(rval);
return NULL;
}
PyTuple_SET_ITEM(tpl, 0, rval);
PyTuple_SET_ITEM(tpl, 1, pyidx);
return tpl;
}
#define APPEND_OLD_CHUNK \
if (chunk != NULL) { \
if (chunks == NULL) { \
chunks = PyList_New(0); \
if (chunks == NULL) { \
goto bail; \
} \
} \
if (PyList_Append(chunks, chunk)) { \
goto bail; \
} \
Py_CLEAR(chunk); \
}
static PyObject *
scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyString pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyString (if ASCII-only) or PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyString_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
int has_unicode = 0;
char *buf = PyString_AS_STRING(pystr);
PyObject *chunks = NULL;
PyObject *chunk = NULL;
if (len == end) {
raise_errmsg("Unterminated string starting at", pystr, begin);
}
else if (end < 0 || len < end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
for (next = end; next < len; next++) {
c = (unsigned char)buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
else if (c > 0x7f) {
has_unicode = 1;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
PyObject *strchunk;
APPEND_OLD_CHUNK
strchunk = PyString_FromStringAndSize(&buf[end], next - end);
if (strchunk == NULL) {
goto bail;
}
if (has_unicode) {
chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
Py_DECREF(strchunk);
if (chunk == NULL) {
goto bail;
}
}
else {
chunk = strchunk;
}
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
if (c > 0x7f) {
has_unicode = 1;
}
APPEND_OLD_CHUNK
if (has_unicode) {
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
}
else {
char c_char = Py_CHARMASK(c);
chunk = PyString_FromStringAndSize(&c_char, 1);
if (chunk == NULL) {
goto bail;
}
}
}
if (chunks == NULL) {
if (chunk != NULL)
rval = chunk;
else
rval = PyString_FromStringAndSize("", 0);
}
else {
APPEND_OLD_CHUNK
rval = join_list_string(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
}
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunk);
Py_XDECREF(chunks);
return NULL;
}
static PyObject *
scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyUnicode pystr.
end is the index of the first character after the quote.
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
PyObject *chunks = NULL;
PyObject *chunk = NULL;
if (len == end) {
raise_errmsg("Unterminated string starting at", pystr, begin);
}
else if (end < 0 || len < end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
for (next = end; next < len; next++) {
c = buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
APPEND_OLD_CHUNK
chunk = PyUnicode_FromUnicode(&buf[end], next - end);
if (chunk == NULL) {
goto bail;
}
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
APPEND_OLD_CHUNK
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
}
if (chunks == NULL) {
if (chunk != NULL)
rval = chunk;
else
rval = PyUnicode_FromUnicode(NULL, 0);
}
else {
APPEND_OLD_CHUNK
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
}
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunk);
Py_XDECREF(chunks);
return NULL;
}
PyDoc_STRVAR(pydoc_scanstring,
"scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
"\n"
"Scan the string s for a JSON string. End is the index of the\n"
"character in s after the quote that started the JSON string.\n"
"Unescapes all valid JSON string escape sequences and raises ValueError\n"
"on attempt to decode an invalid string. If strict is False then literal\n"
"control characters are allowed in the string.\n"
"\n"
"Returns a tuple of the decoded string and the index of the character in s\n"
"after the end quote."
);
static PyObject *
py_scanstring(PyObject* self UNUSED, PyObject *args)
{
PyObject *pystr;
PyObject *rval;
Py_ssize_t end;
Py_ssize_t next_end = -1;
char *encoding = NULL;
int strict = 1;
if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
return NULL;
}
if (encoding == NULL) {
encoding = DEFAULT_ENCODING;
}
if (PyString_Check(pystr)) {
rval = scanstring_str(pystr, end, encoding, strict, &next_end);
}
else if (PyUnicode_Check(pystr)) {
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_end);
}
PyDoc_STRVAR(pydoc_encode_basestring_ascii,
"encode_basestring_ascii(basestring) -> str\n"
"\n"
"Return an ASCII-only JSON representation of a Python string"
);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
{
/* Return an ASCII-only JSON representation of a Python string */
/* METH_O */
if (PyString_Check(pystr)) {
return ascii_escape_str(pystr);
}
else if (PyUnicode_Check(pystr)) {
return ascii_escape_unicode(pystr);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
}
static void
scanner_dealloc(PyObject *self)
{
/* Deallocate scanner object */
scanner_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
scanner_traverse(PyObject *self, visitproc visit, void *arg)
{
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_VISIT(s->encoding);
Py_VISIT(s->strict);
Py_VISIT(s->object_hook);
Py_VISIT(s->pairs_hook);
Py_VISIT(s->parse_float);
Py_VISIT(s->parse_int);
Py_VISIT(s->parse_constant);
Py_VISIT(s->memo);
return 0;
}
static int
scanner_clear(PyObject *self)
{
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->pairs_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
Py_CLEAR(s->memo);
return 0;
}
static PyObject *
_parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyString pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook or
object_pairs_hook can change that)
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *rval = NULL;
PyObject *pairs = NULL;
PyObject *item;
PyObject *key = NULL;
PyObject *val = NULL;
char *encoding = PyString_AS_STRING(s->encoding);
int strict = PyObject_IsTrue(s->strict);
int has_pairs_hook = (s->pairs_hook != Py_None);
Py_ssize_t next_idx;
if (has_pairs_hook) {
pairs = PyList_New(0);
if (pairs == NULL)
return NULL;
}
else {
rval = PyDict_New();
if (rval == NULL)
return NULL;
}
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
PyObject *memokey;
/* read key */
if (str[idx] != '"') {
raise_errmsg(
"Expecting property name enclosed in double quotes",
pystr, idx);
goto bail;
}
key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
if (key == NULL)
goto bail;
memokey = PyDict_GetItem(s->memo, key);
if (memokey != NULL) {
Py_INCREF(memokey);
Py_DECREF(key);
key = memokey;
}
else {
if (PyDict_SetItem(s->memo, key, key) < 0)
goto bail;
}
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting ':' delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON data type */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (has_pairs_hook) {
item = PyTuple_Pack(2, key, val);
if (item == NULL)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
if (PyList_Append(pairs, item) == -1) {
Py_DECREF(item);
goto bail;
}
Py_DECREF(item);
}
else {
if (PyDict_SetItem(rval, key, val) < 0)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
}
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting ',' delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
if (s->pairs_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
if (val == NULL)
goto bail;
Py_DECREF(pairs);
*next_idx_ptr = idx + 1;
return val;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(rval);
Py_XDECREF(key);
Py_XDECREF(val);
Py_XDECREF(pairs);
return NULL;
}
static PyObject *
_parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyUnicode pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *rval = NULL;
PyObject *pairs = NULL;
PyObject *item;
PyObject *key = NULL;
PyObject *val = NULL;
int strict = PyObject_IsTrue(s->strict);
int has_pairs_hook = (s->pairs_hook != Py_None);
Py_ssize_t next_idx;
if (has_pairs_hook) {
pairs = PyList_New(0);
if (pairs == NULL)
return NULL;
}
else {
rval = PyDict_New();
if (rval == NULL)
return NULL;
}
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
PyObject *memokey;
/* read key */
if (str[idx] != '"') {
raise_errmsg(
"Expecting property name enclosed in double quotes",
pystr, idx);
goto bail;
}
key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
if (key == NULL)
goto bail;
memokey = PyDict_GetItem(s->memo, key);
if (memokey != NULL) {
Py_INCREF(memokey);
Py_DECREF(key);
key = memokey;
}
else {
if (PyDict_SetItem(s->memo, key, key) < 0)
goto bail;
}
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip
whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting ':' delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (has_pairs_hook) {
item = PyTuple_Pack(2, key, val);
if (item == NULL)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
if (PyList_Append(pairs, item) == -1) {
Py_DECREF(item);
goto bail;
}
Py_DECREF(item);
}
else {
if (PyDict_SetItem(rval, key, val) < 0)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
}
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the ,
delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting ',' delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
if (s->pairs_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
if (val == NULL)
goto bail;
Py_DECREF(pairs);
*next_idx_ptr = idx + 1;
return val;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(rval);
Py_XDECREF(key);
Py_XDECREF(val);
Py_XDECREF(pairs);
return NULL;
}
static PyObject *
_parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term and de-tuplefy the (rval, idx) */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL) {
if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
PyErr_Clear();
raise_errmsg("Expecting object", pystr, idx);
}
goto bail;
}
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting ',' delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL) {
if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
PyErr_Clear();
raise_errmsg("Expecting object", pystr, idx);
}
goto bail;
}
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting ',' delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON constant from PyString pystr.
constant is the constant string that was found
("NaN", "Infinity", "-Infinity").
idx is the index of the first character of the constant
*next_idx_ptr is a return-by-reference index to the first character after
the constant.
Returns the result of parse_constant
*/
PyObject *cstr;
PyObject *rval;
/* constant is "NaN", "Infinity", or "-Infinity" */
cstr = PyString_InternFromString(constant);
if (cstr == NULL)
return NULL;
/* rval = parse_constant(constant) */
rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
idx += PyString_GET_SIZE(cstr);
Py_DECREF(cstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyString pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
/* save the index of the 'e' or 'E' just in case we need to backtrack */
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyString_FromStringAndSize(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
/* rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr))); */
double d = PyOS_string_to_double(PyString_AS_STRING(numstr),
NULL, NULL);
if (d == -1.0 && PyErr_Occurred())
return NULL;
rval = PyFloat_FromDouble(d);
}
}
else {
/* parse as an int using a fast path if available, otherwise call user defined method */
if (s->parse_int != (PyObject *)&PyInt_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
else {
rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
}
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyUnicode pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyUnicode_FromUnicode(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromString(numstr, NULL);
}
}
else {
/* no fast path for unicode -> int, just call */
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyString pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
PyObject *rval = NULL;
int fallthrough = 0;
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
if (Py_EnterRecursiveCall(" while decoding a JSON document"))
return NULL;
switch (str[idx]) {
case '"':
/* string */
rval = scanstring_str(pystr, idx + 1,
PyString_AS_STRING(s->encoding),
PyObject_IsTrue(s->strict),
next_idx_ptr);
break;
case '{':
/* object */
rval = _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
break;
case '[':
/* array */
rval = _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
break;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
rval = Py_None;
}
else
fallthrough = 1;
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
rval = Py_True;
}
else
fallthrough = 1;
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
rval = Py_False;
}
else
fallthrough = 1;
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
rval = _parse_constant(s, "NaN", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
rval = _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
rval = _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
default:
fallthrough = 1;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
if (fallthrough)
rval = _match_number_str(s, pystr, idx, next_idx_ptr);
Py_LeaveRecursiveCall();
return rval;
}
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyUnicode pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
PyObject *rval = NULL;
int fallthrough = 0;
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
if (Py_EnterRecursiveCall(" while decoding a JSON document"))
return NULL;
switch (str[idx]) {
case '"':
/* string */
rval = scanstring_unicode(pystr, idx + 1,
PyObject_IsTrue(s->strict),
next_idx_ptr);
break;
case '{':
/* object */
rval = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
break;
case '[':
/* array */
rval = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
break;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
rval = Py_None;
}
else
fallthrough = 1;
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
rval = Py_True;
}
else
fallthrough = 1;
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
rval = Py_False;
}
else
fallthrough = 1;
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
rval = _parse_constant(s, "NaN", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
rval = _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
rval = _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
else
fallthrough = 1;
break;
default:
fallthrough = 1;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
if (fallthrough)
rval = _match_number_unicode(s, pystr, idx, next_idx_ptr);
Py_LeaveRecursiveCall();
return rval;
}
static PyObject *
scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to scan_once_{str,unicode} */
PyObject *pystr;
PyObject *rval;
Py_ssize_t idx;
Py_ssize_t next_idx = -1;
static char *kwlist[] = {"string", "idx", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
return NULL;
if (PyString_Check(pystr)) {
rval = scan_once_str(s, pystr, idx, &next_idx);
}
else if (PyUnicode_Check(pystr)) {
rval = scan_once_unicode(s, pystr, idx, &next_idx);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
PyDict_Clear(s->memo);
return _build_rval_index_tuple(rval, next_idx);
}
static PyObject *
scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyScannerObject *s;
s = (PyScannerObject *)type->tp_alloc(type, 0);
if (s != NULL) {
s->encoding = NULL;
s->strict = NULL;
s->object_hook = NULL;
s->pairs_hook = NULL;
s->parse_float = NULL;
s->parse_int = NULL;
s->parse_constant = NULL;
}
return (PyObject *)s;
}
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Initialize Scanner object */
PyObject *ctx;
static char *kwlist[] = {"context", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
return -1;
if (s->memo == NULL) {
s->memo = PyDict_New();
if (s->memo == NULL)
goto bail;
}
/* PyString_AS_STRING is used on encoding */
s->encoding = PyObject_GetAttrString(ctx, "encoding");
if (s->encoding == NULL)
goto bail;
if (s->encoding == Py_None) {
Py_DECREF(Py_None);
s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
}
else if (PyUnicode_Check(s->encoding)) {
PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
Py_DECREF(s->encoding);
s->encoding = tmp;
}
if (s->encoding == NULL || !PyString_Check(s->encoding))
goto bail;
/* All of these will fail "gracefully" so we don't need to verify them */
s->strict = PyObject_GetAttrString(ctx, "strict");
if (s->strict == NULL)
goto bail;
s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
if (s->object_hook == NULL)
goto bail;
s->pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook");
if (s->pairs_hook == NULL)
goto bail;
s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
if (s->parse_float == NULL)
goto bail;
s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
if (s->parse_int == NULL)
goto bail;
s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
if (s->parse_constant == NULL)
goto bail;
return 0;
bail:
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->pairs_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return -1;
}
PyDoc_STRVAR(scanner_doc, "JSON scanner object");
static
PyTypeObject PyScannerType = {
PyObject_HEAD_INIT(NULL)
0, /* tp_internal */
"simplejson._speedups.Scanner", /* tp_name */
sizeof(PyScannerObject), /* tp_basicsize */
0, /* tp_itemsize */
scanner_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
scanner_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
scanner_doc, /* tp_doc */
scanner_traverse, /* tp_traverse */
scanner_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
scanner_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
scanner_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
scanner_new, /* tp_new */
0,/* PyObject_GC_Del, */ /* tp_free */
};
static PyObject *
encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyEncoderObject *s;
s = (PyEncoderObject *)type->tp_alloc(type, 0);
if (s != NULL) {
s->markers = NULL;
s->defaultfn = NULL;
s->encoder = NULL;
s->indent = NULL;
s->key_separator = NULL;
s->item_separator = NULL;
s->sort_keys = NULL;
s->skipkeys = NULL;
s->key_memo = NULL;
s->item_sort_key = NULL;
s->Decimal = NULL;
}
return (PyObject *)s;
}
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", "key_memo", "use_decimal", "namedtuple_as_object", "tuple_as_array", "bigint_as_string", "item_sort_key", "Decimal", NULL};
PyEncoderObject *s;
PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan, *key_memo;
PyObject *use_decimal, *namedtuple_as_object, *tuple_as_array;
PyObject *bigint_as_string, *item_sort_key, *Decimal;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOOOOOOOO:make_encoder", kwlist,
&markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
&sort_keys, &skipkeys, &allow_nan, &key_memo, &use_decimal,
&namedtuple_as_object, &tuple_as_array, &bigint_as_string,
&item_sort_key, &Decimal))
return -1;
s->markers = markers;
s->defaultfn = defaultfn;
s->encoder = encoder;
s->indent = indent;
s->key_separator = key_separator;
s->item_separator = item_separator;
s->sort_keys = sort_keys;
s->skipkeys = skipkeys;
s->key_memo = key_memo;
s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
s->allow_nan = PyObject_IsTrue(allow_nan);
s->use_decimal = PyObject_IsTrue(use_decimal);
s->namedtuple_as_object = PyObject_IsTrue(namedtuple_as_object);
s->tuple_as_array = PyObject_IsTrue(tuple_as_array);
s->bigint_as_string = PyObject_IsTrue(bigint_as_string);
s->item_sort_key = item_sort_key;
s->Decimal = Decimal;
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
Py_INCREF(s->encoder);
Py_INCREF(s->indent);
Py_INCREF(s->key_separator);
Py_INCREF(s->item_separator);
Py_INCREF(s->sort_keys);
Py_INCREF(s->skipkeys);
Py_INCREF(s->key_memo);
Py_INCREF(s->item_sort_key);
Py_INCREF(s->Decimal);
return 0;
}
static PyObject *
encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to encode_listencode_obj */
static char *kwlist[] = {"obj", "_current_indent_level", NULL};
PyObject *obj;
PyObject *rval;
Py_ssize_t indent_level;
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
&obj, _convertPyInt_AsSsize_t, &indent_level))
return NULL;
rval = PyList_New(0);
if (rval == NULL)
return NULL;
if (encoder_listencode_obj(s, rval, obj, indent_level)) {
Py_DECREF(rval);
return NULL;
}
return rval;
}
static PyObject *
_encoded_const(PyObject *obj)
{
/* Return the JSON string representation of None, True, False */
if (obj == Py_None) {
static PyObject *s_null = NULL;
if (s_null == NULL) {
s_null = PyString_InternFromString("null");
}
Py_INCREF(s_null);
return s_null;
}
else if (obj == Py_True) {
static PyObject *s_true = NULL;
if (s_true == NULL) {
s_true = PyString_InternFromString("true");
}
Py_INCREF(s_true);
return s_true;
}
else if (obj == Py_False) {
static PyObject *s_false = NULL;
if (s_false == NULL) {
s_false = PyString_InternFromString("false");
}
Py_INCREF(s_false);
return s_false;
}
else {
PyErr_SetString(PyExc_ValueError, "not a const");
return NULL;
}
}
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyString_FromString("Infinity");
}
else if (i < 0) {
return PyString_FromString("-Infinity");
}
else {
return PyString_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a string */
if (s->fast_encode)
return py_encode_basestring_ascii(NULL, obj);
else
return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
}
static int
_steal_list_append(PyObject *lst, PyObject *stolen)
{
/* Append stolen and then decrement its reference count */
int rval = PyList_Append(lst, stolen);
Py_DECREF(stolen);
return rval;
}
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
{
/* Encode Python object obj to a JSON term, rval is a PyList */
int rv = -1;
if (Py_EnterRecursiveCall(" while encoding a JSON document"))
return rv;
do {
if (obj == Py_None || obj == Py_True || obj == Py_False) {
PyObject *cstr = _encoded_const(obj);
if (cstr != NULL)
rv = _steal_list_append(rval, cstr);
}
else if (PyString_Check(obj) || PyUnicode_Check(obj))
{
PyObject *encoded = encoder_encode_string(s, obj);
if (encoded != NULL)
rv = _steal_list_append(rval, encoded);
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded != NULL) {
if (s->bigint_as_string) {
encoded = maybe_quote_bigint(encoded, obj);
if (encoded == NULL)
break;
}
rv = _steal_list_append(rval, encoded);
}
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
if (encoded != NULL)
rv = _steal_list_append(rval, encoded);
}
else if (s->namedtuple_as_object && _is_namedtuple(obj)) {
PyObject *newobj = PyObject_CallMethod(obj, "_asdict", NULL);
if (newobj != NULL) {
rv = encoder_listencode_dict(s, rval, newobj, indent_level);
Py_DECREF(newobj);
}
}
else if (PyList_Check(obj) || (s->tuple_as_array && PyTuple_Check(obj))) {
rv = encoder_listencode_list(s, rval, obj, indent_level);
}
else if (PyDict_Check(obj)) {
rv = encoder_listencode_dict(s, rval, obj, indent_level);
}
else if (s->use_decimal && PyObject_TypeCheck(obj, s->Decimal)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded != NULL)
rv = _steal_list_append(rval, encoded);
}
else {
PyObject *ident = NULL;
PyObject *newobj;
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(obj);
if (ident == NULL)
break;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
Py_DECREF(ident);
break;
}
if (PyDict_SetItem(s->markers, ident, obj)) {
Py_DECREF(ident);
break;
}
}
newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
if (newobj == NULL) {
Py_XDECREF(ident);
break;
}
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
rv = -1;
}
else if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident)) {
Py_XDECREF(ident);
rv = -1;
}
Py_XDECREF(ident);
}
}
} while (0);
Py_LeaveRecursiveCall();
return rv;
}
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
{
/* Encode Python dict dct a JSON term, rval is a PyList */
static PyObject *open_dict = NULL;
static PyObject *close_dict = NULL;
static PyObject *empty_dict = NULL;
static PyObject *iteritems = NULL;
PyObject *kstr = NULL;
PyObject *ident = NULL;
PyObject *iter = NULL;
PyObject *item = NULL;
PyObject *items = NULL;
PyObject *encoded = NULL;
int skipkeys;
Py_ssize_t idx;
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL || iteritems == NULL) {
open_dict = PyString_InternFromString("{");
close_dict = PyString_InternFromString("}");
empty_dict = PyString_InternFromString("{}");
iteritems = PyString_InternFromString("iteritems");
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL || iteritems == NULL)
return -1;
}
if (PyDict_Size(dct) == 0)
return PyList_Append(rval, empty_dict);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(dct);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, dct)) {
goto bail;
}
}
if (PyList_Append(rval, open_dict))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (_indent * _current_indent_level)
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
if (PyCallable_Check(s->item_sort_key)) {
if (PyDict_CheckExact(dct))
items = PyDict_Items(dct);
else
items = PyMapping_Items(dct);
PyObject_CallMethod(items, "sort", "OO", Py_None, s->item_sort_key);
}
else if (PyObject_IsTrue(s->sort_keys)) {
/* First sort the keys then replace them with (key, value) tuples. */
Py_ssize_t i, nitems;
if (PyDict_CheckExact(dct))
items = PyDict_Keys(dct);
else
items = PyMapping_Keys(dct);
if (items == NULL)
goto bail;
if (!PyList_Check(items)) {
PyErr_SetString(PyExc_ValueError, "keys must return list");
goto bail;
}
if (PyList_Sort(items) < 0)
goto bail;
nitems = PyList_GET_SIZE(items);
for (i = 0; i < nitems; i++) {
PyObject *key, *value;
key = PyList_GET_ITEM(items, i);
value = PyDict_GetItem(dct, key);
item = PyTuple_Pack(2, key, value);
if (item == NULL)
goto bail;
PyList_SET_ITEM(items, i, item);
Py_DECREF(key);
}
}
else {
if (PyDict_CheckExact(dct))
items = PyDict_Items(dct);
else
items = PyMapping_Items(dct);
}
if (items == NULL)
goto bail;
iter = PyObject_GetIter(items);
Py_DECREF(items);
if (iter == NULL)
goto bail;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
while ((item = PyIter_Next(iter))) {
PyObject *encoded, *key, *value;
if (!PyTuple_Check(item) || Py_SIZE(item) != 2) {
PyErr_SetString(PyExc_ValueError, "items must return 2-tuples");
goto bail;
}
key = PyTuple_GET_ITEM(item, 0);
if (key == NULL)
goto bail;
value = PyTuple_GET_ITEM(item, 1);
if (value == NULL)
goto bail;
encoded = PyDict_GetItem(s->key_memo, key);
if (encoded != NULL) {
Py_INCREF(encoded);
}
else if (PyString_Check(key) || PyUnicode_Check(key)) {
Py_INCREF(key);
kstr = key;
}
else if (PyFloat_Check(key)) {
kstr = encoder_encode_float(s, key);
if (kstr == NULL)
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
/* This must come before the PyInt_Check because
True and False are also 1 and 0.*/
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
}
else if (PyInt_Check(key) || PyLong_Check(key)) {
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
}
else if (skipkeys) {
Py_DECREF(item);
continue;
}
else {
/* TODO: include repr of key */
PyErr_SetString(PyExc_TypeError, "keys must be a string");
goto bail;
}
if (idx) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoded == NULL) {
encoded = encoder_encode_string(s, kstr);
Py_CLEAR(kstr);
if (encoded == NULL)
goto bail;
if (PyDict_SetItem(s->key_memo, key, encoded))
goto bail;
}
if (PyList_Append(rval, encoded)) {
goto bail;
}
Py_CLEAR(encoded);
if (PyList_Append(rval, s->key_separator))
goto bail;
if (encoder_listencode_obj(s, rval, value, indent_level))
goto bail;
Py_CLEAR(item);
idx += 1;
}
Py_CLEAR(iter);
if (PyErr_Occurred())
goto bail;
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (_indent * _current_indent_level)
*/
}
if (PyList_Append(rval, close_dict))
goto bail;
return 0;
bail:
Py_XDECREF(encoded);
Py_XDECREF(items);
Py_XDECREF(iter);
Py_XDECREF(kstr);
Py_XDECREF(ident);
return -1;
}
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
{
/* Encode Python list seq to a JSON term, rval is a PyList */
static PyObject *open_array = NULL;
static PyObject *close_array = NULL;
static PyObject *empty_array = NULL;
PyObject *ident = NULL;
PyObject *iter = NULL;
PyObject *obj = NULL;
int is_true;
int i = 0;
if (open_array == NULL || close_array == NULL || empty_array == NULL) {
open_array = PyString_InternFromString("[");
close_array = PyString_InternFromString("]");
empty_array = PyString_InternFromString("[]");
if (open_array == NULL || close_array == NULL || empty_array == NULL)
return -1;
}
ident = NULL;
is_true = PyObject_IsTrue(seq);
if (is_true == -1)
return -1;
else if (is_true == 0)
return PyList_Append(rval, empty_array);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(seq);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, seq)) {
goto bail;
}
}
iter = PyObject_GetIter(seq);
if (iter == NULL)
goto bail;
if (PyList_Append(rval, open_array))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (_indent * _current_indent_level)
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
while ((obj = PyIter_Next(iter))) {
if (i) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoder_listencode_obj(s, rval, obj, indent_level))
goto bail;
i++;
Py_CLEAR(obj);
}
Py_CLEAR(iter);
if (PyErr_Occurred())
goto bail;
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (_indent * _current_indent_level)
*/
}
if (PyList_Append(rval, close_array))
goto bail;
return 0;
bail:
Py_XDECREF(obj);
Py_XDECREF(iter);
Py_XDECREF(ident);
return -1;
}
static void
encoder_dealloc(PyObject *self)
{
/* Deallocate Encoder */
encoder_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
encoder_traverse(PyObject *self, visitproc visit, void *arg)
{
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_VISIT(s->markers);
Py_VISIT(s->defaultfn);
Py_VISIT(s->encoder);
Py_VISIT(s->indent);
Py_VISIT(s->key_separator);
Py_VISIT(s->item_separator);
Py_VISIT(s->sort_keys);
Py_VISIT(s->skipkeys);
Py_VISIT(s->key_memo);
Py_VISIT(s->item_sort_key);
return 0;
}
static int
encoder_clear(PyObject *self)
{
/* Deallocate Encoder */
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_CLEAR(s->markers);
Py_CLEAR(s->defaultfn);
Py_CLEAR(s->encoder);
Py_CLEAR(s->indent);
Py_CLEAR(s->key_separator);
Py_CLEAR(s->item_separator);
Py_CLEAR(s->sort_keys);
Py_CLEAR(s->skipkeys);
Py_CLEAR(s->key_memo);
Py_CLEAR(s->item_sort_key);
Py_CLEAR(s->Decimal);
return 0;
}
PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
static
PyTypeObject PyEncoderType = {
PyObject_HEAD_INIT(NULL)
0, /* tp_internal */
"simplejson._speedups.Encoder", /* tp_name */
sizeof(PyEncoderObject), /* tp_basicsize */
0, /* tp_itemsize */
encoder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
encoder_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
encoder_doc, /* tp_doc */
encoder_traverse, /* tp_traverse */
encoder_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
encoder_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
encoder_init, /* tp_init */
0, /* tp_alloc */
encoder_new, /* tp_new */
0, /* tp_free */
};
static PyMethodDef speedups_methods[] = {
{"encode_basestring_ascii",
(PyCFunction)py_encode_basestring_ascii,
METH_O,
pydoc_encode_basestring_ascii},
{"scanstring",
(PyCFunction)py_scanstring,
METH_VARARGS,
pydoc_scanstring},
{NULL, NULL, 0, NULL}
};
PyDoc_STRVAR(module_doc,
"simplejson speedups\n");
void
init_speedups(void)
{
PyObject *m;
PyScannerType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PyScannerType) < 0)
return;
PyEncoderType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PyEncoderType) < 0)
return;
m = Py_InitModule3("_speedups", speedups_methods, module_doc);
Py_INCREF((PyObject*)&PyScannerType);
PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
Py_INCREF((PyObject*)&PyEncoderType);
PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
}
| bsd-3-clause |
Omegaphora/external_speex | libspeex/exc_5_256_table.c | 1000 | 6096 | /* Copyright (C) 2002 Jean-Marc Valin
File: exc_5_256_table.c
Codebook for excitation in narrowband CELP mode (12800 bps)
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 the Xiph.org Foundation 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 FOUNDATION 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.
*/
const signed char exc_5_256_table[1280] = {
-8,-37,5,-43,5,
73,61,39,12,-3,
-61,-32,2,42,30,
-3,17,-27,9,34,
20,-1,-5,2,23,
-7,-46,26,53,-47,
20,-2,-33,-89,-51,
-64,27,11,15,-34,
-5,-56,25,-9,-1,
-29,1,40,67,-23,
-16,16,33,19,7,
14,85,22,-10,-10,
-12,-7,-1,52,89,
29,11,-20,-37,-46,
-15,17,-24,-28,24,
2,1,0,23,-101,
23,14,-1,-23,-18,
9,5,-13,38,1,
-28,-28,4,27,51,
-26,34,-40,35,47,
54,38,-54,-26,-6,
42,-25,13,-30,-36,
18,41,-4,-33,23,
-32,-7,-4,51,-3,
17,-52,56,-47,36,
-2,-21,36,10,8,
-33,31,19,9,-5,
-40,10,-9,-21,19,
18,-78,-18,-5,0,
-26,-36,-47,-51,-44,
18,40,27,-2,29,
49,-26,2,32,-54,
30,-73,54,3,-5,
36,22,53,10,-1,
-84,-53,-29,-5,3,
-44,53,-51,4,22,
71,-35,-1,33,-5,
-27,-7,36,17,-23,
-39,16,-9,-55,-15,
-20,39,-35,6,-39,
-14,18,48,-64,-17,
-15,9,39,81,37,
-68,37,47,-21,-6,
-104,13,6,9,-2,
35,8,-23,18,42,
45,21,33,-5,-49,
9,-6,-43,-56,39,
2,-16,-25,87,1,
-3,-9,17,-25,-11,
-9,-1,10,2,-14,
-14,4,-1,-10,28,
-23,40,-32,26,-9,
26,4,-27,-23,3,
42,-60,1,49,-3,
27,10,-52,-40,-2,
18,45,-23,17,-44,
3,-3,17,-46,52,
-40,-47,25,75,31,
-49,53,30,-30,-32,
-36,38,-6,-15,-16,
54,-27,-48,3,38,
-29,-32,-22,-14,-4,
-23,-13,32,-39,9,
8,-45,-13,34,-16,
49,40,32,31,28,
23,23,32,47,59,
-68,8,62,44,25,
-14,-24,-65,-16,36,
67,-25,-38,-21,4,
-33,-2,42,5,-63,
40,11,26,-42,-23,
-61,79,-31,23,-20,
10,-32,53,-25,-36,
10,-26,-5,3,0,
-71,5,-10,-37,1,
-24,21,-54,-17,1,
-29,-25,-15,-27,32,
68,45,-16,-37,-18,
-5,1,0,-77,71,
-6,3,-20,71,-67,
29,-35,10,-30,19,
4,16,17,5,0,
-14,19,2,28,26,
59,3,2,24,39,
55,-50,-45,-18,-17,
33,-35,14,-1,1,
8,87,-35,-29,0,
-27,13,-7,23,-13,
37,-40,50,-35,14,
19,-7,-14,49,54,
-5,22,-2,-29,-8,
-27,38,13,27,48,
12,-41,-21,-15,28,
7,-16,-24,-19,-20,
11,-20,9,2,13,
23,-20,11,27,-27,
71,-69,8,2,-6,
22,12,16,16,9,
-16,-8,-17,1,25,
1,40,-37,-33,66,
94,53,4,-22,-25,
-41,-42,25,35,-16,
-15,57,31,-29,-32,
21,16,-60,45,15,
-1,7,57,-26,-47,
-29,11,8,15,19,
-105,-8,54,27,10,
-17,6,-12,-1,-10,
4,0,23,-10,31,
13,11,10,12,-64,
23,-3,-8,-19,16,
52,24,-40,16,10,
40,5,9,0,-13,
-7,-21,-8,-6,-7,
-21,59,16,-53,18,
-60,11,-47,14,-18,
25,-13,-24,4,-39,
16,-28,54,26,-67,
30,27,-20,-52,20,
-12,55,12,18,-16,
39,-14,-6,-26,56,
-88,-55,12,25,26,
-37,6,75,0,-34,
-81,54,-30,1,-7,
49,-23,-14,21,10,
-62,-58,-57,-47,-34,
15,-4,34,-78,31,
25,-11,7,50,-10,
42,-63,14,-36,-4,
57,55,57,53,42,
-42,-1,15,40,37,
15,25,-11,6,1,
31,-2,-6,-1,-7,
-64,34,28,30,-1,
3,21,0,-88,-12,
-56,25,-28,40,8,
-28,-14,9,12,2,
-6,-17,22,49,-6,
-26,14,28,-20,4,
-12,50,35,40,13,
-38,-58,-29,17,30,
22,60,26,-54,-39,
-12,58,-28,-63,10,
-21,-8,-12,26,-62,
6,-10,-11,-22,-6,
-7,4,1,18,2,
-70,11,14,4,13,
19,-24,-34,24,67,
17,51,-21,13,23,
54,-30,48,1,-13,
80,26,-16,-2,13,
-4,6,-30,29,-24,
73,-58,30,-27,20,
-2,-21,41,45,30,
-27,-3,-5,-18,-20,
-49,-3,-35,10,42,
-19,-67,-53,-11,9,
13,-15,-33,-51,-30,
15,7,25,-30,4,
28,-22,-34,54,-29,
39,-46,20,16,34,
-4,47,75,1,-44,
-55,-24,7,-1,9,
-42,50,-8,-36,41,
68,0,-4,-10,-23,
-15,-50,64,36,-9,
-27,12,25,-38,-47,
-37,32,-49,51,-36,
2,-4,69,-26,19,
7,45,67,46,13,
-63,46,15,-47,4,
-41,13,-6,5,-21,
37,26,-55,-7,33,
-1,-28,10,-17,-64,
-14,0,-36,-17,93,
-3,-9,-66,44,-21,
3,-12,38,-6,-13,
-12,19,13,43,-43,
-10,-12,6,-5,9,
-49,32,-5,2,4,
5,15,-16,10,-21,
8,-62,-8,64,8,
79,-1,-66,-49,-18,
5,40,-5,-30,-45,
1,-6,21,-32,93,
-18,-30,-21,32,21,
-18,22,8,5,-41,
-54,80,22,-10,-7,
-8,-23,-64,66,56,
-14,-30,-41,-46,-14,
-29,-37,27,-14,42,
-2,-9,-29,34,14,
33,-14,22,4,10,
26,26,28,32,23,
-72,-32,3,0,-14,
35,-42,-78,-32,6,
29,-18,-45,-5,7,
-33,-45,-3,-22,-34,
8,-8,4,-51,-25,
-9,59,-78,21,-5,
-25,-48,66,-15,-17,
-24,-49,-13,25,-23,
-64,-6,40,-24,-19,
-11,57,-33,-8,1,
10,-52,-54,28,39,
49,34,-11,-61,-41,
-43,10,15,-15,51,
30,15,-51,32,-34,
-2,-34,14,18,16,
1,1,-3,-3,1,
1,-18,6,16,48,
12,-5,-42,7,36,
48,7,-20,-10,7,
12,2,54,39,-38,
37,54,4,-11,-8,
-46,-10,5,-10,-34,
46,-12,29,-37,39,
36,-11,24,56,17,
14,20,25,0,-25,
-28,55,-7,-5,27,
3,9,-26,-8,6,
-24,-10,-30,-31,-34,
18,4,22,21,40,
-1,-29,-37,-8,-21,
92,-29,11,-3,11,
73,23,22,7,4,
-44,-9,-11,21,-13,
11,9,-78,-1,47,
114,-12,-37,-19,-5,
-11,-22,19,12,-30,
7,38,45,-21,-8,
-9,55,-45,56,-21,
7,17,46,-57,-87,
-6,27,31,31,7,
-56,-12,46,21,-5,
-12,36,3,3,-21,
43,19,12,-7,9,
-14,0,-9,-33,-91,
7,26,3,-11,64,
83,-31,-46,25,2,
9,5,2,2,-1,
20,-17,10,-5,-27,
-8,20,8,-19,16,
-21,-13,-31,5,5,
42,24,9,34,-20,
28,-61,22,11,-39,
64,-20,-1,-30,-9,
-20,24,-25,-24,-29,
22,-60,6,-5,41,
-9,-87,14,34,15,
-57,52,69,15,-3,
-102,58,16,3,6,
60,-75,-32,26,7,
-57,-27,-32,-24,-21,
-29,-16,62,-46,31,
30,-27,-15,7,15};
| bsd-3-clause |
sgraham/nope | third_party/opus/src/silk/enc_API.c | 250 | 30333 | /***********************************************************************
Copyright (c) 2006-2011, Skype Limited. 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.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "define.h"
#include "API.h"
#include "control.h"
#include "typedef.h"
#include "stack_alloc.h"
#include "structs.h"
#include "tuning_parameters.h"
#ifdef FIXED_POINT
#include "main_FIX.h"
#else
#include "main_FLP.h"
#endif
/***************************************/
/* Read control structure from encoder */
/***************************************/
static opus_int silk_QueryEncoder( /* O Returns error code */
const void *encState, /* I State */
silk_EncControlStruct *encStatus /* O Encoder Status */
);
/****************************************/
/* Encoder functions */
/****************************************/
opus_int silk_Get_Encoder_Size( /* O Returns error code */
opus_int *encSizeBytes /* O Number of bytes in SILK encoder state */
)
{
opus_int ret = SILK_NO_ERROR;
*encSizeBytes = sizeof( silk_encoder );
return ret;
}
/*************************/
/* Init or Reset encoder */
/*************************/
opus_int silk_InitEncoder( /* O Returns error code */
void *encState, /* I/O State */
int arch, /* I Run-time architecture */
silk_EncControlStruct *encStatus /* O Encoder Status */
)
{
silk_encoder *psEnc;
opus_int n, ret = SILK_NO_ERROR;
psEnc = (silk_encoder *)encState;
/* Reset encoder */
silk_memset( psEnc, 0, sizeof( silk_encoder ) );
for( n = 0; n < ENCODER_NUM_CHANNELS; n++ ) {
if( ret += silk_init_encoder( &psEnc->state_Fxx[ n ], arch ) ) {
silk_assert( 0 );
}
}
psEnc->nChannelsAPI = 1;
psEnc->nChannelsInternal = 1;
/* Read control structure */
if( ret += silk_QueryEncoder( encState, encStatus ) ) {
silk_assert( 0 );
}
return ret;
}
/***************************************/
/* Read control structure from encoder */
/***************************************/
static opus_int silk_QueryEncoder( /* O Returns error code */
const void *encState, /* I State */
silk_EncControlStruct *encStatus /* O Encoder Status */
)
{
opus_int ret = SILK_NO_ERROR;
silk_encoder_state_Fxx *state_Fxx;
silk_encoder *psEnc = (silk_encoder *)encState;
state_Fxx = psEnc->state_Fxx;
encStatus->nChannelsAPI = psEnc->nChannelsAPI;
encStatus->nChannelsInternal = psEnc->nChannelsInternal;
encStatus->API_sampleRate = state_Fxx[ 0 ].sCmn.API_fs_Hz;
encStatus->maxInternalSampleRate = state_Fxx[ 0 ].sCmn.maxInternal_fs_Hz;
encStatus->minInternalSampleRate = state_Fxx[ 0 ].sCmn.minInternal_fs_Hz;
encStatus->desiredInternalSampleRate = state_Fxx[ 0 ].sCmn.desiredInternal_fs_Hz;
encStatus->payloadSize_ms = state_Fxx[ 0 ].sCmn.PacketSize_ms;
encStatus->bitRate = state_Fxx[ 0 ].sCmn.TargetRate_bps;
encStatus->packetLossPercentage = state_Fxx[ 0 ].sCmn.PacketLoss_perc;
encStatus->complexity = state_Fxx[ 0 ].sCmn.Complexity;
encStatus->useInBandFEC = state_Fxx[ 0 ].sCmn.useInBandFEC;
encStatus->useDTX = state_Fxx[ 0 ].sCmn.useDTX;
encStatus->useCBR = state_Fxx[ 0 ].sCmn.useCBR;
encStatus->internalSampleRate = silk_SMULBB( state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
encStatus->allowBandwidthSwitch = state_Fxx[ 0 ].sCmn.allow_bandwidth_switch;
encStatus->inWBmodeWithoutVariableLP = state_Fxx[ 0 ].sCmn.fs_kHz == 16 && state_Fxx[ 0 ].sCmn.sLP.mode == 0;
return ret;
}
/**************************/
/* Encode frame with Silk */
/**************************/
/* Note: if prefillFlag is set, the input must contain 10 ms of audio, irrespective of what */
/* encControl->payloadSize_ms is set to */
opus_int silk_Encode( /* O Returns error code */
void *encState, /* I/O State */
silk_EncControlStruct *encControl, /* I Control status */
const opus_int16 *samplesIn, /* I Speech sample input vector */
opus_int nSamplesIn, /* I Number of samples in input vector */
ec_enc *psRangeEnc, /* I/O Compressor data structure */
opus_int32 *nBytesOut, /* I/O Number of bytes in payload (input: Max bytes) */
const opus_int prefillFlag /* I Flag to indicate prefilling buffers no coding */
)
{
opus_int n, i, nBits, flags, tmp_payloadSize_ms = 0, tmp_complexity = 0, ret = 0;
opus_int nSamplesToBuffer, nSamplesToBufferMax, nBlocksOf10ms;
opus_int nSamplesFromInput = 0, nSamplesFromInputMax;
opus_int speech_act_thr_for_switch_Q8;
opus_int32 TargetRate_bps, MStargetRates_bps[ 2 ], channelRate_bps, LBRR_symbol, sum;
silk_encoder *psEnc = ( silk_encoder * )encState;
VARDECL( opus_int16, buf );
opus_int transition, curr_block, tot_blocks;
SAVE_STACK;
if (encControl->reducedDependency)
{
psEnc->state_Fxx[0].sCmn.first_frame_after_reset = 1;
psEnc->state_Fxx[1].sCmn.first_frame_after_reset = 1;
}
psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded = psEnc->state_Fxx[ 1 ].sCmn.nFramesEncoded = 0;
/* Check values in encoder control structure */
if( ( ret = check_control_input( encControl ) != 0 ) ) {
silk_assert( 0 );
RESTORE_STACK;
return ret;
}
encControl->switchReady = 0;
if( encControl->nChannelsInternal > psEnc->nChannelsInternal ) {
/* Mono -> Stereo transition: init state of second channel and stereo state */
ret += silk_init_encoder( &psEnc->state_Fxx[ 1 ], psEnc->state_Fxx[ 0 ].sCmn.arch );
silk_memset( psEnc->sStereo.pred_prev_Q13, 0, sizeof( psEnc->sStereo.pred_prev_Q13 ) );
silk_memset( psEnc->sStereo.sSide, 0, sizeof( psEnc->sStereo.sSide ) );
psEnc->sStereo.mid_side_amp_Q0[ 0 ] = 0;
psEnc->sStereo.mid_side_amp_Q0[ 1 ] = 1;
psEnc->sStereo.mid_side_amp_Q0[ 2 ] = 0;
psEnc->sStereo.mid_side_amp_Q0[ 3 ] = 1;
psEnc->sStereo.width_prev_Q14 = 0;
psEnc->sStereo.smth_width_Q14 = SILK_FIX_CONST( 1, 14 );
if( psEnc->nChannelsAPI == 2 ) {
silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof( silk_resampler_state_struct ) );
silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.In_HP_State, &psEnc->state_Fxx[ 0 ].sCmn.In_HP_State, sizeof( psEnc->state_Fxx[ 1 ].sCmn.In_HP_State ) );
}
}
transition = (encControl->payloadSize_ms != psEnc->state_Fxx[ 0 ].sCmn.PacketSize_ms) || (psEnc->nChannelsInternal != encControl->nChannelsInternal);
psEnc->nChannelsAPI = encControl->nChannelsAPI;
psEnc->nChannelsInternal = encControl->nChannelsInternal;
nBlocksOf10ms = silk_DIV32( 100 * nSamplesIn, encControl->API_sampleRate );
tot_blocks = ( nBlocksOf10ms > 1 ) ? nBlocksOf10ms >> 1 : 1;
curr_block = 0;
if( prefillFlag ) {
/* Only accept input length of 10 ms */
if( nBlocksOf10ms != 1 ) {
silk_assert( 0 );
RESTORE_STACK;
return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
}
/* Reset Encoder */
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
ret = silk_init_encoder( &psEnc->state_Fxx[ n ], psEnc->state_Fxx[ n ].sCmn.arch );
silk_assert( !ret );
}
tmp_payloadSize_ms = encControl->payloadSize_ms;
encControl->payloadSize_ms = 10;
tmp_complexity = encControl->complexity;
encControl->complexity = 0;
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
psEnc->state_Fxx[ n ].sCmn.prefillFlag = 1;
}
} else {
/* Only accept input lengths that are a multiple of 10 ms */
if( nBlocksOf10ms * encControl->API_sampleRate != 100 * nSamplesIn || nSamplesIn < 0 ) {
silk_assert( 0 );
RESTORE_STACK;
return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
}
/* Make sure no more than one packet can be produced */
if( 1000 * (opus_int32)nSamplesIn > encControl->payloadSize_ms * encControl->API_sampleRate ) {
silk_assert( 0 );
RESTORE_STACK;
return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
}
}
TargetRate_bps = silk_RSHIFT32( encControl->bitRate, encControl->nChannelsInternal - 1 );
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
/* Force the side channel to the same rate as the mid */
opus_int force_fs_kHz = (n==1) ? psEnc->state_Fxx[0].sCmn.fs_kHz : 0;
if( ( ret = silk_control_encoder( &psEnc->state_Fxx[ n ], encControl, TargetRate_bps, psEnc->allowBandwidthSwitch, n, force_fs_kHz ) ) != 0 ) {
silk_assert( 0 );
RESTORE_STACK;
return ret;
}
if( psEnc->state_Fxx[n].sCmn.first_frame_after_reset || transition ) {
for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] = 0;
}
}
psEnc->state_Fxx[ n ].sCmn.inDTX = psEnc->state_Fxx[ n ].sCmn.useDTX;
}
silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );
/* Input buffering/resampling and encoding */
nSamplesToBufferMax =
10 * nBlocksOf10ms * psEnc->state_Fxx[ 0 ].sCmn.fs_kHz;
nSamplesFromInputMax =
silk_DIV32_16( nSamplesToBufferMax *
psEnc->state_Fxx[ 0 ].sCmn.API_fs_Hz,
psEnc->state_Fxx[ 0 ].sCmn.fs_kHz * 1000 );
ALLOC( buf, nSamplesFromInputMax, opus_int16 );
while( 1 ) {
nSamplesToBuffer = psEnc->state_Fxx[ 0 ].sCmn.frame_length - psEnc->state_Fxx[ 0 ].sCmn.inputBufIx;
nSamplesToBuffer = silk_min( nSamplesToBuffer, nSamplesToBufferMax );
nSamplesFromInput = silk_DIV32_16( nSamplesToBuffer * psEnc->state_Fxx[ 0 ].sCmn.API_fs_Hz, psEnc->state_Fxx[ 0 ].sCmn.fs_kHz * 1000 );
/* Resample and write to buffer */
if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 2 ) {
opus_int id = psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded;
for( n = 0; n < nSamplesFromInput; n++ ) {
buf[ n ] = samplesIn[ 2 * n ];
}
/* Making sure to start both resamplers from the same state when switching from mono to stereo */
if( psEnc->nPrevChannelsInternal == 1 && id==0 ) {
silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof(psEnc->state_Fxx[ 1 ].sCmn.resampler_state));
}
ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
&psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
nSamplesToBuffer = psEnc->state_Fxx[ 1 ].sCmn.frame_length - psEnc->state_Fxx[ 1 ].sCmn.inputBufIx;
nSamplesToBuffer = silk_min( nSamplesToBuffer, 10 * nBlocksOf10ms * psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );
for( n = 0; n < nSamplesFromInput; n++ ) {
buf[ n ] = samplesIn[ 2 * n + 1 ];
}
ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
&psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
psEnc->state_Fxx[ 1 ].sCmn.inputBufIx += nSamplesToBuffer;
} else if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 1 ) {
/* Combine left and right channels before resampling */
for( n = 0; n < nSamplesFromInput; n++ ) {
sum = samplesIn[ 2 * n ] + samplesIn[ 2 * n + 1 ];
buf[ n ] = (opus_int16)silk_RSHIFT_ROUND( sum, 1 );
}
ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
&psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
/* On the first mono frame, average the results for the two resampler states */
if( psEnc->nPrevChannelsInternal == 2 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 ) {
ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
&psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
for( n = 0; n < psEnc->state_Fxx[ 0 ].sCmn.frame_length; n++ ) {
psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ] =
silk_RSHIFT(psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ]
+ psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx+n+2 ], 1);
}
}
psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
} else {
silk_assert( encControl->nChannelsAPI == 1 && encControl->nChannelsInternal == 1 );
silk_memcpy(buf, samplesIn, nSamplesFromInput*sizeof(opus_int16));
ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
&psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
}
samplesIn += nSamplesFromInput * encControl->nChannelsAPI;
nSamplesIn -= nSamplesFromInput;
/* Default */
psEnc->allowBandwidthSwitch = 0;
/* Silk encoder */
if( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx >= psEnc->state_Fxx[ 0 ].sCmn.frame_length ) {
/* Enough data in input buffer, so encode */
silk_assert( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx == psEnc->state_Fxx[ 0 ].sCmn.frame_length );
silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inputBufIx == psEnc->state_Fxx[ 1 ].sCmn.frame_length );
/* Deal with LBRR data */
if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 && !prefillFlag ) {
/* Create space at start of payload for VAD and FEC flags */
opus_uint8 iCDF[ 2 ] = { 0, 0 };
iCDF[ 0 ] = 256 - silk_RSHIFT( 256, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
ec_enc_icdf( psRangeEnc, 0, iCDF, 8 );
/* Encode any LBRR data from previous packet */
/* Encode LBRR flags */
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
LBRR_symbol = 0;
for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
LBRR_symbol |= silk_LSHIFT( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ], i );
}
psEnc->state_Fxx[ n ].sCmn.LBRR_flag = LBRR_symbol > 0 ? 1 : 0;
if( LBRR_symbol && psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket > 1 ) {
ec_enc_icdf( psRangeEnc, LBRR_symbol - 1, silk_LBRR_flags_iCDF_ptr[ psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket - 2 ], 8 );
}
}
/* Code LBRR indices and excitation signals */
for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
if( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] ) {
opus_int condCoding;
if( encControl->nChannelsInternal == 2 && n == 0 ) {
silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ i ] );
/* For LBRR data there's no need to code the mid-only flag if the side-channel LBRR flag is set */
if( psEnc->state_Fxx[ 1 ].sCmn.LBRR_flags[ i ] == 0 ) {
silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ i ] );
}
}
/* Use conditional coding if previous frame available */
if( i > 0 && psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i - 1 ] ) {
condCoding = CODE_CONDITIONALLY;
} else {
condCoding = CODE_INDEPENDENTLY;
}
silk_encode_indices( &psEnc->state_Fxx[ n ].sCmn, psRangeEnc, i, 1, condCoding );
silk_encode_pulses( psRangeEnc, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].signalType, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].quantOffsetType,
psEnc->state_Fxx[ n ].sCmn.pulses_LBRR[ i ], psEnc->state_Fxx[ n ].sCmn.frame_length );
}
}
}
/* Reset LBRR flags */
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
silk_memset( psEnc->state_Fxx[ n ].sCmn.LBRR_flags, 0, sizeof( psEnc->state_Fxx[ n ].sCmn.LBRR_flags ) );
}
}
silk_HP_variable_cutoff( psEnc->state_Fxx );
/* Total target bits for packet */
nBits = silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
/* Subtract half of the bits already used */
if( !prefillFlag ) {
nBits -= ec_tell( psRangeEnc ) >> 1;
}
/* Divide by number of uncoded frames left in packet */
nBits = silk_DIV32_16( nBits, psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket - psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded );
/* Convert to bits/second */
if( encControl->payloadSize_ms == 10 ) {
TargetRate_bps = silk_SMULBB( nBits, 100 );
} else {
TargetRate_bps = silk_SMULBB( nBits, 50 );
}
/* Subtract fraction of bits in excess of target in previous packets */
TargetRate_bps -= silk_DIV32_16( silk_MUL( psEnc->nBitsExceeded, 1000 ), BITRESERVOIR_DECAY_TIME_MS );
/* Never exceed input bitrate */
TargetRate_bps = silk_LIMIT( TargetRate_bps, encControl->bitRate, 5000 );
/* Convert Left/Right to Mid/Side */
if( encControl->nChannelsInternal == 2 ) {
silk_stereo_LR_to_MS( &psEnc->sStereo, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ 2 ], &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ 2 ],
psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ], &psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ],
MStargetRates_bps, TargetRate_bps, psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8, encControl->toMono,
psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, psEnc->state_Fxx[ 0 ].sCmn.frame_length );
if( psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
/* Reset side channel encoder memory for first frame with side coding */
if( psEnc->prev_decode_only_middle == 1 ) {
silk_memset( &psEnc->state_Fxx[ 1 ].sShape, 0, sizeof( psEnc->state_Fxx[ 1 ].sShape ) );
silk_memset( &psEnc->state_Fxx[ 1 ].sPrefilt, 0, sizeof( psEnc->state_Fxx[ 1 ].sPrefilt ) );
silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sNSQ, 0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sNSQ ) );
silk_memset( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15, 0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15 ) );
silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State, 0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State ) );
psEnc->state_Fxx[ 1 ].sCmn.prevLag = 100;
psEnc->state_Fxx[ 1 ].sCmn.sNSQ.lagPrev = 100;
psEnc->state_Fxx[ 1 ].sShape.LastGainIndex = 10;
psEnc->state_Fxx[ 1 ].sCmn.prevSignalType = TYPE_NO_VOICE_ACTIVITY;
psEnc->state_Fxx[ 1 ].sCmn.sNSQ.prev_gain_Q16 = 65536;
psEnc->state_Fxx[ 1 ].sCmn.first_frame_after_reset = 1;
}
silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 1 ] );
} else {
psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] = 0;
}
if( !prefillFlag ) {
silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
if( psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
}
}
} else {
/* Buffering */
silk_memcpy( psEnc->state_Fxx[ 0 ].sCmn.inputBuf, psEnc->sStereo.sMid, 2 * sizeof( opus_int16 ) );
silk_memcpy( psEnc->sStereo.sMid, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.frame_length ], 2 * sizeof( opus_int16 ) );
}
silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 0 ] );
/* Encode */
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
opus_int maxBits, useCBR;
/* Handling rate constraints */
maxBits = encControl->maxBits;
if( tot_blocks == 2 && curr_block == 0 ) {
maxBits = maxBits * 3 / 5;
} else if( tot_blocks == 3 ) {
if( curr_block == 0 ) {
maxBits = maxBits * 2 / 5;
} else if( curr_block == 1 ) {
maxBits = maxBits * 3 / 4;
}
}
useCBR = encControl->useCBR && curr_block == tot_blocks - 1;
if( encControl->nChannelsInternal == 1 ) {
channelRate_bps = TargetRate_bps;
} else {
channelRate_bps = MStargetRates_bps[ n ];
if( n == 0 && MStargetRates_bps[ 1 ] > 0 ) {
useCBR = 0;
/* Give mid up to 1/2 of the max bits for that frame */
maxBits -= encControl->maxBits / ( tot_blocks * 2 );
}
}
if( channelRate_bps > 0 ) {
opus_int condCoding;
silk_control_SNR( &psEnc->state_Fxx[ n ].sCmn, channelRate_bps );
/* Use independent coding if no previous frame available */
if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - n <= 0 ) {
condCoding = CODE_INDEPENDENTLY;
} else if( n > 0 && psEnc->prev_decode_only_middle ) {
/* If we skipped a side frame in this packet, we don't
need LTP scaling; the LTP state is well-defined. */
condCoding = CODE_INDEPENDENTLY_NO_LTP_SCALING;
} else {
condCoding = CODE_CONDITIONALLY;
}
if( ( ret = silk_encode_frame_Fxx( &psEnc->state_Fxx[ n ], nBytesOut, psRangeEnc, condCoding, maxBits, useCBR ) ) != 0 ) {
silk_assert( 0 );
}
}
psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
psEnc->state_Fxx[ n ].sCmn.inputBufIx = 0;
psEnc->state_Fxx[ n ].sCmn.nFramesEncoded++;
}
psEnc->prev_decode_only_middle = psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - 1 ];
/* Insert VAD and FEC flags at beginning of bitstream */
if( *nBytesOut > 0 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket) {
flags = 0;
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
flags = silk_LSHIFT( flags, 1 );
flags |= psEnc->state_Fxx[ n ].sCmn.VAD_flags[ i ];
}
flags = silk_LSHIFT( flags, 1 );
flags |= psEnc->state_Fxx[ n ].sCmn.LBRR_flag;
}
if( !prefillFlag ) {
ec_enc_patch_initial_bits( psRangeEnc, flags, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
}
/* Return zero bytes if all channels DTXed */
if( psEnc->state_Fxx[ 0 ].sCmn.inDTX && ( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inDTX ) ) {
*nBytesOut = 0;
}
psEnc->nBitsExceeded += *nBytesOut * 8;
psEnc->nBitsExceeded -= silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
psEnc->nBitsExceeded = silk_LIMIT( psEnc->nBitsExceeded, 0, 10000 );
/* Update flag indicating if bandwidth switching is allowed */
speech_act_thr_for_switch_Q8 = silk_SMLAWB( SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ),
SILK_FIX_CONST( ( 1 - SPEECH_ACTIVITY_DTX_THRES ) / MAX_BANDWIDTH_SWITCH_DELAY_MS, 16 + 8 ), psEnc->timeSinceSwitchAllowed_ms );
if( psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8 < speech_act_thr_for_switch_Q8 ) {
psEnc->allowBandwidthSwitch = 1;
psEnc->timeSinceSwitchAllowed_ms = 0;
} else {
psEnc->allowBandwidthSwitch = 0;
psEnc->timeSinceSwitchAllowed_ms += encControl->payloadSize_ms;
}
}
if( nSamplesIn == 0 ) {
break;
}
} else {
break;
}
curr_block++;
}
psEnc->nPrevChannelsInternal = encControl->nChannelsInternal;
encControl->allowBandwidthSwitch = psEnc->allowBandwidthSwitch;
encControl->inWBmodeWithoutVariableLP = psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == 16 && psEnc->state_Fxx[ 0 ].sCmn.sLP.mode == 0;
encControl->internalSampleRate = silk_SMULBB( psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
encControl->stereoWidth_Q14 = encControl->toMono ? 0 : psEnc->sStereo.smth_width_Q14;
if( prefillFlag ) {
encControl->payloadSize_ms = tmp_payloadSize_ms;
encControl->complexity = tmp_complexity;
for( n = 0; n < encControl->nChannelsInternal; n++ ) {
psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
psEnc->state_Fxx[ n ].sCmn.prefillFlag = 0;
}
}
RESTORE_STACK;
return ret;
}
| bsd-3-clause |
eriknstr/ThinkPad-FreeBSD-setup | FreeBSD/sys/amd64/vmm/io/ppt.c | 2 | 14698 | /*-
* Copyright (c) 2011 NetApp, Inc.
* 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 NETAPP, INC ``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 NETAPP, INC 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.
*
* $FreeBSD$
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <sys/pciio.h>
#include <sys/rman.h>
#include <sys/smp.h>
#include <sys/sysctl.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <machine/resource.h>
#include <machine/vmm.h>
#include <machine/vmm_dev.h>
#include "vmm_lapic.h"
#include "vmm_ktr.h"
#include "iommu.h"
#include "ppt.h"
/* XXX locking */
#define MAX_MSIMSGS 32
/*
* If the MSI-X table is located in the middle of a BAR then that MMIO
* region gets split into two segments - one segment above the MSI-X table
* and the other segment below the MSI-X table - with a hole in place of
* the MSI-X table so accesses to it can be trapped and emulated.
*
* So, allocate a MMIO segment for each BAR register + 1 additional segment.
*/
#define MAX_MMIOSEGS ((PCIR_MAX_BAR_0 + 1) + 1)
MALLOC_DEFINE(M_PPTMSIX, "pptmsix", "Passthru MSI-X resources");
struct pptintr_arg { /* pptintr(pptintr_arg) */
struct pptdev *pptdev;
uint64_t addr;
uint64_t msg_data;
};
struct pptseg {
vm_paddr_t gpa;
size_t len;
int wired;
};
struct pptdev {
device_t dev;
struct vm *vm; /* owner of this device */
TAILQ_ENTRY(pptdev) next;
struct pptseg mmio[MAX_MMIOSEGS];
struct {
int num_msgs; /* guest state */
int startrid; /* host state */
struct resource *res[MAX_MSIMSGS];
void *cookie[MAX_MSIMSGS];
struct pptintr_arg arg[MAX_MSIMSGS];
} msi;
struct {
int num_msgs;
int startrid;
int msix_table_rid;
struct resource *msix_table_res;
struct resource **res;
void **cookie;
struct pptintr_arg *arg;
} msix;
};
SYSCTL_DECL(_hw_vmm);
SYSCTL_NODE(_hw_vmm, OID_AUTO, ppt, CTLFLAG_RW, 0, "bhyve passthru devices");
static int num_pptdevs;
SYSCTL_INT(_hw_vmm_ppt, OID_AUTO, devices, CTLFLAG_RD, &num_pptdevs, 0,
"number of pci passthru devices");
static TAILQ_HEAD(, pptdev) pptdev_list = TAILQ_HEAD_INITIALIZER(pptdev_list);
static int
ppt_probe(device_t dev)
{
int bus, slot, func;
struct pci_devinfo *dinfo;
dinfo = (struct pci_devinfo *)device_get_ivars(dev);
bus = pci_get_bus(dev);
slot = pci_get_slot(dev);
func = pci_get_function(dev);
/*
* To qualify as a pci passthrough device a device must:
* - be allowed by administrator to be used in this role
* - be an endpoint device
*/
if ((dinfo->cfg.hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_NORMAL)
return (ENXIO);
else if (vmm_is_pptdev(bus, slot, func))
return (0);
else
/*
* Returning BUS_PROBE_NOWILDCARD here matches devices that the
* SR-IOV infrastructure specified as "ppt" passthrough devices.
* All normal devices that did not have "ppt" specified as their
* driver will not be matched by this.
*/
return (BUS_PROBE_NOWILDCARD);
}
static int
ppt_attach(device_t dev)
{
struct pptdev *ppt;
ppt = device_get_softc(dev);
num_pptdevs++;
TAILQ_INSERT_TAIL(&pptdev_list, ppt, next);
ppt->dev = dev;
if (bootverbose)
device_printf(dev, "attached\n");
return (0);
}
static int
ppt_detach(device_t dev)
{
struct pptdev *ppt;
ppt = device_get_softc(dev);
if (ppt->vm != NULL)
return (EBUSY);
num_pptdevs--;
TAILQ_REMOVE(&pptdev_list, ppt, next);
return (0);
}
static device_method_t ppt_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, ppt_probe),
DEVMETHOD(device_attach, ppt_attach),
DEVMETHOD(device_detach, ppt_detach),
{0, 0}
};
static devclass_t ppt_devclass;
DEFINE_CLASS_0(ppt, ppt_driver, ppt_methods, sizeof(struct pptdev));
DRIVER_MODULE(ppt, pci, ppt_driver, ppt_devclass, NULL, NULL);
static struct pptdev *
ppt_find(int bus, int slot, int func)
{
device_t dev;
struct pptdev *ppt;
int b, s, f;
TAILQ_FOREACH(ppt, &pptdev_list, next) {
dev = ppt->dev;
b = pci_get_bus(dev);
s = pci_get_slot(dev);
f = pci_get_function(dev);
if (bus == b && slot == s && func == f)
return (ppt);
}
return (NULL);
}
static void
ppt_unmap_mmio(struct vm *vm, struct pptdev *ppt)
{
int i;
struct pptseg *seg;
for (i = 0; i < MAX_MMIOSEGS; i++) {
seg = &ppt->mmio[i];
if (seg->len == 0)
continue;
(void)vm_unmap_mmio(vm, seg->gpa, seg->len);
bzero(seg, sizeof(struct pptseg));
}
}
static void
ppt_teardown_msi(struct pptdev *ppt)
{
int i, rid;
void *cookie;
struct resource *res;
if (ppt->msi.num_msgs == 0)
return;
for (i = 0; i < ppt->msi.num_msgs; i++) {
rid = ppt->msi.startrid + i;
res = ppt->msi.res[i];
cookie = ppt->msi.cookie[i];
if (cookie != NULL)
bus_teardown_intr(ppt->dev, res, cookie);
if (res != NULL)
bus_release_resource(ppt->dev, SYS_RES_IRQ, rid, res);
ppt->msi.res[i] = NULL;
ppt->msi.cookie[i] = NULL;
}
if (ppt->msi.startrid == 1)
pci_release_msi(ppt->dev);
ppt->msi.num_msgs = 0;
}
static void
ppt_teardown_msix_intr(struct pptdev *ppt, int idx)
{
int rid;
struct resource *res;
void *cookie;
rid = ppt->msix.startrid + idx;
res = ppt->msix.res[idx];
cookie = ppt->msix.cookie[idx];
if (cookie != NULL)
bus_teardown_intr(ppt->dev, res, cookie);
if (res != NULL)
bus_release_resource(ppt->dev, SYS_RES_IRQ, rid, res);
ppt->msix.res[idx] = NULL;
ppt->msix.cookie[idx] = NULL;
}
static void
ppt_teardown_msix(struct pptdev *ppt)
{
int i;
if (ppt->msix.num_msgs == 0)
return;
for (i = 0; i < ppt->msix.num_msgs; i++)
ppt_teardown_msix_intr(ppt, i);
if (ppt->msix.msix_table_res) {
bus_release_resource(ppt->dev, SYS_RES_MEMORY,
ppt->msix.msix_table_rid,
ppt->msix.msix_table_res);
ppt->msix.msix_table_res = NULL;
ppt->msix.msix_table_rid = 0;
}
free(ppt->msix.res, M_PPTMSIX);
free(ppt->msix.cookie, M_PPTMSIX);
free(ppt->msix.arg, M_PPTMSIX);
pci_release_msi(ppt->dev);
ppt->msix.num_msgs = 0;
}
int
ppt_avail_devices(void)
{
return (num_pptdevs);
}
int
ppt_assigned_devices(struct vm *vm)
{
struct pptdev *ppt;
int num;
num = 0;
TAILQ_FOREACH(ppt, &pptdev_list, next) {
if (ppt->vm == vm)
num++;
}
return (num);
}
boolean_t
ppt_is_mmio(struct vm *vm, vm_paddr_t gpa)
{
int i;
struct pptdev *ppt;
struct pptseg *seg;
TAILQ_FOREACH(ppt, &pptdev_list, next) {
if (ppt->vm != vm)
continue;
for (i = 0; i < MAX_MMIOSEGS; i++) {
seg = &ppt->mmio[i];
if (seg->len == 0)
continue;
if (gpa >= seg->gpa && gpa < seg->gpa + seg->len)
return (TRUE);
}
}
return (FALSE);
}
int
ppt_assign_device(struct vm *vm, int bus, int slot, int func)
{
struct pptdev *ppt;
ppt = ppt_find(bus, slot, func);
if (ppt != NULL) {
/*
* If this device is owned by a different VM then we
* cannot change its owner.
*/
if (ppt->vm != NULL && ppt->vm != vm)
return (EBUSY);
ppt->vm = vm;
iommu_add_device(vm_iommu_domain(vm), pci_get_rid(ppt->dev));
return (0);
}
return (ENOENT);
}
int
ppt_unassign_device(struct vm *vm, int bus, int slot, int func)
{
struct pptdev *ppt;
ppt = ppt_find(bus, slot, func);
if (ppt != NULL) {
/*
* If this device is not owned by this 'vm' then bail out.
*/
if (ppt->vm != vm)
return (EBUSY);
ppt_unmap_mmio(vm, ppt);
ppt_teardown_msi(ppt);
ppt_teardown_msix(ppt);
iommu_remove_device(vm_iommu_domain(vm), pci_get_rid(ppt->dev));
ppt->vm = NULL;
return (0);
}
return (ENOENT);
}
int
ppt_unassign_all(struct vm *vm)
{
struct pptdev *ppt;
int bus, slot, func;
device_t dev;
TAILQ_FOREACH(ppt, &pptdev_list, next) {
if (ppt->vm == vm) {
dev = ppt->dev;
bus = pci_get_bus(dev);
slot = pci_get_slot(dev);
func = pci_get_function(dev);
vm_unassign_pptdev(vm, bus, slot, func);
}
}
return (0);
}
int
ppt_map_mmio(struct vm *vm, int bus, int slot, int func,
vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
{
int i, error;
struct pptseg *seg;
struct pptdev *ppt;
ppt = ppt_find(bus, slot, func);
if (ppt != NULL) {
if (ppt->vm != vm)
return (EBUSY);
for (i = 0; i < MAX_MMIOSEGS; i++) {
seg = &ppt->mmio[i];
if (seg->len == 0) {
error = vm_map_mmio(vm, gpa, len, hpa);
if (error == 0) {
seg->gpa = gpa;
seg->len = len;
}
return (error);
}
}
return (ENOSPC);
}
return (ENOENT);
}
static int
pptintr(void *arg)
{
struct pptdev *ppt;
struct pptintr_arg *pptarg;
pptarg = arg;
ppt = pptarg->pptdev;
if (ppt->vm != NULL)
lapic_intr_msi(ppt->vm, pptarg->addr, pptarg->msg_data);
else {
/*
* XXX
* This is not expected to happen - panic?
*/
}
/*
* For legacy interrupts give other filters a chance in case
* the interrupt was not generated by the passthrough device.
*/
if (ppt->msi.startrid == 0)
return (FILTER_STRAY);
else
return (FILTER_HANDLED);
}
int
ppt_setup_msi(struct vm *vm, int vcpu, int bus, int slot, int func,
uint64_t addr, uint64_t msg, int numvec)
{
int i, rid, flags;
int msi_count, startrid, error, tmp;
struct pptdev *ppt;
if (numvec < 0 || numvec > MAX_MSIMSGS)
return (EINVAL);
ppt = ppt_find(bus, slot, func);
if (ppt == NULL)
return (ENOENT);
if (ppt->vm != vm) /* Make sure we own this device */
return (EBUSY);
/* Free any allocated resources */
ppt_teardown_msi(ppt);
if (numvec == 0) /* nothing more to do */
return (0);
flags = RF_ACTIVE;
msi_count = pci_msi_count(ppt->dev);
if (msi_count == 0) {
startrid = 0; /* legacy interrupt */
msi_count = 1;
flags |= RF_SHAREABLE;
} else
startrid = 1; /* MSI */
/*
* The device must be capable of supporting the number of vectors
* the guest wants to allocate.
*/
if (numvec > msi_count)
return (EINVAL);
/*
* Make sure that we can allocate all the MSI vectors that are needed
* by the guest.
*/
if (startrid == 1) {
tmp = numvec;
error = pci_alloc_msi(ppt->dev, &tmp);
if (error)
return (error);
else if (tmp != numvec) {
pci_release_msi(ppt->dev);
return (ENOSPC);
} else {
/* success */
}
}
ppt->msi.startrid = startrid;
/*
* Allocate the irq resource and attach it to the interrupt handler.
*/
for (i = 0; i < numvec; i++) {
ppt->msi.num_msgs = i + 1;
ppt->msi.cookie[i] = NULL;
rid = startrid + i;
ppt->msi.res[i] = bus_alloc_resource_any(ppt->dev, SYS_RES_IRQ,
&rid, flags);
if (ppt->msi.res[i] == NULL)
break;
ppt->msi.arg[i].pptdev = ppt;
ppt->msi.arg[i].addr = addr;
ppt->msi.arg[i].msg_data = msg + i;
error = bus_setup_intr(ppt->dev, ppt->msi.res[i],
INTR_TYPE_NET | INTR_MPSAFE,
pptintr, NULL, &ppt->msi.arg[i],
&ppt->msi.cookie[i]);
if (error != 0)
break;
}
if (i < numvec) {
ppt_teardown_msi(ppt);
return (ENXIO);
}
return (0);
}
int
ppt_setup_msix(struct vm *vm, int vcpu, int bus, int slot, int func,
int idx, uint64_t addr, uint64_t msg, uint32_t vector_control)
{
struct pptdev *ppt;
struct pci_devinfo *dinfo;
int numvec, alloced, rid, error;
size_t res_size, cookie_size, arg_size;
ppt = ppt_find(bus, slot, func);
if (ppt == NULL)
return (ENOENT);
if (ppt->vm != vm) /* Make sure we own this device */
return (EBUSY);
dinfo = device_get_ivars(ppt->dev);
if (!dinfo)
return (ENXIO);
/*
* First-time configuration:
* Allocate the MSI-X table
* Allocate the IRQ resources
* Set up some variables in ppt->msix
*/
if (ppt->msix.num_msgs == 0) {
numvec = pci_msix_count(ppt->dev);
if (numvec <= 0)
return (EINVAL);
ppt->msix.startrid = 1;
ppt->msix.num_msgs = numvec;
res_size = numvec * sizeof(ppt->msix.res[0]);
cookie_size = numvec * sizeof(ppt->msix.cookie[0]);
arg_size = numvec * sizeof(ppt->msix.arg[0]);
ppt->msix.res = malloc(res_size, M_PPTMSIX, M_WAITOK | M_ZERO);
ppt->msix.cookie = malloc(cookie_size, M_PPTMSIX,
M_WAITOK | M_ZERO);
ppt->msix.arg = malloc(arg_size, M_PPTMSIX, M_WAITOK | M_ZERO);
rid = dinfo->cfg.msix.msix_table_bar;
ppt->msix.msix_table_res = bus_alloc_resource_any(ppt->dev,
SYS_RES_MEMORY, &rid, RF_ACTIVE);
if (ppt->msix.msix_table_res == NULL) {
ppt_teardown_msix(ppt);
return (ENOSPC);
}
ppt->msix.msix_table_rid = rid;
alloced = numvec;
error = pci_alloc_msix(ppt->dev, &alloced);
if (error || alloced != numvec) {
ppt_teardown_msix(ppt);
return (error == 0 ? ENOSPC: error);
}
}
if ((vector_control & PCIM_MSIX_VCTRL_MASK) == 0) {
/* Tear down the IRQ if it's already set up */
ppt_teardown_msix_intr(ppt, idx);
/* Allocate the IRQ resource */
ppt->msix.cookie[idx] = NULL;
rid = ppt->msix.startrid + idx;
ppt->msix.res[idx] = bus_alloc_resource_any(ppt->dev, SYS_RES_IRQ,
&rid, RF_ACTIVE);
if (ppt->msix.res[idx] == NULL)
return (ENXIO);
ppt->msix.arg[idx].pptdev = ppt;
ppt->msix.arg[idx].addr = addr;
ppt->msix.arg[idx].msg_data = msg;
/* Setup the MSI-X interrupt */
error = bus_setup_intr(ppt->dev, ppt->msix.res[idx],
INTR_TYPE_NET | INTR_MPSAFE,
pptintr, NULL, &ppt->msix.arg[idx],
&ppt->msix.cookie[idx]);
if (error != 0) {
bus_teardown_intr(ppt->dev, ppt->msix.res[idx], ppt->msix.cookie[idx]);
bus_release_resource(ppt->dev, SYS_RES_IRQ, rid, ppt->msix.res[idx]);
ppt->msix.cookie[idx] = NULL;
ppt->msix.res[idx] = NULL;
return (ENXIO);
}
} else {
/* Masked, tear it down if it's already been set up */
ppt_teardown_msix_intr(ppt, idx);
}
return (0);
}
| isc |
TigerBSD/TigerBSD | FreeBSD/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp | 52 | 1377 | //== Checker.cpp - Registration mechanism for checkers -----------*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines Checker, used to create and register checkers.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
using namespace clang;
using namespace ento;
StringRef CheckerBase::getTagDescription() const {
return getCheckName().getName();
}
CheckName CheckerBase::getCheckName() const { return Name; }
CheckerProgramPointTag::CheckerProgramPointTag(StringRef CheckerName,
StringRef Msg)
: SimpleProgramPointTag(CheckerName, Msg) {}
CheckerProgramPointTag::CheckerProgramPointTag(const CheckerBase *Checker,
StringRef Msg)
: SimpleProgramPointTag(Checker->getCheckName().getName(), Msg) {}
raw_ostream& clang::ento::operator<<(raw_ostream &Out,
const CheckerBase &Checker) {
Out << Checker.getCheckName().getName();
return Out;
}
| isc |
danjtg/Odin-Project | Odin/Source/Core/Log/Log.cpp | 1 | 1608 | //
// Log.cpp
// Odin.MacOSX
//
// Created by Daniel on 20/05/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#include "preprocessor.h"
#if defined ODIN_SYSTEM_MACOSX
#include <sys/stat.h> // MacOSX - mkdir
#endif
#include "Log.h"
namespace odin
{
namespace core
{
Log::Log(LogLevel level, std::string file, std::string dir)
{
m_logLevel = level;
m_fileName = file;
m_directory = dir;
}
void Log::log(std::string& message)
{
FILE* fileHandler;
if(m_fileName == "")
{
fileHandler = stdout;
}
else
{
#if defined ODIN_SYSTEM_MACOSX || ODIN_SYSTEM_LINUX
mkdir(m_directory.c_str(), 0755); // APPLE
#elif defined ODIN_SYSTEM_WINDOWS
_mkdir(sDirectory.c_str()); // WINDOWS
#endif
fileHandler = fopen((m_directory + "/" + m_fileName).c_str(), "a");
if (fileHandler == nullptr)
{
printf("ERROR: Log file %s could not be opened. Writing logs to stdout:\n", (m_directory + "/" + m_fileName).c_str());
fileHandler = stdout;
}
}
fwrite(message.c_str(), message.size(), 1, fileHandler);
if(fileHandler != stdout)
{
fclose (fileHandler);
}
}
LogLevel Log::getLogLevel()
{
return m_logLevel;
}
}
}
| mit |
nagadomi/animeface-2009 | nvxs/CLAPACK/TESTING/EIG/zlarfy.c | 1 | 3984 | #include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static doublecomplex c_b1 = {1.,0.};
static doublecomplex c_b2 = {0.,0.};
static integer c__1 = 1;
/* Subroutine */ int zlarfy_(char *uplo, integer *n, doublecomplex *v,
integer *incv, doublecomplex *tau, doublecomplex *c__, integer *ldc,
doublecomplex *work)
{
/* System generated locals */
integer c_dim1, c_offset;
doublecomplex z__1, z__2, z__3, z__4;
/* Local variables */
extern /* Subroutine */ int zher2_(char *, integer *, doublecomplex *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublecomplex *, integer *);
doublecomplex alpha;
extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *);
extern /* Subroutine */ int zhemv_(char *, integer *, doublecomplex *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublecomplex *, doublecomplex *, integer *), zaxpy_(
integer *, doublecomplex *, doublecomplex *, integer *,
doublecomplex *, integer *);
/* -- LAPACK auxiliary test routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* ZLARFY applies an elementary reflector, or Householder matrix, H, */
/* to an n x n Hermitian matrix C, from both the left and the right. */
/* H is represented in the form */
/* H = I - tau * v * v' */
/* where tau is a scalar and v is a vector. */
/* If tau is zero, then H is taken to be the unit matrix. */
/* Arguments */
/* ========= */
/* UPLO (input) CHARACTER*1 */
/* Specifies whether the upper or lower triangular part of the */
/* Hermitian matrix C is stored. */
/* = 'U': Upper triangle */
/* = 'L': Lower triangle */
/* N (input) INTEGER */
/* The number of rows and columns of the matrix C. N >= 0. */
/* V (input) COMPLEX*16 array, dimension */
/* (1 + (N-1)*abs(INCV)) */
/* The vector v as described above. */
/* INCV (input) INTEGER */
/* The increment between successive elements of v. INCV must */
/* not be zero. */
/* TAU (input) COMPLEX*16 */
/* The value tau as described above. */
/* C (input/output) COMPLEX*16 array, dimension (LDC, N) */
/* On entry, the matrix C. */
/* On exit, C is overwritten by H * C * H'. */
/* LDC (input) INTEGER */
/* The leading dimension of the array C. LDC >= max( 1, N ). */
/* WORK (workspace) COMPLEX*16 array, dimension (N) */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
--v;
c_dim1 = *ldc;
c_offset = 1 + c_dim1;
c__ -= c_offset;
--work;
/* Function Body */
if (tau->r == 0. && tau->i == 0.) {
return 0;
}
/* Form w:= C * v */
zhemv_(uplo, n, &c_b1, &c__[c_offset], ldc, &v[1], incv, &c_b2, &work[1],
&c__1);
z__3.r = -.5, z__3.i = -0.;
z__2.r = z__3.r * tau->r - z__3.i * tau->i, z__2.i = z__3.r * tau->i +
z__3.i * tau->r;
zdotc_(&z__4, n, &work[1], &c__1, &v[1], incv);
z__1.r = z__2.r * z__4.r - z__2.i * z__4.i, z__1.i = z__2.r * z__4.i +
z__2.i * z__4.r;
alpha.r = z__1.r, alpha.i = z__1.i;
zaxpy_(n, &alpha, &v[1], incv, &work[1], &c__1);
/* C := C - v * w' - w * v' */
z__1.r = -tau->r, z__1.i = -tau->i;
zher2_(uplo, n, &z__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc);
return 0;
/* End of ZLARFY */
} /* zlarfy_ */
| mit |
Luoyayu/ACM | CodeBook/资料/紫书代码/ch5/BigInteger.cpp | 1 | 1855 | #include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
using namespace std;
struct BigInteger {
static const int BASE = 100000000;
static const int WIDTH = 8;
vector<int> s;
BigInteger(long long num = 0) { *this = num; } // 构造函数
BigInteger operator = (long long num) { // 赋值运算符
s.clear();
do {
s.push_back(num % BASE);
num /= BASE;
} while(num > 0);
return *this;
}
BigInteger operator = (const string& str) { // 赋值运算符
s.clear();
int x, len = (str.length() - 1) / WIDTH + 1;
for(int i = 0; i < len; i++) {
int end = str.length() - i*WIDTH;
int start = max(0, end - WIDTH);
sscanf(str.substr(start, end-start).c_str(), "%d", &x);
s.push_back(x);
}
return *this;
}
BigInteger operator + (const BigInteger& b) const {
BigInteger c;
c.s.clear();
for(int i = 0, g = 0; ; i++) {
if(g == 0 && i >= s.size() && i >= b.s.size()) break;
int x = g;
if(i < s.size()) x += s[i];
if(i < b.s.size()) x += b.s[i];
c.s.push_back(x % BASE);
g = x / BASE;
}
return c;
}
};
ostream& operator << (ostream &out, const BigInteger& x) {
out << x.s.back();
for(int i = x.s.size()-2; i >= 0; i--) {
char buf[20];
sprintf(buf, "%08d", x.s[i]);
for(int j = 0; j < strlen(buf); j++) out << buf[j];
}
return out;
}
istream& operator >> (istream &in, BigInteger& x) {
string s;
if(!(in >> s)) return in;
x = s;
return in;
}
#include<set>
#include<map>
set<BigInteger> s;
map<BigInteger, int> m;
int main() {
BigInteger y;
BigInteger x = y;
BigInteger z = 123;
BigInteger a, b;
cin >> a >> b;
cout << a + b << "\n";
cout << BigInteger::BASE << "\n";
return 0;
}
| mit |
Infernoman/skidoo | src/chainparams.cpp | 1 | 13325 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 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 "chainparams.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace std;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
/**
* Main network
*/
//! Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
static Checkpoints::MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x0000074e6840be44f43857beb3a16350f99182bc1ce64088a7b405aaec3cedb3"))
( 25000, uint256("0x00000000000757add245f48236a4bcbe0fce70c256b6ee36e812b1b48e7ac36a"))
( 303709, uint256("0x0000000000011bf57263dc8dafb04bd599dff49e8732a1411c30fee0e6139680"))
( 303710, uint256("0x000000000001ea2051926e7cbe381dbb85b770b2ec074a4211353d085a488365"))
( 309600, uint256("0x00000000000105550f8c28dc1df4ee6185f187e00e82aa3a5a8c44f0edfb40df"))
;
static const Checkpoints::CCheckpointData data = {
&mapCheckpoints,
1437932135, // * UNIX timestamp of last checkpoint block
317206, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
2880 // * estimated number of transactions per day after checkpoint
};
static Checkpoints::MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x0x00000374e85c69e9d39c5f033b2a56656af20b094c58a4a02c5d7a5fe3f3805f"))
;
static const Checkpoints::CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
2,
0,
2880
};
static Checkpoints::MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256S("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
;
static const Checkpoints::CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0x02;
pchMessageStart[1] = 0x03;
pchMessageStart[2] = 0x02;
pchMessageStart[3] = 0x03;
vAlertPubKey = ParseHex("");
nDefaultPort = 10005;
bnProofOfWorkLimit = ~uint256(0) >> 20;
nSubsidyHalvingInterval = 1000000;
nEnforceBlockUpgradeMajority = 750;
nRejectBlockOutdatedMajority = 950;
nToCheckBlockUpgradeMajority = 1000;
nMinerThreads = 0;
nTargetTimespan = 2.3 * 60 * 25;
nTargetSpacing = 2.3 * 60;
const char* pszTimestamp = "In thanks to Saint Jude for favors granted. A.W.";
CMutableTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 0 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 5;
genesis.nBits = 0x1e0fffff;
genesis.nNonce = 1200094;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256S("0x0000074e6840be44f43857beb3a16350f99182bc1ce64088a7b405aaec3cedb3"));
assert(genesis.hashMerkleRoot == uint256S("0x921c1604d9b02fe2329599e548f53c07c34b26eb22447cff171183921c3dd14e"));
vSeeds.push_back(CDNSSeedData("23skidoo.xyz", "23skidoo.xyz"));
vSeeds.push_back(CDNSSeedData("45.33.104.27", "45.33.104.27"));
vSeeds.push_back(CDNSSeedData("107.134.126.6", "107.134.126.6"));
vSeeds.push_back(CDNSSeedData("35.163.132.3", "35.163.132.3"));
vSeeds.push_back(CDNSSeedData("147.135.191.162", "147.135.191.162"));
vSeeds.push_back(CDNSSeedData("skidoo.duckdns.org", "skidoo.duckdns.org"));
vSeeds.push_back(CDNSSeedData("chainz.cryptoid.info", "chainz.cryptoid.info"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,142);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,142);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,224);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
fRequireRPCPassword = true;
fMiningRequiresPeers = true;
fDefaultCheckMemPool = false;
fAllowMinDifficultyBlocks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fSkipProofOfWorkCheck = false;
fTestnetToBeDeprecatedFieldRPC = false;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return data;
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
strNetworkID = "test";
pchMessageStart[0] = 0x01;
pchMessageStart[1] = 0xfe;
pchMessageStart[2] = 0xfe;
pchMessageStart[3] = 0x05;
vAlertPubKey = ParseHex("");
nDefaultPort = 55537;
nEnforceBlockUpgradeMajority = 51000000;
nRejectBlockOutdatedMajority = 75000000;
nToCheckBlockUpgradeMajority = 10000000;
nMinerThreads = 0;
nTargetTimespan = 2.3 * 60 * 25;
nTargetSpacing = 2.3 * 60;
//! Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 2;
genesis.nNonce = 1294578;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256S("0x00000374e85c69e9d39c5f033b2a56656af20b094c58a4a02c5d7a5fe3f3805f"));
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("23skidoo.info", "23skidoo.info"));
vSeeds.push_back(CDNSSeedData("testnet.skidoo.info", "testnet.skidoo.info"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,130);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,30);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x86)(0xCE).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x82)(0x93).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
fRequireRPCPassword = true;
fMiningRequiresPeers = true;
fDefaultCheckMemPool = false;
fAllowMinDifficultyBlocks = true;
fRequireStandard = false;
fMineBlocksOnDemand = false;
fTestnetToBeDeprecatedFieldRPC = true;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataTestnet;
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
pchMessageStart[0] = 0x04;
pchMessageStart[1] = 0x03;
pchMessageStart[2] = 0x02;
pchMessageStart[3] = 0x01;
nSubsidyHalvingInterval = 150;
nEnforceBlockUpgradeMajority = 750;
nRejectBlockOutdatedMajority = 950;
nToCheckBlockUpgradeMajority = 1000;
nMinerThreads = 1;
nTargetTimespan = 3 * 60; // 3 minutes
nTargetSpacing = 60; // 30 seconds
bnProofOfWorkLimit = ~uint256(0) >> 1;
genesis.nTime = 1375548985;
genesis.nBits = 0x207fffff;
genesis.nNonce = 1;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18444;
//assert(hashGenesisBlock == uint256S("0x3868bcc735f32cdd9b42971cdee7bc620c50fada5e3ac5fdfd35630aaf2eb64e"));
vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //! Regtest mode doesn't have any DNS seeds.
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,128);
fRequireRPCPassword = false;
fMiningRequiresPeers = false;
fDefaultCheckMemPool = true;
fAllowMinDifficultyBlocks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
fTestnetToBeDeprecatedFieldRPC = false;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataRegtest;
}
};
static CRegTestParams regTestParams;
/**
* Unit test
*/
class CUnitTestParams : public CMainParams, public CModifiableParams {
public:
CUnitTestParams() {
strNetworkID = "unittest";
nDefaultPort = 18444;
vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds.
vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds.
fRequireRPCPassword = false;
fMiningRequiresPeers = false;
fDefaultCheckMemPool = true;
fAllowMinDifficultyBlocks = false;
fMineBlocksOnDemand = true;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
// UnitTest share the same checkpoints as MAIN
return data;
}
//! Published setters to allow changing values in unit test cases
virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval=anSubsidyHalvingInterval; }
virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority=anEnforceBlockUpgradeMajority; }
virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority=anRejectBlockOutdatedMajority; }
virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority=anToCheckBlockUpgradeMajority; }
virtual void setDefaultCheckMemPool(bool afDefaultCheckMemPool) { fDefaultCheckMemPool=afDefaultCheckMemPool; }
virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks=afAllowMinDifficultyBlocks; }
virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }
};
static CUnitTestParams unitTestParams;
static CChainParams *pCurrentParams = 0;
CModifiableParams *ModifiableParams()
{
assert(pCurrentParams);
assert(pCurrentParams==&unitTestParams);
return (CModifiableParams*)&unitTestParams;
}
const CChainParams &Params() {
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams &Params(CBaseChainParams::Network network) {
switch (network) {
case CBaseChainParams::MAIN:
return mainParams;
case CBaseChainParams::TESTNET:
return testNetParams;
case CBaseChainParams::REGTEST:
return regTestParams;
case CBaseChainParams::UNITTEST:
return unitTestParams;
default:
assert(false && "Unimplemented network");
return mainParams;
}
}
void SelectParams(CBaseChainParams::Network network) {
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
bool SelectParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectParams(network);
return true;
}
| mit |
rburing/kontsevich_graph_series-cpp | tests/schouten_bracket.cpp | 1 | 1455 | #include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <fstream>
using namespace std;
using namespace GiNaC;
int main(int argc, char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << " <graph-series-filename1> <graph-series-filename2>\n";
return 1;
}
// Reading in graph series:
parser coefficient_reader;
string graph_series_filename1(argv[1]);
ifstream graph_series_file1(graph_series_filename1);
KontsevichGraphSeries<ex> graph_series1 = KontsevichGraphSeries<ex>::from_istream(graph_series_file1, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
string graph_series_filename2(argv[2]);
ifstream graph_series_file2(graph_series_filename2);
KontsevichGraphSeries<ex> graph_series2 = KontsevichGraphSeries<ex>::from_istream(graph_series_file2, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
size_t order = min(graph_series1.precision(), graph_series2.precision());
KontsevichGraphSeries<ex> schouten_bracket_series = schouten_bracket(graph_series1, graph_series2);
for (size_t n = 0; n <= order; ++n)
{
if (schouten_bracket_series[n] != 0 || n == order)
cout << "h^" << n << ":\n";
for (auto& term : schouten_bracket_series[n])
{
cout << term.second.encoding() << " " << term.first << "\n";
}
}
}
| mit |
junyanz/MirrorMirror | src/FadeModule.cpp | 1 | 21704 | #include "FadeModule.h"
#include "Timer.h"
#include "ImageTools.h"
#include "WarpingModule.h"
#include "BlendModule.h"
#include "WarpUtils.h"
const int NUM_BINS = 256;
const int NUM_FRAMES_COLOR = 30;
const double MAX_ERROR = 2.5f;
#ifdef __linux__
#include<X11/Xlib.h>
#include<GL/glx.h>
Display *dpy;
Window root;
GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo *vi;
Colormap cmap;
XSetWindowAttributes swa;
Window win;
GLXContext glc;
XWindowAttributes gwa;
XEvent xev;
void DrawAQuad() {
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1., 1., -1., 1., 1., 20.);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 10., 0., 0., 0., 0., 1., 0.);
glBegin(GL_QUADS);
glColor3f(1., 0., 0.); glVertex3f(-.75, -.75, 0.);
glColor3f(0., 1., 0.); glVertex3f( .75, -.75, 0.);
glColor3f(0., 0., 1.); glVertex3f( .75, .75, 0.);
glColor3f(1., 1., 0.); glVertex3f(-.75, .75, 0.);
glEnd();
}
void EnableOpenGL() {
dpy = XOpenDisplay(NULL);
if(dpy == NULL)
DEBUG_ERROR("cannot connect to X server");
root = DefaultRootWindow(dpy);
vi = glXChooseVisual(dpy, 0, att);
if(vi == NULL)
DEBUG_ERROR("no appropriate visual found");
else
DEBUG_INFO("visual %p selected", (void *)vi->visualid); /* %p creates hexadecimal output like in glxinfo */
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
swa.colormap = cmap;
swa.event_mask = ExposureMask | KeyPressMask;
win = XCreateWindow(dpy, root, 0, 0, 224, 224, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa);
// XMapWindow(dpy, win);
XStoreName(dpy, win, "3D Face");
glc = glXCreateContext(dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(dpy, win, glc);
glEnable(GL_DEPTH_TEST);
}
#endif
#ifdef _WIN32
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC);
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage( 0 );
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch ( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
}
// Enable OpenGL
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int format;
// get the device context (DC)
*hDC = GetDC( hWnd );
// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat( *hDC, &pfd );
SetPixelFormat( *hDC, format, &pfd );
// create and enable the render context (RC)
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );
}
// Disable OpenGL
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) {
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC( hWnd, hDC );
}
#endif
CFadeModule::CFadeModule() {
DEBUG_INFO("Loading CFadeModule...");
Clear();
Reset();
m_isDebug = false;
m_isFirst = true;
m_isInitList = false;
m_warpModule = new CWarpingModule();
m_Z = CWarpUtils::LoadZ("models/Z.img");
LoadContours();
m_pnts3d = CWarpUtils::LoadMeanPnts3D("models/3d.txt");
}
void CFadeModule::Reset() {
m_nFrames = 0;
m_Hs.clear();
FOR_u (i, m_srcCDF.size())
m_srcCDF[i].clear();
FOR_u (i, m_tgtCDF.size())
m_tgtCDF[i].clear();
m_srcCDF.clear();
m_tgtCDF.clear();
m_isInitList = false;
m_error = -1;
}
void CFadeModule::Clear() {
m_alpha = 0.0f;
m_gridSz = 0;
m_transRatio = 0;
m_nFrames = 0;
}
CFadeModule::~CFadeModule() {
Clear();
}
Mat CFadeModule::DrawPoints( const Mat& _img, const PointSetd& _p, const PointSetd& _q ) {
Mat showImg = _img.clone();
FOR_u (i, _p.size())
cv::circle(showImg, _p[i], 2, Scalar(0, 0, 255), 2); // original
FOR_u (i, _q.size())
cv::circle(showImg, _q[i], 2, Scalar(0, 255, 0), 2); // projection
return showImg;
}
Rect LocalizeParts( PointSeti _pnts, int _border) {
int min_x = 10000;
int min_y = 10000;
int max_x = 0;
int max_y = 0;
FOR (j, (int)_pnts.size()) {
int i = j;
min_x = MIN(min_x, (int)_pnts[i].x);
min_y = MIN(min_y, (int)_pnts[i].y);
max_x = MAX(max_x, (int)_pnts[i].x);
max_y = MAX(max_y, (int)_pnts[i].y);
}
// add border
min_x = min_x - _border;
min_y = min_y - _border;
max_x = max_x + _border;
max_y = max_y + _border;
//cout << min_x << " " << min_y << " " << max_x << " " << max_y << endl;
return Rect(min_x, min_y, max_x-min_x+1, max_y-min_y+1);
}
void CFadeModule::DrawEllipse( const Mat& _img, string _name, RotatedRect _e ) {
Mat showImg = _img.clone();
ellipse(showImg, _e, Scalar(0, 255, 0), 3);
imshow(_name, showImg);
}
Mat CFadeModule::EstimateHistMatch( const Mat& _src, const Mat& _tgt, const Mat& _mask) {
//CTimer timer("EstimateHistMatch");
// match src to tgt
//Mat src_f, tgt_f;
// Mat src_hsv, tgt_hsv;
Mat src = _src.clone();
Mat tgt = _tgt.clone();
m_luts.clear();
ImageSet srcBGR;
ImageSet tgtBGR;
split(src, srcBGR);
split(tgt, tgtBGR);
int histSz = NUM_BINS;
float range[] = { 0, (float)256 } ;
const float* histRange = { range };
bool uniform = true;
bool accumulate = false;
CDF srcCDFs;
CDF tgtCDFs;
FOR (chn, 3) {
Mat srcHist, tgtHist;
// compute histogram
//SHOW_IMG(srcBGR[chn]);
calcHist( &tgtBGR[chn], 1, 0, _mask, tgtHist, 1, &histSz, &histRange, uniform, accumulate );
calcHist( &srcBGR[chn], 1, 0, _mask, srcHist, 1, &histSz, &histRange, uniform, accumulate );
// compute CDF
vectord srcCDF(NUM_BINS, 0.0);
vectord tgtCDF(NUM_BINS, 0.0);
srcCDF[0] = (double)srcHist.at<float>(0);
tgtCDF[0] = (double)tgtHist.at<float>(0);
for (int n = 1; n < NUM_BINS; n++) {
srcCDF[n] = srcCDF[n-1]+(double)srcHist.at<float>(n);
tgtCDF[n] = tgtCDF[n-1]+(double)tgtHist.at<float>(n);
}
srcCDFs.push_back(srcCDF);
tgtCDFs.push_back(tgtCDF);
}
CDF srcCDF_mean;
CDF tgtCDF_mean;
//DEBUG_INFO("queue size = %d", m_tgtCDF.size());
if (m_tgtCDF.size() >= NUM_FRAMES_COLOR) {
FOR_u (i, m_srcCDF[0].size())
m_srcCDF[0][i].clear();
FOR_u (i, m_tgtCDF[0].size())
m_tgtCDF[0][i].clear();
m_srcCDF[0].clear();
m_tgtCDF[0].clear();
m_srcCDF.erase(m_srcCDF.begin());
m_tgtCDF.erase(m_tgtCDF.begin());
}
/*FOR (k, m_tgtCDF.size()) {
cout << m_tgtCDF[k][0][128] << " ";
}
cout << endl; */
m_srcCDF.push_back(srcCDFs);
m_tgtCDF.push_back(tgtCDFs);
FOR (chn, 3) { // compute mean CDF over 30 frames
vectord srcCDF_mean(NUM_BINS, 0.0);
vectord tgtCDF_mean(NUM_BINS, 0.0);
FOR (i, NUM_BINS) {
FOR_u (k, m_tgtCDF.size()) {
srcCDF_mean[i] += m_srcCDF[k][chn][i];
tgtCDF_mean[i] += m_tgtCDF[k][chn][i];
}
srcCDF_mean[i] /= (double)m_srcCDF.size();
tgtCDF_mean[i] /= (double)m_tgtCDF.size();
}
Mat Mv(1,NUM_BINS,CV_8UC1);
uchar* M = Mv.ptr<uchar>();
//int window = 200;
FOR (n, NUM_BINS) {
double cdf = srcCDF_mean[n];
//histMap[n] = lastK;
int min_idx = -1;
double min_dist = 1e10;
FOR (k, NUM_BINS) {
double dist = abs(cdf-tgtCDF_mean[k]);
if (dist <= min_dist) {
min_dist = dist;
min_idx = k;
}
}
M[n] = (uchar)min_idx;
//if (chn == 0) {
//cout << min_idx - n << " ";
//}
}
//if (chn == 0)
//cout << endl;
Mat lut(1,NUM_BINS,CV_8UC1,M);
LUT(srcBGR[chn],lut,srcBGR[chn]);
//SHOW_IMG(srcBGR[chn]);
}
Mat out;
merge(srcBGR, out);
//cvtColor(out, out, CV_Luv2BGR);
//SHOW_IMG(out);
srcBGR.clear();
tgtBGR.clear();
return out;
}
PointSeti CFadeModule::CreatFaceMask( const Mat& _img, const PointSetd& _pnts, Mat& _mask, Rect& _roi) {
//PointSeti drawP;
PointSetd drawP_d;
drawP_d.push_back(m_meanPnts[0]+Point2d(3, 0));
for (int i = 1; i < 16; i++)
drawP_d.push_back(m_meanPnts[i]);
drawP_d.push_back(m_meanPnts[16]-Point2d(3, 0));
for (int i = 26; i >= 17; i--)
drawP_d.push_back(m_meanPnts[i]-Point2d(0, 20));
Mat H = CWarpUtils::EstimateHWeighted(m_meanPnts, _pnts, false);
//Mat H = CWarpUtils::EstimateH(m_meanPnts, _pnts, false);
if (H.empty()) {
DEBUG_INFO("empty H");
_mask = Mat();
_roi = Rect(-1, -1, 0, 0);
return PointSeti();
}
PointSetd projP_d = CWarpUtils::ProjPnts(drawP_d, H);
PointSeti projP;
FOR_u (i, projP_d.size())
projP.push_back(Point2i(projP_d[i].x, projP_d[i].y));
//cout << drawP << endl;
_roi = CWarpUtils::GetRect(projP_d, 15);
//cout << _roi << endl;
_mask = Mat::zeros(_img.size(), CV_8UC1);
vector<PointSeti> countours;
countours.push_back(projP);
drawContours(_mask, countours, 0, Scalar(255), -1);
int dilate_size = 5;
Mat element = getStructuringElement( MORPH_CROSS,
Size( 2*dilate_size + 1, 2*dilate_size+1 ),
Point( dilate_size, dilate_size ) );
dilate(_mask, _mask, element);
//fillPoly(mask, drawP, Scalar(255), -1);
//drawP.clear();
//projP.clear();
projP_d.clear();
drawP_d.clear();
//imwrite("mask.jpg", _mask);
//SHOW_IMG(_mask);
//imshow("mask", _mask);
countours.clear();
return projP;
}
Mat CFadeModule::ColorMatch( const Mat& _src, const ImageSet& _luts ) {
ImageSet rgb;
split(_src, rgb);
FOR (k, 3)
LUT(rgb[k], _luts[k], rgb[k]);
Mat out;
merge(rgb, out);
return out;
}
Mat CFadeModule::DrawMask( const Mat& _img, const PointSeti& _maskPnts ) {
Mat showImg = _img.clone();
vector<PointSeti> countours;
countours.push_back(_maskPnts);
drawContours(showImg, countours, 0, Scalar(0, 255, 0), 2);
return showImg;
}
double CFadeModule::AlignmentError( const PointSetd& _pnts1, const PointSetd& _pnts2 ) {
double error = 0.0;
FOR_u (i, _pnts1.size()) {
double e = CWarpUtils::PntDist(_pnts1[i], _pnts2[i]);
error = e * e;
}
error /= (double)_pnts1.size();
error = sqrt(error);
return error;
}
Mat TranslateImage( const Mat& _img, Point2d _t) {
Mat out;
Mat H = Mat::zeros(2, 3, CV_64FC1);
H.at<double>(0, 0) = 1.0; H.at<double>(1, 1) = 1.0;
H.at<double>(0, 2) = _t.x; H.at<double>(1, 2) = _t.y;
warpAffine(_img, out, H, _img.size());
return out;
//}
}
Mat CFadeModule::Fade3D(const Mat& _tgt, PointSetd _srcPnts, PointSetd _tgtPnts, float _r, bool _flag ) {
vectord weights(_srcPnts.size(), 1.0);
double m[6]={0};
CvMat M = cvMat( 2, 3, CV_64F, m);
CWarpUtils::EstimateHWeighted(_srcPnts, _tgtPnts, weights, &M, true);
m_H = cvarrToMat(&M).clone();
if (m_H.empty()) {
DEBUG_INFO("Fail to fit");
return Mat();
}
PointSetd projPnts = CWarpUtils::ProjPnts(_srcPnts, m_H);
Rect rect = CWarpUtils::GetRect(_tgtPnts);
m_error = AlignmentError(projPnts, _tgtPnts)/sqrt(rect.width*rect.height)*25;
if (m_error >= MAX_ERROR) {
DEBUG_INFO("large alignment error (%4.4f)", m_error);
return Mat();
}
m_warpModule->WarpToFrontalFace3D(_tgt, _tgtPnts, false);
Mat ar, H;
Point2d t;
m_warpModule->Matrix(ar, H, t);
invertAffineTransform(H, H);
Mat warpImg = Mat::zeros(_tgt.size(), _tgt.type());
Mat face = Render3D(m_Z, m_texture, ar, t);
if (face.empty())
return Mat();
warpAffine(face, warpImg, H, _tgt.size());
PointSeti contours = Contours(m_Z, ar, t, H);
Mat warpMask = Mat::zeros(_tgt.size(), CV_8UC1);
vector<PointSeti> pts;
pts.push_back(contours);
drawContours(warpMask, pts, 0, Scalar(255), -1);
Mat disp;
Rect roi = Rect(0, 0, warpImg.cols, warpImg.rows);
Mat color = EstimateHistMatch(warpImg, _tgt, warpMask);
m_warp3d = warpImg;
disp = CBlendModule::LaplacianBlend(color, _tgt, warpMask, roi, _r, m_halfBlend, m_fullBlend);
Mat tgt2 = _tgt.clone();
if (m_isDebug) {
Mat dispHalf = m_halfBlend.clone();
Mat dispFull = m_fullBlend.clone();
FOR_u (i, 9) {
circle(tgt2, _tgtPnts[i], 2, Scalar(0, 0, 255), -1);
circle(dispHalf, _tgtPnts[i], 2, Scalar(0, 0, 255), -1);
circle(dispFull, _tgtPnts[i], 2, Scalar(0, 0, 255), -1);
}
PointSetd prjPnts = ProjPnts(ar, t, H);
FOR_u (i, 9) {
circle(tgt2, prjPnts[i], 2, Scalar(0, 255, 0), -1);
circle(dispHalf, prjPnts[i], 2, Scalar(0, 255, 0), -1);
circle(dispFull, prjPnts[i], 2, Scalar(0, 255, 0), -1);
}
imshow("50% blend", dispHalf);
imshow("100% blend", dispFull);
imshow("ori", tgt2);
}
return disp;
}
void CFadeModule::Init () {
DEBUG_INFO("CFaceModule::Init");
// select projection matrix
glMatrixMode(GL_PROJECTION);
// set the viewport
glViewport(0, 0, 174, 224);
// set matrix mode
glLoadIdentity();
glOrtho(0, 1, 1, 0, 0.1f, 500.0f);
// specify which matrix is the current matrix
glMatrixMode(GL_MODELVIEW);
glShadeModel( GL_SMOOTH );
// specify the clear value for the depth buffer
glClearDepth( 1.0f );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glClearColor(0.0, 0.0, 0.0, 1.0);
}
Mat CFadeModule::DrawFace(Size _sz,const Mat& _Z, const Mat& _texture) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearDepth(1.0f );
glEnable( GL_DEPTH_TEST );
glCallList(m_list);
float _size = (float)max(_sz.width, _sz.height);
unsigned char* buffer = new unsigned char[(int)(_size*_size*3)];
glReadPixels(0, 0, (int)_size, (int)_size, GL_RGB, GL_UNSIGNED_BYTE, buffer);
cv::Mat img((int)_size, (int)_size, CV_8UC3, buffer);
cvtColor(img, img, CV_RGB2BGR);
// SHOW_IMG(img);
flip(img, img, 0);
Mat final = img(Rect(0, 0, _sz.width, _sz.height));
// glutSwapBuffers();
return final;
}
Mat CFadeModule::Render3D(const Mat& _Z, const Mat& _texture, const Mat& _ar, Point2d _t) {
#ifdef WIN32
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
#endif
float size = (float)max(_Z.cols, _Z.rows);
if (m_isFirst) {
// win.width = (int)size;//g_Z.cols;
// win.height = (int)size;//g_Z.rows;
// win.title = "face";
// win.z_near = 0.1f;
// win.z_far = 500.0f;
// set up OpenGL context
// register window class
#ifdef _WIN32
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = NULL;
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
wc.lpszMenuName = NULL;
wc.lpszClassName = L"GLSample";
RegisterClass( &wc );
// create main window
hWnd = CreateWindow(
L"GLSample", L"OpenGL Sample",
WS_POPUPWINDOW,
0, 0, (int)size, (int)size,
NULL, NULL, NULL, NULL );
EnableOpenGL( hWnd, &hDC, &hRC );
#endif
#ifdef __linux__
EnableOpenGL();
#endif
Init();
m_isFirst = false;
}
#ifdef __linux__
XGetWindowAttributes(dpy, win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
#endif
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0,0,100, 0,0,0, 0,1,0);
glPushMatrix();
double m[16] = {0};
FOR (i, 3) FOR (j, 3) m[4*i+j] = _ar.at<double>(j, i);
m[15]=1.0f;
glMultMatrixd(m);
glTranslated(_t.x/size, _t.y/size, 0);
if (!m_isInitList) {
m_isInitList = true;
InitList(_Z, _texture, size);
}
Mat face = DrawFace(_Z.size(), _Z, _texture);
glPopMatrix();
#ifdef WIN32
SwapBuffers( hDC );
#endif
#ifdef __linux__
glXSwapBuffers(dpy, win);
#endif
return face;
}
void CFadeModule::InitList(const Mat& _Z, const Mat& _texture, float _size) {
// SHOW_IMG(_Z);
// DEBUG_INFO(" CFadeModule::InitList");
m_list = glGenLists(1);
glNewList(m_list, GL_COMPILE );
int width = _Z.cols;
int height = _Z.rows;
int dx[] = {0, 0, 1, 1};
int dy[] = {0, 1, 1, 0};
FOR (w, width-1) {
FOR (h, height-1) {
bool flag = true;
FOR (k, 4) {
flag = flag && (_Z.at<double>(h+dy[k], w+dx[k])>0.0f);
}
if (true) {
glBegin(GL_QUADS);
FOR (k, 4) {
int hh = h + dy[k];
int ww = w + dx[k];
float r = _texture.at<Vec3b>(hh,ww)[2]/255.0f;
float g = _texture.at<Vec3b>(hh,ww)[1]/255.0f;
float b = _texture.at<Vec3b>(hh,ww)[0]/255.0f;
glColor3f(r,g,b);
// glColor3b(1.0, 1.0, 1.0);
float x = ww/_size; //2*(-ww+width/2)/_size;//*(174/224.0);
float y = hh/_size; //2 * (height/2-hh) / _size;
float z = (float)_Z.at<double>(hh,ww)/_size;//103.9104f;
// DEBUG_INFO("(x,y,z) = (%3.3f, %3.3f, %3.3f)", x, y, z);
glVertex3f(x,y,z);
}
glEnd();
}
}
}
glEndList();
}
void CFadeModule::LoadContours() {
string maskpath = "./models/mask.png";
Mat mask = imread(maskpath, 0);
if (mask.empty()) {
DEBUG_ERROR("cannot load mask image (%s)", maskpath.c_str());
}
int dilate_size = 5;
Mat element = getStructuringElement( MORPH_CROSS,
Size( 2*dilate_size + 1, 2*dilate_size+1 ),
Point( dilate_size, dilate_size ) );
erode(mask, mask, element);
Mat threshold_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
// Detect edges using Threshold
threshold(mask, threshold_output, 128, 255, THRESH_BINARY );
//Find contours
findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
PointSeti c = contours[0];
m_countours.clear();
FOR_u (i, c.size())
m_countours.push_back(Point2d(c[i].x, c[i].y));
}
PointSeti CFadeModule::Contours(const Mat& _Z, const Mat& _ar, Point2d _t, const Mat& _H ) {
PointSetd outP;
FOR_u (i, m_countours.size()) {
int w = (int)m_countours[i].x;
int h = (int)m_countours[i].y;
Mat pnt3d = Mat(Size(1, 3), CV_64FC1);
pnt3d.at<double>(0, 0) = w;// +dx[k];
pnt3d.at<double>(1, 0) = h;// +dy[k];
pnt3d.at<double>(2, 0) = m_Z.at<double>(h,w);
Mat pnt2d = _ar * pnt3d;
double nx = pnt2d.at<double>(0, 0)+ _t.x;
double ny = pnt2d.at<double>(1, 0) + _t.y;
outP.push_back(Point2d(nx, ny));
}
PointSetd out = CWarpUtils::ProjPnts(outP, _H);
PointSeti outi;
FOR_u (i, out.size())
outi.push_back(Point2i(roundInt(out[i].x), roundInt(out[i].y)));
return outi;
}
PointSetd CFadeModule::ProjPnts( const Mat& _ar, Point2d _t, const Mat& _H ) {
Mat pnt2d = _ar * m_pnts3d.t();
PointSetd pnts(9);
FOR (i, 9) {
pnts[i].x = pnt2d.at<double>(0, i) + _t.x;
pnts[i].y = pnt2d.at<double>(1, i) + _t.y;
}
PointSetd out = CWarpUtils::ProjPnts(pnts, _H);
return out;
}
| mit |
Biart95/appleseed | src/appleseed/renderer/modeling/edf/edffactoryregistrar.cpp | 1 | 2848 |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "edffactoryregistrar.h"
// appleseed.renderer headers.
#include "renderer/modeling/edf/coneedf.h"
#include "renderer/modeling/edf/diffuseedf.h"
#include "renderer/modeling/edf/edftraits.h"
#include "renderer/modeling/entity/entityfactoryregistrar.h"
// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
using namespace foundation;
namespace renderer
{
APPLESEED_DEFINE_APIARRAY(EDFFactoryArray);
struct EDFFactoryRegistrar::Impl
: public EntityFactoryRegistrarImpl<
EDFFactoryRegistrar::EntityType,
EDFFactoryRegistrar::FactoryType,
EDFFactoryRegistrar::FactoryArrayType
>
{
};
EDFFactoryRegistrar::EDFFactoryRegistrar(const SearchPaths& search_paths)
: impl(new Impl())
{
// Register built-in factories.
impl->register_factory(auto_release_ptr<FactoryType>(new ConeEDFFactory()));
impl->register_factory(auto_release_ptr<FactoryType>(new DiffuseEDFFactory()));
}
EDFFactoryRegistrar::~EDFFactoryRegistrar()
{
delete impl;
}
void EDFFactoryRegistrar::register_factory_plugin(Plugin* plugin, void* plugin_entry_point)
{
impl->register_factory_plugin(plugin, plugin_entry_point);
}
EDFFactoryArray EDFFactoryRegistrar::get_factories() const
{
return impl->get_factories();
}
const EDFFactoryRegistrar::FactoryType* EDFFactoryRegistrar::lookup(const char* name) const
{
return impl->lookup(name);
}
} // namespace renderer
| mit |
rockeet/nark-fsa-intro | samples/regex_submatch.cpp | 1 | 2058 | #define _SCL_SECURE_NO_WARNINGS
#include <nark/fsa/forward_decl.hpp>
#include <nark/fsa/mre_match.hpp>
#include <nark/util/linebuf.hpp>
#include <nark/util/profiling.hpp>
#include <getopt.h>
#include <malloc.h>
using namespace nark;
void match_and_print(MultiRegexSubmatch& sub, fstring text) {
printf("%s ----------\n", text.p);
int max_match_len = sub.match_utf8(text, ::tolower);
for(int j = 0; j < (int)sub.fullmatch_regex().size(); ++j) {
int regex_id = sub.fullmatch_regex()[j];
int nsub = sub.num_submatch(regex_id);
for(int k = 0; k < nsub; ++k) {
fstring str = sub(text.p, regex_id, k);
printf("j=%d regex_id=%d sub(%d): %.*s\n", j, regex_id, k, str.ilen(), str.data());
}
}
printf("max_match_len=%d: %.*s\n", max_match_len, max_match_len, text.p);
}
int main(int argc, char* argv[]) {
const char* bin_meta_file = NULL;
const char* dfa_file = NULL;
bool verbose = false;
for (int opt=0; (opt = getopt(argc, argv, "b:i:v")) != -1; ) {
switch (opt) {
case '?': return 1;
case 'b': bin_meta_file = optarg; break;
case 'i': dfa_file = optarg; break;
case 'v': verbose = true; break;
}
}
if (NULL == bin_meta_file) {
fprintf(stderr, "-b bin_meta_file is required\n");
return 1;
}
if (NULL == dfa_file) {
fprintf(stderr, "loading dfa file from stdin...\n");
DFA_InterfacePtr dfa(DFA_Interface_load(stdin));
MultiRegexSubmatch sub(&*dfa, bin_meta_file);
for (int i = optind; i < argc; ++i) {
match_and_print(sub, argv[i]);
}
}
else {
DFA_InterfacePtr dfa(DFA_Interface_load(dfa_file));
MultiRegexSubmatch sub(&*dfa, bin_meta_file);
nark::LineBuf line;
nark::profiling pf;
long t0 = pf.now();
long lineno = 0;
while (line.getline(stdin) > 0) {
lineno++;
line.chomp();
if (verbose)
match_and_print(sub, fstring(line.p, line.n));
else
sub.match_utf8(fstring(line.p, line.n), ::tolower);
}
long t1 = pf.now();
printf("time=%f's QPS=%f Latency=%f'us\n"
, pf.sf(t0,t1)
, lineno/pf.sf(t0,t1)
, pf.uf(t0,t1)/lineno
);
}
return 0;
}
| mit |
crockeo/cpp-whatisthisgame | src/entities/player.cpp | 1 | 2863 | #include "player.hpp"
//////////////
// Includes //
#include "../observer.hpp"
#include "../events.hpp"
#include "../utils.hpp"
//////////
// Code //
// Creating a new player at a given location.
Player::Player(float x, float y) :
Entity(Rectangle(x, y, Player::width, Player::height)) {
this->dy = 0;
}
// Updating this entity.
void Player::update(GLFWwindow* window, const GameState& gs, float dt) {
bool present = false;
int joystick;
for (joystick = 0; joystick <= GLFW_JOYSTICK_LAST; joystick++) {
if (glfwJoystickPresent(joystick) == GL_TRUE) {
present = true;
break;
}
}
int num;
const unsigned char* bs = glfwGetJoystickButtons(joystick, &num);
bool my = false;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS || (present && bs[12] == GLFW_PRESS)) {
this->dy += ((this->dy < 0 ? Player::decel_speed : 0) + Player::speed) * dt;
my = true;
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS || (present && bs[14] == GLFW_PRESS)) {
this->dy -= ((this->dy > 0 ? Player::decel_speed : 0) + Player::speed) * dt;
my = true;
}
OM& om = OM::instance();
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS || (present && bs[1] == GLFW_PRESS))
om.alert(BulletShootEvent(this->position().x + this->position().w / 2,
this->position().y + this->position().h / 2,
this->dy));
if (!my) {
this->dy = lerp(dy, 0, 0.2f, dt);
}
if (!my && this->dy > -Player::min_speed && this->dy < Player::min_speed)
this->dy = 0;
if (this->dy > Player::max_speed)
this->dy = Player::max_speed;
if (this->dy < -Player::max_speed)
this->dy = -Player::max_speed;
int height;
glfwGetWindowSize(window, nullptr, &height);
if (this->position().y < 0) {
this->dy /= -3;
this->position().y = 0;
}
if (this->position().y + this->position().h > height) {
this->dy /= -3;
this->position().y = height - this->position().h;
}
this->position().y += this->dy * dt;
}
// Providing the initial render for this entity.
void Player::initRender(GLFWwindow* window, const Assets& assets, Renders& renders) const {
renders[0]["player"] = new Render(this->getPosition(),
GL_DYNAMIC_DRAW,
assets.getSSAnimation("player"),
assets.getShader("res/game2d"));
}
// Rendering this entity.
void Player::render(GLFWwindow* window, Renders& renders) const {
renders[0]["player"]->updateVertices(generateRectangle(this->getPosition()),
rectangleOrder(),
GL_DYNAMIC_DRAW);
}
| mit |
armink/SFUD | demo/stm32f2xx_rtt/RT-Thread-2.1.0/components/drivers/serial/serial.c | 1 | 23443 | /*
* File : serial.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team
*
* This program 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Change Logs:
* Date Author Notes
* 2006-03-13 bernard first version
* 2012-05-15 lgnq modified according bernard's implementation.
* 2012-05-28 bernard code cleanup
* 2012-11-23 bernard fix compiler warning.
* 2013-02-20 bernard use RT_SERIAL_RB_BUFSZ to define
* the size of ring buffer.
* 2014-07-10 bernard rewrite serial framework
* 2014-12-31 bernard use open_flag for poll_tx stream mode.
* 2015-05-19 Quintin fix DMA tx mod tx_dma->activated flag !=RT_FALSE BUG
* in open function.
* 2015-11-10 bernard fix the poll rx issue when there is no data.
* 2016-05-10 armink add fifo mode to DMA rx when serial->config.bufsz != 0.
*/
#include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
/*
* Serial poll routines
*/
rt_inline int _serial_poll_rx(struct rt_serial_device *serial, rt_uint8_t *data, int length)
{
int ch;
int size;
RT_ASSERT(serial != RT_NULL);
size = length;
while (length)
{
ch = serial->ops->getc(serial);
if (ch == -1) break;
*data = ch;
data ++; length --;
if (ch == '\n') break;
}
return size - length;
}
rt_inline int _serial_poll_tx(struct rt_serial_device *serial, const rt_uint8_t *data, int length)
{
int size;
RT_ASSERT(serial != RT_NULL);
size = length;
while (length)
{
/*
* to be polite with serial console add a line feed
* to the carriage return character
*/
if (*data == '\n' && (serial->parent.open_flag & RT_DEVICE_FLAG_STREAM))
{
serial->ops->putc(serial, '\r');
}
serial->ops->putc(serial, *data);
++ data;
-- length;
}
return size - length;
}
/*
* Serial interrupt routines
*/
rt_inline int _serial_int_rx(struct rt_serial_device *serial, rt_uint8_t *data, int length)
{
int size;
struct rt_serial_rx_fifo* rx_fifo;
RT_ASSERT(serial != RT_NULL);
size = length;
rx_fifo = (struct rt_serial_rx_fifo*) serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
/* read from software FIFO */
while (length)
{
int ch;
rt_base_t level;
/* disable interrupt */
level = rt_hw_interrupt_disable();
if (rx_fifo->get_index != rx_fifo->put_index)
{
ch = rx_fifo->buffer[rx_fifo->get_index];
rx_fifo->get_index += 1;
if (rx_fifo->get_index >= serial->config.bufsz) rx_fifo->get_index = 0;
}
else
{
/* no data, enable interrupt and break out */
rt_hw_interrupt_enable(level);
break;
}
/* enable interrupt */
rt_hw_interrupt_enable(level);
*data = ch & 0xff;
data ++; length --;
}
return size - length;
}
rt_inline int _serial_int_tx(struct rt_serial_device *serial, const rt_uint8_t *data, int length)
{
int size;
struct rt_serial_tx_fifo *tx;
RT_ASSERT(serial != RT_NULL);
size = length;
tx = (struct rt_serial_tx_fifo*) serial->serial_tx;
RT_ASSERT(tx != RT_NULL);
while (length)
{
if (serial->ops->putc(serial, *(char*)data) == -1)
{
rt_completion_wait(&(tx->completion), RT_WAITING_FOREVER);
continue;
}
data ++; length --;
}
return size - length;
}
/**
* Calculate DMA received data length.
*
* @param serial serial device
*
* @return length
*/
static rt_size_t rt_dma_calc_recved_len(struct rt_serial_device *serial) {
static rt_size_t rx_length;
struct rt_serial_rx_fifo *rx_fifo = (struct rt_serial_rx_fifo *)serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
rx_length = (rx_fifo->put_index >= rx_fifo->get_index)? (rx_fifo->put_index - rx_fifo->get_index):
(serial->config.bufsz - (rx_fifo->get_index - rx_fifo->put_index));
return rx_length;
}
/**
* Read data finish by DMA mode then update the gut index for receive fifo.
*
* @param serial serial device
* @param len get data length for this operate
*/
static void rt_dma_recv_update_get_index(struct rt_serial_device *serial, rt_size_t len) {
struct rt_serial_rx_fifo *rx_fifo = (struct rt_serial_rx_fifo *)serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
RT_ASSERT(len <= rt_dma_calc_recved_len(serial));
rx_fifo->get_index += len;
if (rx_fifo->get_index > serial->config.bufsz ) {
rx_fifo->get_index -= serial->config.bufsz;
}
}
/**
* DMA received finish then update put index for receive fifo.
*
* @param serial serial device
* @param len received length for this transmit
*/
static void rt_dma_recv_update_put_index(struct rt_serial_device *serial, rt_size_t len) {
struct rt_serial_rx_fifo *rx_fifo = (struct rt_serial_rx_fifo *)serial->serial_rx;
rt_size_t i;
RT_ASSERT(rx_fifo != RT_NULL);
if (rx_fifo->get_index <= rx_fifo->put_index) {
rx_fifo->put_index += len;
/* beyond the fifo end */
if (rx_fifo->put_index >= serial->config.bufsz) {
for (i = 0; i <= len / serial->config.bufsz; i++) {
rx_fifo->put_index -= serial->config.bufsz;
}
/* force overwrite get index */
if (rx_fifo->put_index >= rx_fifo->get_index) {
rx_fifo->get_index = rx_fifo->put_index + 1;
}
}
} else {
rx_fifo->put_index += len;
if(rx_fifo->put_index >= rx_fifo->get_index) {
/* beyond the fifo end */
if(rx_fifo->put_index >= serial->config.bufsz) {
for (i = 0; i <= len / serial->config.bufsz; i++) {
rx_fifo->put_index -= serial->config.bufsz;
}
}
/* force overwrite get index */
rx_fifo->get_index = rx_fifo->put_index + 1;
}
}
}
/*
* Serial DMA routines
*/
rt_inline int _serial_dma_rx(struct rt_serial_device *serial, rt_uint8_t *data, int length)
{
rt_base_t level;
RT_ASSERT((serial != RT_NULL) && (data != RT_NULL));
level = rt_hw_interrupt_disable();
if (serial->config.bufsz == 0) {
int result = RT_EOK;
struct rt_serial_rx_dma *rx_dma;
rx_dma = (struct rt_serial_rx_dma*)serial->serial_rx;
RT_ASSERT(rx_dma != RT_NULL);
if (rx_dma->activated != RT_TRUE)
{
rx_dma->activated = RT_TRUE;
RT_ASSERT(serial->ops->dma_transmit != RT_NULL);
serial->ops->dma_transmit(serial, data, length, RT_SERIAL_DMA_RX);
}
else result = -RT_EBUSY;
rt_hw_interrupt_enable(level);
if (result == RT_EOK) return length;
rt_set_errno(result);
return 0;
} else {
struct rt_serial_rx_fifo *rx_fifo = (struct rt_serial_rx_fifo *) serial->serial_rx;
rt_size_t recv_len = 0, fifo_recved_len = rt_dma_calc_recved_len(serial);
RT_ASSERT(rx_fifo != RT_NULL);
if (length < fifo_recved_len) {
recv_len = length;
} else {
recv_len = fifo_recved_len;
}
if (rx_fifo->get_index + recv_len < serial->config.bufsz) {
rt_memcpy(data, rx_fifo->buffer + rx_fifo->get_index, recv_len);
} else {
rt_memcpy(data, rx_fifo->buffer + rx_fifo->get_index,
serial->config.bufsz - rx_fifo->get_index);
rt_memcpy(data + serial->config.bufsz - rx_fifo->get_index, rx_fifo->buffer,
recv_len + rx_fifo->get_index - serial->config.bufsz);
}
rt_dma_recv_update_get_index(serial, recv_len);
rt_hw_interrupt_enable(level);
return recv_len;
}
}
rt_inline int _serial_dma_tx(struct rt_serial_device *serial, const rt_uint8_t *data, int length)
{
rt_base_t level;
rt_err_t result;
struct rt_serial_tx_dma *tx_dma;
tx_dma = (struct rt_serial_tx_dma*)(serial->serial_tx);
result = rt_data_queue_push(&(tx_dma->data_queue), data, length, RT_WAITING_FOREVER);
if (result == RT_EOK)
{
level = rt_hw_interrupt_disable();
if (tx_dma->activated != RT_TRUE)
{
tx_dma->activated = RT_TRUE;
rt_hw_interrupt_enable(level);
/* make a DMA transfer */
serial->ops->dma_transmit(serial, (rt_uint8_t *)data, length, RT_SERIAL_DMA_TX);
}
else
{
rt_hw_interrupt_enable(level);
}
return length;
}
else
{
rt_set_errno(result);
return 0;
}
}
/* RT-Thread Device Interface */
/*
* This function initializes serial device.
*/
static rt_err_t rt_serial_init(struct rt_device *dev)
{
rt_err_t result = RT_EOK;
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
serial = (struct rt_serial_device *)dev;
/* initialize rx/tx */
serial->serial_rx = RT_NULL;
serial->serial_tx = RT_NULL;
/* apply configuration */
if (serial->ops->configure)
result = serial->ops->configure(serial, &serial->config);
return result;
}
static rt_err_t rt_serial_open(struct rt_device *dev, rt_uint16_t oflag)
{
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
serial = (struct rt_serial_device *)dev;
/* check device flag with the open flag */
if ((oflag & RT_DEVICE_FLAG_DMA_RX) && !(dev->flag & RT_DEVICE_FLAG_DMA_RX))
return -RT_EIO;
if ((oflag & RT_DEVICE_FLAG_DMA_TX) && !(dev->flag & RT_DEVICE_FLAG_DMA_TX))
return -RT_EIO;
if ((oflag & RT_DEVICE_FLAG_INT_RX) && !(dev->flag & RT_DEVICE_FLAG_INT_RX))
return -RT_EIO;
if ((oflag & RT_DEVICE_FLAG_INT_TX) && !(dev->flag & RT_DEVICE_FLAG_INT_TX))
return -RT_EIO;
/* get open flags */
dev->open_flag = oflag & 0xff;
/* initialize the Rx/Tx structure according to open flag */
if (serial->serial_rx == RT_NULL)
{
if (oflag & RT_DEVICE_FLAG_DMA_RX)
{
if (serial->config.bufsz == 0) {
struct rt_serial_rx_dma* rx_dma;
rx_dma = (struct rt_serial_rx_dma*) rt_malloc (sizeof(struct rt_serial_rx_dma));
RT_ASSERT(rx_dma != RT_NULL);
rx_dma->activated = RT_FALSE;
serial->serial_rx = rx_dma;
} else {
struct rt_serial_rx_fifo* rx_fifo;
rx_fifo = (struct rt_serial_rx_fifo*) rt_malloc (sizeof(struct rt_serial_rx_fifo) +
serial->config.bufsz);
RT_ASSERT(rx_fifo != RT_NULL);
rx_fifo->buffer = (rt_uint8_t*) (rx_fifo + 1);
rt_memset(rx_fifo->buffer, 0, serial->config.bufsz);
rx_fifo->put_index = 0;
rx_fifo->get_index = 0;
serial->serial_rx = rx_fifo;
/* configure fifo address and length to low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_CONFIG, (void *) RT_DEVICE_FLAG_DMA_RX);
}
dev->open_flag |= RT_DEVICE_FLAG_DMA_RX;
}
else if (oflag & RT_DEVICE_FLAG_INT_RX)
{
struct rt_serial_rx_fifo* rx_fifo;
rx_fifo = (struct rt_serial_rx_fifo*) rt_malloc (sizeof(struct rt_serial_rx_fifo) +
serial->config.bufsz);
RT_ASSERT(rx_fifo != RT_NULL);
rx_fifo->buffer = (rt_uint8_t*) (rx_fifo + 1);
rt_memset(rx_fifo->buffer, 0, serial->config.bufsz);
rx_fifo->put_index = 0;
rx_fifo->get_index = 0;
serial->serial_rx = rx_fifo;
dev->open_flag |= RT_DEVICE_FLAG_INT_RX;
/* configure low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_SET_INT, (void *)RT_DEVICE_FLAG_INT_RX);
}
else
{
serial->serial_rx = RT_NULL;
}
}
if (serial->serial_tx == RT_NULL)
{
if (oflag & RT_DEVICE_FLAG_DMA_TX)
{
struct rt_serial_tx_dma* tx_dma;
tx_dma = (struct rt_serial_tx_dma*) rt_malloc (sizeof(struct rt_serial_tx_dma));
RT_ASSERT(tx_dma != RT_NULL);
tx_dma->activated = RT_FALSE;
rt_data_queue_init(&(tx_dma->data_queue), 8, 4, RT_NULL);
serial->serial_tx = tx_dma;
dev->open_flag |= RT_DEVICE_FLAG_DMA_TX;
}
else if (oflag & RT_DEVICE_FLAG_INT_TX)
{
struct rt_serial_tx_fifo *tx_fifo;
tx_fifo = (struct rt_serial_tx_fifo*) rt_malloc(sizeof(struct rt_serial_tx_fifo));
RT_ASSERT(tx_fifo != RT_NULL);
rt_completion_init(&(tx_fifo->completion));
serial->serial_tx = tx_fifo;
dev->open_flag |= RT_DEVICE_FLAG_INT_TX;
/* configure low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_SET_INT, (void *)RT_DEVICE_FLAG_INT_TX);
}
else
{
serial->serial_tx = RT_NULL;
}
}
return RT_EOK;
}
static rt_err_t rt_serial_close(struct rt_device *dev)
{
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
serial = (struct rt_serial_device *)dev;
/* this device has more reference count */
if (dev->ref_count > 1) return RT_EOK;
if (dev->open_flag & RT_DEVICE_FLAG_INT_RX)
{
struct rt_serial_rx_fifo* rx_fifo;
rx_fifo = (struct rt_serial_rx_fifo*)serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
rt_free(rx_fifo);
serial->serial_rx = RT_NULL;
dev->open_flag &= ~RT_DEVICE_FLAG_INT_RX;
/* configure low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void*)RT_DEVICE_FLAG_INT_RX);
}
else if (dev->open_flag & RT_DEVICE_FLAG_DMA_RX)
{
if (serial->config.bufsz == 0) {
struct rt_serial_rx_dma* rx_dma;
rx_dma = (struct rt_serial_rx_dma*)serial->serial_rx;
RT_ASSERT(rx_dma != RT_NULL);
rt_free(rx_dma);
} else {
struct rt_serial_rx_fifo* rx_fifo;
rx_fifo = (struct rt_serial_rx_fifo*)serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
rt_free(rx_fifo);
}
/* configure low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void *) RT_DEVICE_FLAG_DMA_RX);
serial->serial_rx = RT_NULL;
dev->open_flag &= ~RT_DEVICE_FLAG_DMA_RX;
}
if (dev->open_flag & RT_DEVICE_FLAG_INT_TX)
{
struct rt_serial_tx_fifo* tx_fifo;
tx_fifo = (struct rt_serial_tx_fifo*)serial->serial_tx;
RT_ASSERT(tx_fifo != RT_NULL);
rt_free(tx_fifo);
serial->serial_tx = RT_NULL;
dev->open_flag &= ~RT_DEVICE_FLAG_INT_TX;
/* configure low level device */
serial->ops->control(serial, RT_DEVICE_CTRL_CLR_INT, (void*)RT_DEVICE_FLAG_INT_TX);
}
else if (dev->open_flag & RT_DEVICE_FLAG_DMA_TX)
{
struct rt_serial_tx_dma* tx_dma;
tx_dma = (struct rt_serial_tx_dma*)serial->serial_tx;
RT_ASSERT(tx_dma != RT_NULL);
rt_free(tx_dma);
serial->serial_tx = RT_NULL;
dev->open_flag &= ~RT_DEVICE_FLAG_DMA_TX;
}
return RT_EOK;
}
static rt_size_t rt_serial_read(struct rt_device *dev,
rt_off_t pos,
void *buffer,
rt_size_t size)
{
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
if (size == 0) return 0;
serial = (struct rt_serial_device *)dev;
if (dev->open_flag & RT_DEVICE_FLAG_INT_RX)
{
return _serial_int_rx(serial, buffer, size);
}
else if (dev->open_flag & RT_DEVICE_FLAG_DMA_RX)
{
return _serial_dma_rx(serial, buffer, size);
}
return _serial_poll_rx(serial, buffer, size);
}
static rt_size_t rt_serial_write(struct rt_device *dev,
rt_off_t pos,
const void *buffer,
rt_size_t size)
{
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
if (size == 0) return 0;
serial = (struct rt_serial_device *)dev;
if (dev->open_flag & RT_DEVICE_FLAG_INT_TX)
{
return _serial_int_tx(serial, buffer, size);
}
else if (dev->open_flag & RT_DEVICE_FLAG_DMA_TX)
{
return _serial_dma_tx(serial, buffer, size);
}
else
{
return _serial_poll_tx(serial, buffer, size);
}
}
static rt_err_t rt_serial_control(struct rt_device *dev,
rt_uint8_t cmd,
void *args)
{
struct rt_serial_device *serial;
RT_ASSERT(dev != RT_NULL);
serial = (struct rt_serial_device *)dev;
switch (cmd)
{
case RT_DEVICE_CTRL_SUSPEND:
/* suspend device */
dev->flag |= RT_DEVICE_FLAG_SUSPENDED;
break;
case RT_DEVICE_CTRL_RESUME:
/* resume device */
dev->flag &= ~RT_DEVICE_FLAG_SUSPENDED;
break;
case RT_DEVICE_CTRL_CONFIG:
/* configure device */
serial->ops->configure(serial, (struct serial_configure *)args);
break;
default :
/* control device */
serial->ops->control(serial, cmd, args);
break;
}
return RT_EOK;
}
/*
* serial register
*/
rt_err_t rt_hw_serial_register(struct rt_serial_device *serial,
const char *name,
rt_uint32_t flag,
void *data)
{
struct rt_device *device;
RT_ASSERT(serial != RT_NULL);
device = &(serial->parent);
device->type = RT_Device_Class_Char;
device->rx_indicate = RT_NULL;
device->tx_complete = RT_NULL;
device->init = rt_serial_init;
device->open = rt_serial_open;
device->close = rt_serial_close;
device->read = rt_serial_read;
device->write = rt_serial_write;
device->control = rt_serial_control;
device->user_data = data;
/* register a character device */
return rt_device_register(device, name, flag);
}
/* ISR for serial interrupt */
void rt_hw_serial_isr(struct rt_serial_device *serial, int event)
{
switch (event & 0xff)
{
case RT_SERIAL_EVENT_RX_IND:
{
int ch = -1;
rt_base_t level;
struct rt_serial_rx_fifo* rx_fifo;
/* interrupt mode receive */
rx_fifo = (struct rt_serial_rx_fifo*)serial->serial_rx;
RT_ASSERT(rx_fifo != RT_NULL);
while (1)
{
ch = serial->ops->getc(serial);
if (ch == -1) break;
/* disable interrupt */
level = rt_hw_interrupt_disable();
rx_fifo->buffer[rx_fifo->put_index] = ch;
rx_fifo->put_index += 1;
if (rx_fifo->put_index >= serial->config.bufsz) rx_fifo->put_index = 0;
/* if the next position is read index, discard this 'read char' */
if (rx_fifo->put_index == rx_fifo->get_index)
{
rx_fifo->get_index += 1;
if (rx_fifo->get_index >= serial->config.bufsz) rx_fifo->get_index = 0;
}
/* enable interrupt */
rt_hw_interrupt_enable(level);
}
/* invoke callback */
if (serial->parent.rx_indicate != RT_NULL)
{
rt_size_t rx_length;
/* get rx length */
level = rt_hw_interrupt_disable();
rx_length = (rx_fifo->put_index >= rx_fifo->get_index)? (rx_fifo->put_index - rx_fifo->get_index):
(serial->config.bufsz - (rx_fifo->get_index - rx_fifo->put_index));
rt_hw_interrupt_enable(level);
serial->parent.rx_indicate(&serial->parent, rx_length);
}
break;
}
case RT_SERIAL_EVENT_TX_DONE:
{
struct rt_serial_tx_fifo* tx_fifo;
tx_fifo = (struct rt_serial_tx_fifo*)serial->serial_tx;
rt_completion_done(&(tx_fifo->completion));
break;
}
case RT_SERIAL_EVENT_TX_DMADONE:
{
const void *data_ptr;
rt_size_t data_size;
const void *last_data_ptr;
struct rt_serial_tx_dma* tx_dma;
tx_dma = (struct rt_serial_tx_dma*) serial->serial_tx;
rt_data_queue_pop(&(tx_dma->data_queue), &last_data_ptr, &data_size, 0);
if (rt_data_queue_peak(&(tx_dma->data_queue), &data_ptr, &data_size) == RT_EOK)
{
/* transmit next data node */
tx_dma->activated = RT_TRUE;
serial->ops->dma_transmit(serial, (rt_uint8_t *)data_ptr, data_size, RT_SERIAL_DMA_TX);
}
else
{
tx_dma->activated = RT_FALSE;
}
/* invoke callback */
if (serial->parent.tx_complete != RT_NULL)
{
serial->parent.tx_complete(&serial->parent, (void*)last_data_ptr);
}
break;
}
case RT_SERIAL_EVENT_RX_DMADONE:
{
int length;
/* get DMA rx length */
length = (event & (~0xff)) >> 8;
if (serial->config.bufsz == 0) {
struct rt_serial_rx_dma* rx_dma;
rx_dma = (struct rt_serial_rx_dma*)serial->serial_rx;
RT_ASSERT(rx_dma != RT_NULL);
RT_ASSERT(serial->parent.rx_indicate != RT_NULL);
serial->parent.rx_indicate(&(serial->parent), length);
rx_dma->activated = RT_FALSE;
} else {
/* update fifo put index */
rt_dma_recv_update_put_index(serial, length);
/* invoke callback */
if (serial->parent.rx_indicate != RT_NULL) {
serial->parent.rx_indicate(&(serial->parent), rt_dma_calc_recved_len(serial));
}
}
break;
}
}
}
| mit |
johnnylee/jlsampler2 | ringbuffer.c | 1 | 1037 | #include "ringbuffer.h"
#include "mem.h"
struct RingBuffer {
int size;
jack_ringbuffer_t *buf;
};
RingBuffer *ringbuf_new(int size)
{
RingBuffer *rb = malloc_exit(sizeof(RingBuffer));
rb->size = size;
rb->buf = jack_ringbuffer_create(sizeof(void *) * size);
return rb;
}
void ringbuf_free(RingBuffer * rb)
{
jack_ringbuffer_free(rb->buf);
free(rb);
}
int ringbuf_size(RingBuffer * rb)
{
return rb->size;
}
inline int ringbuf_count(RingBuffer * rb)
{
return jack_ringbuffer_read_space(rb->buf) / sizeof(void *);
}
inline bool ringbuf_put(RingBuffer * rb, void *data)
{
int writeSpace = jack_ringbuffer_write_space(rb->buf);
if (writeSpace < sizeof(void *)) {
return false;
}
jack_ringbuffer_write(rb->buf, (char *)(&data), sizeof(void *));
return true;
}
inline void *ringbuf_get(RingBuffer * rb)
{
if (ringbuf_count(rb) == 0) {
return NULL;
}
void *data;
jack_ringbuffer_read(rb->buf, (char *)(&data), sizeof(void *));
return data;
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.