Untabify C files. Will watch buildbots.

This commit is contained in:
Antoine Pitrou 2010-05-09 14:46:46 +00:00
parent 368ede83d9
commit c83ea137d7
318 changed files with 198669 additions and 198669 deletions

View file

@ -6,40 +6,40 @@ void initxyzzy(void); /* Forward */
main(int argc, char **argv)
{
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Add a static module */
initxyzzy();
/* Add a static module */
initxyzzy();
/* Define sys.argv. It is up to the application if you
want this; you can also let it undefined (since the Python
code is generally not a main program it has no business
touching sys.argv...) */
PySys_SetArgv(argc, argv);
/* Define sys.argv. It is up to the application if you
want this; you can also let it undefined (since the Python
code is generally not a main program it has no business
touching sys.argv...) */
PySys_SetArgv(argc, argv);
/* Do some application specific code */
printf("Hello, brave new world\n\n");
/* Do some application specific code */
printf("Hello, brave new world\n\n");
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
PyRun_SimpleString("print sys.builtin_module_names\n");
PyRun_SimpleString("print sys.modules.keys()\n");
PyRun_SimpleString("print sys.executable\n");
PyRun_SimpleString("print sys.argv\n");
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
PyRun_SimpleString("print sys.builtin_module_names\n");
PyRun_SimpleString("print sys.modules.keys()\n");
PyRun_SimpleString("print sys.executable\n");
PyRun_SimpleString("print sys.argv\n");
/* Note that you can call any public function of the Python
interpreter here, e.g. call_object(). */
/* Note that you can call any public function of the Python
interpreter here, e.g. call_object(). */
/* Some more application specific code */
printf("\nGoodbye, cruel world\n");
/* Some more application specific code */
printf("\nGoodbye, cruel world\n");
/* Exit, cleaning up the interpreter */
Py_Exit(0);
/*NOTREACHED*/
/* Exit, cleaning up the interpreter */
Py_Exit(0);
/*NOTREACHED*/
}
/* A static module */
@ -48,18 +48,18 @@ main(int argc, char **argv)
static PyObject *
xyzzy_foo(PyObject *self, PyObject* args)
{
return PyInt_FromLong(42L);
return PyInt_FromLong(42L);
}
static PyMethodDef xyzzy_methods[] = {
{"foo", xyzzy_foo, METH_NOARGS,
"Return the meaning of everything."},
{NULL, NULL} /* sentinel */
{"foo", xyzzy_foo, METH_NOARGS,
"Return the meaning of everything."},
{NULL, NULL} /* sentinel */
};
void
initxyzzy(void)
{
PyImport_AddModule("xyzzy");
Py_InitModule("xyzzy", xyzzy_methods);
PyImport_AddModule("xyzzy");
Py_InitModule("xyzzy", xyzzy_methods);
}

View file

@ -6,28 +6,28 @@
main(int argc, char **argv)
{
int count = -1;
char *command;
int count = -1;
char *command;
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: loop <python-command> [count]\n");
exit(2);
}
command = argv[1];
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: loop <python-command> [count]\n");
exit(2);
}
command = argv[1];
if (argc == 3) {
count = atoi(argv[2]);
}
if (argc == 3) {
count = atoi(argv[2]);
}
Py_SetProgramName(argv[0]);
Py_SetProgramName(argv[0]);
/* uncomment this if you don't want to load site.py */
/* Py_NoSiteFlag = 1; */
/* uncomment this if you don't want to load site.py */
/* Py_NoSiteFlag = 1; */
while (count == -1 || --count >= 0 ) {
Py_Initialize();
PyRun_SimpleString(command);
Py_Finalize();
}
return 0;
while (count == -1 || --count >= 0 ) {
Py_Initialize();
PyRun_SimpleString(command);
Py_Finalize();
}
return 0;
}

View file

@ -34,8 +34,8 @@ extern int Py_VerboseFlag;
#endif
struct workorder {
int conn;
struct sockaddr_in addr;
int conn;
struct sockaddr_in addr;
};
/* Forward */
@ -55,40 +55,40 @@ static PyThreadState *gtstate;
main(int argc, char **argv)
{
int port = PORT;
int c;
int port = PORT;
int c;
if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
progname = argv[0];
if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
progname = argv[0];
while ((c = getopt(argc, argv, "v")) != EOF) {
switch (c) {
case 'v':
Py_VerboseFlag++;
break;
default:
usage();
}
}
while ((c = getopt(argc, argv, "v")) != EOF) {
switch (c) {
case 'v':
Py_VerboseFlag++;
break;
default:
usage();
}
}
if (optind < argc) {
if (optind+1 < argc) {
oprogname();
fprintf(stderr, "too many arguments\n");
usage();
}
port = atoi(argv[optind]);
if (port <= 0) {
fprintf(stderr, "bad port (%s)\n", argv[optind]);
usage();
}
}
if (optind < argc) {
if (optind+1 < argc) {
oprogname();
fprintf(stderr, "too many arguments\n");
usage();
}
port = atoi(argv[optind]);
if (port <= 0) {
fprintf(stderr, "bad port (%s)\n", argv[optind]);
usage();
}
}
main_thread(port);
main_thread(port);
fprintf(stderr, "Bye.\n");
fprintf(stderr, "Bye.\n");
exit(0);
exit(0);
}
static char usage_line[] = "usage: %s [port]\n";
@ -96,120 +96,120 @@ static char usage_line[] = "usage: %s [port]\n";
static void
usage(void)
{
fprintf(stderr, usage_line, progname);
exit(2);
fprintf(stderr, usage_line, progname);
exit(2);
}
static void
main_thread(int port)
{
int sock, conn, size, i;
struct sockaddr_in addr, clientaddr;
int sock, conn, size, i;
struct sockaddr_in addr, clientaddr;
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
oprogname();
perror("can't create socket");
exit(1);
}
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
oprogname();
perror("can't create socket");
exit(1);
}
#ifdef SO_REUSEADDR
i = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
i = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
#endif
memset((char *)&addr, '\0', sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = 0L;
if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
oprogname();
perror("can't bind socket to address");
exit(1);
}
memset((char *)&addr, '\0', sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = 0L;
if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
oprogname();
perror("can't bind socket to address");
exit(1);
}
if (listen(sock, 5) < 0) {
oprogname();
perror("can't listen on socket");
exit(1);
}
if (listen(sock, 5) < 0) {
oprogname();
perror("can't listen on socket");
exit(1);
}
fprintf(stderr, "Listening on port %d...\n", port);
fprintf(stderr, "Listening on port %d...\n", port);
for (i = 0; ; i++) {
size = sizeof clientaddr;
memset((char *) &clientaddr, '\0', size);
conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
if (conn < 0) {
oprogname();
perror("can't accept connection from socket");
exit(1);
}
for (i = 0; ; i++) {
size = sizeof clientaddr;
memset((char *) &clientaddr, '\0', size);
conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
if (conn < 0) {
oprogname();
perror("can't accept connection from socket");
exit(1);
}
size = sizeof addr;
memset((char *) &addr, '\0', size);
if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
oprogname();
perror("can't get socket name of connection");
exit(1);
}
if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
oprogname();
perror("connection from non-local host refused");
fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
ntohl(addr.sin_addr.s_addr),
ntohl(clientaddr.sin_addr.s_addr));
close(conn);
continue;
}
if (i == 4) {
close(conn);
break;
}
create_thread(conn, &clientaddr);
}
size = sizeof addr;
memset((char *) &addr, '\0', size);
if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
oprogname();
perror("can't get socket name of connection");
exit(1);
}
if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
oprogname();
perror("connection from non-local host refused");
fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
ntohl(addr.sin_addr.s_addr),
ntohl(clientaddr.sin_addr.s_addr));
close(conn);
continue;
}
if (i == 4) {
close(conn);
break;
}
create_thread(conn, &clientaddr);
}
close(sock);
close(sock);
if (gtstate) {
PyEval_AcquireThread(gtstate);
gtstate = NULL;
Py_Finalize();
/* And a second time, just because we can. */
Py_Finalize(); /* This should be harmless. */
}
exit(0);
if (gtstate) {
PyEval_AcquireThread(gtstate);
gtstate = NULL;
Py_Finalize();
/* And a second time, just because we can. */
Py_Finalize(); /* This should be harmless. */
}
exit(0);
}
static void
create_thread(int conn, struct sockaddr_in *addr)
{
struct workorder *work;
pthread_t tdata;
struct workorder *work;
pthread_t tdata;
work = malloc(sizeof(struct workorder));
if (work == NULL) {
oprogname();
fprintf(stderr, "out of memory for thread.\n");
close(conn);
return;
}
work->conn = conn;
work->addr = *addr;
work = malloc(sizeof(struct workorder));
if (work == NULL) {
oprogname();
fprintf(stderr, "out of memory for thread.\n");
close(conn);
return;
}
work->conn = conn;
work->addr = *addr;
init_python();
init_python();
if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
oprogname();
perror("can't create new thread");
close(conn);
return;
}
if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
oprogname();
perror("can't create new thread");
close(conn);
return;
}
if (pthread_detach(tdata) < 0) {
oprogname();
perror("can't detach from thread");
}
if (pthread_detach(tdata) < 0) {
oprogname();
perror("can't detach from thread");
}
}
static PyThreadState *the_tstate;
@ -219,152 +219,152 @@ static PyObject *the_builtins;
static void
init_python(void)
{
if (gtstate)
return;
Py_Initialize(); /* Initialize the interpreter */
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
gtstate = PyEval_SaveThread(); /* Release the thread state */
if (gtstate)
return;
Py_Initialize(); /* Initialize the interpreter */
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
gtstate = PyEval_SaveThread(); /* Release the thread state */
}
static void *
service_thread(struct workorder *work)
{
FILE *input, *output;
FILE *input, *output;
fprintf(stderr, "Start thread for connection %d.\n", work->conn);
fprintf(stderr, "Start thread for connection %d.\n", work->conn);
ps();
ps();
input = fdopen(work->conn, "r");
if (input == NULL) {
oprogname();
perror("can't create input stream");
goto done;
}
input = fdopen(work->conn, "r");
if (input == NULL) {
oprogname();
perror("can't create input stream");
goto done;
}
output = fdopen(work->conn, "w");
if (output == NULL) {
oprogname();
perror("can't create output stream");
fclose(input);
goto done;
}
output = fdopen(work->conn, "w");
if (output == NULL) {
oprogname();
perror("can't create output stream");
fclose(input);
goto done;
}
setvbuf(input, NULL, _IONBF, 0);
setvbuf(output, NULL, _IONBF, 0);
setvbuf(input, NULL, _IONBF, 0);
setvbuf(output, NULL, _IONBF, 0);
run_interpreter(input, output);
run_interpreter(input, output);
fclose(input);
fclose(output);
fclose(input);
fclose(output);
done:
fprintf(stderr, "End thread for connection %d.\n", work->conn);
close(work->conn);
free(work);
fprintf(stderr, "End thread for connection %d.\n", work->conn);
close(work->conn);
free(work);
}
static void
oprogname(void)
{
int save = errno;
fprintf(stderr, "%s: ", progname);
errno = save;
int save = errno;
fprintf(stderr, "%s: ", progname);
errno = save;
}
static void
run_interpreter(FILE *input, FILE *output)
{
PyThreadState *tstate;
PyObject *new_stdin, *new_stdout;
PyObject *mainmod, *globals;
char buffer[1000];
char *p, *q;
int n, end;
PyThreadState *tstate;
PyObject *new_stdin, *new_stdout;
PyObject *mainmod, *globals;
char buffer[1000];
char *p, *q;
int n, end;
PyEval_AcquireLock();
tstate = Py_NewInterpreter();
if (tstate == NULL) {
fprintf(output, "Sorry -- can't create an interpreter\n");
return;
}
PyEval_AcquireLock();
tstate = Py_NewInterpreter();
if (tstate == NULL) {
fprintf(output, "Sorry -- can't create an interpreter\n");
return;
}
mainmod = PyImport_AddModule("__main__");
globals = PyModule_GetDict(mainmod);
Py_INCREF(globals);
mainmod = PyImport_AddModule("__main__");
globals = PyModule_GetDict(mainmod);
Py_INCREF(globals);
new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
PySys_SetObject("stdin", new_stdin);
PySys_SetObject("stdout", new_stdout);
PySys_SetObject("stderr", new_stdout);
PySys_SetObject("stdin", new_stdin);
PySys_SetObject("stdout", new_stdout);
PySys_SetObject("stderr", new_stdout);
for (n = 1; !PyErr_Occurred(); n++) {
Py_BEGIN_ALLOW_THREADS
fprintf(output, "%d> ", n);
p = fgets(buffer, sizeof buffer, input);
Py_END_ALLOW_THREADS
for (n = 1; !PyErr_Occurred(); n++) {
Py_BEGIN_ALLOW_THREADS
fprintf(output, "%d> ", n);
p = fgets(buffer, sizeof buffer, input);
Py_END_ALLOW_THREADS
if (p == NULL)
break;
if (p[0] == '\377' && p[1] == '\354')
break;
if (p == NULL)
break;
if (p[0] == '\377' && p[1] == '\354')
break;
q = strrchr(p, '\r');
if (q && q[1] == '\n' && q[2] == '\0') {
*q++ = '\n';
*q++ = '\0';
}
q = strrchr(p, '\r');
if (q && q[1] == '\n' && q[2] == '\0') {
*q++ = '\n';
*q++ = '\0';
}
while (*p && isspace(*p))
p++;
if (p[0] == '#' || p[0] == '\0')
continue;
while (*p && isspace(*p))
p++;
if (p[0] == '#' || p[0] == '\0')
continue;
end = run_command(buffer, globals);
if (end < 0)
PyErr_Print();
end = run_command(buffer, globals);
if (end < 0)
PyErr_Print();
if (end)
break;
}
if (end)
break;
}
Py_XDECREF(globals);
Py_XDECREF(new_stdin);
Py_XDECREF(new_stdout);
Py_XDECREF(globals);
Py_XDECREF(new_stdin);
Py_XDECREF(new_stdout);
Py_EndInterpreter(tstate);
PyEval_ReleaseLock();
Py_EndInterpreter(tstate);
PyEval_ReleaseLock();
fprintf(output, "Goodbye!\n");
fprintf(output, "Goodbye!\n");
}
static int
run_command(char *buffer, PyObject *globals)
{
PyObject *m, *d, *v;
fprintf(stderr, "run_command: %s", buffer);
if (strchr(buffer, '\n') == NULL)
fprintf(stderr, "\n");
v = PyRun_String(buffer, Py_single_input, globals, globals);
if (v == NULL) {
if (PyErr_Occurred() == PyExc_SystemExit) {
PyErr_Clear();
return 1;
}
PyErr_Print();
return 0;
}
Py_DECREF(v);
return 0;
PyObject *m, *d, *v;
fprintf(stderr, "run_command: %s", buffer);
if (strchr(buffer, '\n') == NULL)
fprintf(stderr, "\n");
v = PyRun_String(buffer, Py_single_input, globals, globals);
if (v == NULL) {
if (PyErr_Occurred() == PyExc_SystemExit) {
PyErr_Clear();
return 1;
}
PyErr_Print();
return 0;
}
Py_DECREF(v);
return 0;
}
static void
ps(void)
{
char buffer[100];
PyOS_snprintf(buffer, sizeof(buffer),
"ps -l -p %d </dev/null | sed 1d\n", getpid());
system(buffer);
char buffer[100];
PyOS_snprintf(buffer, sizeof(buffer),
"ps -l -p %d </dev/null | sed 1d\n", getpid());
system(buffer);
}

File diff suppressed because it is too large Load diff

View file

@ -8,11 +8,11 @@ extern "C" {
/* Interface to random parts in ceval.c */
PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
PyObject *, PyObject *, PyObject *);
PyObject *, PyObject *, PyObject *);
/* Inline this */
#define PyEval_CallObject(func,arg) \
PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj,
const char *format, ...);
@ -46,10 +46,10 @@ PyAPI_FUNC(void) Py_SetRecursionLimit(int);
PyAPI_FUNC(int) Py_GetRecursionLimit(void);
#define Py_EnterRecursiveCall(where) \
(_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \
_Py_CheckRecursiveCall(where))
#define Py_LeaveRecursiveCall() \
(--PyThreadState_GET()->recursion_depth)
(_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \
_Py_CheckRecursiveCall(where))
#define Py_LeaveRecursiveCall() \
(--PyThreadState_GET()->recursion_depth)
PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where);
PyAPI_DATA(int) _Py_CheckRecursionLimit;
#ifdef USE_STACKCHECK
@ -75,31 +75,31 @@ PyAPI_DATA(int) _Py_CheckInterval;
that lasts a long time and doesn't touch Python data) can allow other
threads to run as follows:
...preparations here...
Py_BEGIN_ALLOW_THREADS
...blocking system call here...
Py_END_ALLOW_THREADS
...interpret result here...
...preparations here...
Py_BEGIN_ALLOW_THREADS
...blocking system call here...
Py_END_ALLOW_THREADS
...interpret result here...
The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
{}-surrounded block.
To leave the block in the middle (e.g., with return), you must insert
a line containing Py_BLOCK_THREADS before the return, e.g.
if (...premature_exit...) {
Py_BLOCK_THREADS
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (...premature_exit...) {
Py_BLOCK_THREADS
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
An alternative is:
Py_BLOCK_THREADS
if (...premature_exit...) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_UNBLOCK_THREADS
Py_BLOCK_THREADS
if (...premature_exit...) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_UNBLOCK_THREADS
For convenience, that the value of 'errno' is restored across
Py_END_ALLOW_THREADS and Py_BLOCK_THREADS.
@ -128,12 +128,12 @@ PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate);
PyAPI_FUNC(void) PyEval_ReInitThreads(void);
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
}
PyThreadState *_save; \
_save = PyEval_SaveThread();
#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
}
#else /* !WITH_THREAD */

View file

@ -11,13 +11,13 @@ extern "C" {
* big-endian, unless otherwise noted:
*
* byte offset
* 0 year 2 bytes, 1-9999
* 2 month 1 byte, 1-12
* 3 day 1 byte, 1-31
* 4 hour 1 byte, 0-23
* 5 minute 1 byte, 0-59
* 6 second 1 byte, 0-59
* 7 usecond 3 bytes, 0-999999
* 0 year 2 bytes, 1-9999
* 2 month 1 byte, 1-12
* 3 day 1 byte, 1-31
* 4 hour 1 byte, 0-23
* 5 minute 1 byte, 0-59
* 6 second 1 byte, 0-59
* 7 usecond 3 bytes, 0-999999
* 10
*/
@ -33,26 +33,26 @@ extern "C" {
typedef struct
{
PyObject_HEAD
long hashcode; /* -1 when unknown */
int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */
int seconds; /* 0 <= seconds < 24*3600 is invariant */
int microseconds; /* 0 <= microseconds < 1000000 is invariant */
PyObject_HEAD
long hashcode; /* -1 when unknown */
int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */
int seconds; /* 0 <= seconds < 24*3600 is invariant */
int microseconds; /* 0 <= microseconds < 1000000 is invariant */
} PyDateTime_Delta;
typedef struct
{
PyObject_HEAD /* a pure abstract base clase */
PyObject_HEAD /* a pure abstract base clase */
} PyDateTime_TZInfo;
/* The datetime and time types have hashcodes, and an optional tzinfo member,
* present if and only if hastzinfo is true.
*/
#define _PyTZINFO_HEAD \
PyObject_HEAD \
long hashcode; \
char hastzinfo; /* boolean flag */
#define _PyTZINFO_HEAD \
PyObject_HEAD \
long hashcode; \
char hastzinfo; /* boolean flag */
/* No _PyDateTime_BaseTZInfo is allocated; it's just to have something
* convenient to cast to, when getting at the hastzinfo member of objects
@ -60,7 +60,7 @@ typedef struct
*/
typedef struct
{
_PyTZINFO_HEAD
_PyTZINFO_HEAD
} _PyDateTime_BaseTZInfo;
/* All time objects are of PyDateTime_TimeType, but that can be allocated
@ -69,20 +69,20 @@ typedef struct
* internal struct used to allocate the right amount of space for the
* "without" case.
*/
#define _PyDateTime_TIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_TIME_DATASIZE];
#define _PyDateTime_TIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_TIME_DATASIZE];
typedef struct
{
_PyDateTime_TIMEHEAD
} _PyDateTime_BaseTime; /* hastzinfo false */
_PyDateTime_TIMEHEAD
} _PyDateTime_BaseTime; /* hastzinfo false */
typedef struct
{
_PyDateTime_TIMEHEAD
PyObject *tzinfo;
} PyDateTime_Time; /* hastzinfo true */
_PyDateTime_TIMEHEAD
PyObject *tzinfo;
} PyDateTime_Time; /* hastzinfo true */
/* All datetime objects are of PyDateTime_DateTimeType, but that can be
@ -92,48 +92,48 @@ typedef struct
*/
typedef struct
{
_PyTZINFO_HEAD
unsigned char data[_PyDateTime_DATE_DATASIZE];
_PyTZINFO_HEAD
unsigned char data[_PyDateTime_DATE_DATASIZE];
} PyDateTime_Date;
#define _PyDateTime_DATETIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_DATETIME_DATASIZE];
#define _PyDateTime_DATETIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_DATETIME_DATASIZE];
typedef struct
{
_PyDateTime_DATETIMEHEAD
} _PyDateTime_BaseDateTime; /* hastzinfo false */
_PyDateTime_DATETIMEHEAD
} _PyDateTime_BaseDateTime; /* hastzinfo false */
typedef struct
{
_PyDateTime_DATETIMEHEAD
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
_PyDateTime_DATETIMEHEAD
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
/* Apply for date and datetime instances. */
#define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \
((PyDateTime_Date*)o)->data[1])
((PyDateTime_Date*)o)->data[1])
#define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2])
#define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3])
#define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4])
#define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5])
#define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6])
#define PyDateTime_DATE_GET_MICROSECOND(o) \
((((PyDateTime_DateTime*)o)->data[7] << 16) | \
(((PyDateTime_DateTime*)o)->data[8] << 8) | \
((PyDateTime_DateTime*)o)->data[9])
#define PyDateTime_DATE_GET_MICROSECOND(o) \
((((PyDateTime_DateTime*)o)->data[7] << 16) | \
(((PyDateTime_DateTime*)o)->data[8] << 8) | \
((PyDateTime_DateTime*)o)->data[9])
/* Apply for time instances. */
#define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0])
#define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1])
#define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2])
#define PyDateTime_TIME_GET_MICROSECOND(o) \
((((PyDateTime_Time*)o)->data[3] << 16) | \
(((PyDateTime_Time*)o)->data[4] << 8) | \
((PyDateTime_Time*)o)->data[5])
#define PyDateTime_TIME_GET_MICROSECOND(o) \
((((PyDateTime_Time*)o)->data[3] << 16) | \
(((PyDateTime_Time*)o)->data[4] << 8) | \
((PyDateTime_Time*)o)->data[5])
/* Define structure for C API. */
@ -148,7 +148,7 @@ typedef struct {
/* constructors */
PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*);
PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int,
PyObject*, PyTypeObject*);
PyObject*, PyTypeObject*);
PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*);
PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*);
@ -188,7 +188,7 @@ typedef struct {
static PyDateTime_CAPI *PyDateTimeAPI = NULL;
#define PyDateTime_IMPORT \
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
/* Macros for type checking when not building the Python core. */
#define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType)
@ -208,30 +208,30 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL;
/* Macros for accessing constructors in a simplified fashion. */
#define PyDate_FromDate(year, month, day) \
PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType)
PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType)
#define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
#define PyTime_FromTime(hour, minute, second, usecond) \
PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
Py_None, PyDateTimeAPI->TimeType)
PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
Py_None, PyDateTimeAPI->TimeType)
#define PyDelta_FromDSU(days, seconds, useconds) \
PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
PyDateTimeAPI->DeltaType)
PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
PyDateTimeAPI->DeltaType)
/* Macros supporting the DB API. */
#define PyDateTime_FromTimestamp(args) \
PyDateTimeAPI->DateTime_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL)
PyDateTimeAPI->DateTime_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL)
#define PyDate_FromTimestamp(args) \
PyDateTimeAPI->Date_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateType), args)
PyDateTimeAPI->Date_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateType), args)
#endif /* Py_BUILD_CORE */
#endif /* Py_BUILD_CORE */
#ifdef __cplusplus
}

View file

@ -9,27 +9,27 @@ typedef PyObject *(*getter)(PyObject *, void *);
typedef int (*setter)(PyObject *, PyObject *, void *);
typedef struct PyGetSetDef {
char *name;
getter get;
setter set;
char *doc;
void *closure;
char *name;
getter get;
setter set;
char *doc;
void *closure;
} PyGetSetDef;
typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
void *wrapped);
void *wrapped);
typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args,
void *wrapped, PyObject *kwds);
void *wrapped, PyObject *kwds);
struct wrapperbase {
char *name;
int offset;
void *function;
wrapperfunc wrapper;
char *doc;
int flags;
PyObject *name_strobj;
char *name;
int offset;
void *function;
wrapperfunc wrapper;
char *doc;
int flags;
PyObject *name_strobj;
};
/* Flags for above struct */
@ -38,33 +38,33 @@ struct wrapperbase {
/* Various kinds of descriptor objects */
#define PyDescr_COMMON \
PyObject_HEAD \
PyTypeObject *d_type; \
PyObject *d_name
PyObject_HEAD \
PyTypeObject *d_type; \
PyObject *d_name
typedef struct {
PyDescr_COMMON;
PyDescr_COMMON;
} PyDescrObject;
typedef struct {
PyDescr_COMMON;
PyMethodDef *d_method;
PyDescr_COMMON;
PyMethodDef *d_method;
} PyMethodDescrObject;
typedef struct {
PyDescr_COMMON;
struct PyMemberDef *d_member;
PyDescr_COMMON;
struct PyMemberDef *d_member;
} PyMemberDescrObject;
typedef struct {
PyDescr_COMMON;
PyGetSetDef *d_getset;
PyDescr_COMMON;
PyGetSetDef *d_getset;
} PyGetSetDescrObject;
typedef struct {
PyDescr_COMMON;
struct wrapperbase *d_base;
void *d_wrapped; /* This can be any function pointer */
PyDescr_COMMON;
struct wrapperbase *d_base;
void *d_wrapped; /* This can be any function pointer */
} PyWrapperDescrObject;
PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type;
@ -75,11 +75,11 @@ PyAPI_DATA(PyTypeObject) PyMemberDescr_Type;
PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *,
struct PyMemberDef *);
struct PyMemberDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *,
struct PyGetSetDef *);
struct PyGetSetDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
struct wrapperbase *, void *);
struct wrapperbase *, void *);
#define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL)
PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);

View file

@ -48,13 +48,13 @@ meaning otherwise.
#define PyDict_MINSIZE 8
typedef struct {
/* Cached hash code of me_key. Note that hash codes are C longs.
* We have to use Py_ssize_t instead because dict_popitem() abuses
* me_hash to hold a search finger.
*/
Py_ssize_t me_hash;
PyObject *me_key;
PyObject *me_value;
/* Cached hash code of me_key. Note that hash codes are C longs.
* We have to use Py_ssize_t instead because dict_popitem() abuses
* me_hash to hold a search finger.
*/
Py_ssize_t me_hash;
PyObject *me_key;
PyObject *me_value;
} PyDictEntry;
/*
@ -68,24 +68,24 @@ it's two-thirds full.
*/
typedef struct _dictobject PyDictObject;
struct _dictobject {
PyObject_HEAD
Py_ssize_t ma_fill; /* # Active + # Dummy */
Py_ssize_t ma_used; /* # Active */
PyObject_HEAD
Py_ssize_t ma_fill; /* # Active + # Dummy */
Py_ssize_t ma_used; /* # Active */
/* The table contains ma_mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t ma_mask;
/* The table contains ma_mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t ma_mask;
/* ma_table points to ma_smalltable for small tables, else to
* additional malloc'ed memory. ma_table is never NULL! This rule
* saves repeated runtime null-tests in the workhorse getitem and
* setitem calls.
*/
PyDictEntry *ma_table;
PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash);
PyDictEntry ma_smalltable[PyDict_MINSIZE];
/* ma_table points to ma_smalltable for small tables, else to
* additional malloc'ed memory. ma_table is never NULL! This rule
* saves repeated runtime null-tests in the workhorse getitem and
* setitem calls.
*/
PyDictEntry *ma_table;
PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash);
PyDictEntry ma_smalltable[PyDict_MINSIZE];
};
PyAPI_DATA(PyTypeObject) PyDict_Type;
@ -104,7 +104,7 @@ PyAPI_DATA(PyTypeObject) PyDictValues_Type;
#define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type)
/* This excludes Values, since they are not sets. */
# define PyDictViewSet_Check(op) \
(PyDictKeys_Check(op) || PyDictItems_Check(op))
(PyDictKeys_Check(op) || PyDictItems_Check(op))
PyAPI_FUNC(PyObject *) PyDict_New(void);
PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key);
@ -112,9 +112,9 @@ PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
PyAPI_FUNC(int) PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
PyAPI_FUNC(int) _PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
@ -134,8 +134,8 @@ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
dict.update(other) is equivalent to PyDict_Merge(dict, other, 1).
*/
PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
PyObject *other,
int override);
PyObject *other,
int override);
/* PyDict_MergeFromSeq2 updates/merges from an iterable object producing
iterable objects of length 2. If override is true, the last occurrence
@ -143,8 +143,8 @@ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1).
*/
PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
PyObject *seq2,
int override);
PyObject *seq2,
int override);
PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);

View file

@ -8,28 +8,28 @@ extern "C" {
#endif
typedef struct {
PyObject_HEAD
FILE *f_fp;
PyObject *f_name;
PyObject *f_mode;
int (*f_close)(FILE *);
int f_softspace; /* Flag used by 'print' command */
int f_binary; /* Flag which indicates whether the file is
open in binary (1) or text (0) mode */
char* f_buf; /* Allocated readahead buffer */
char* f_bufend; /* Points after last occupied position */
char* f_bufptr; /* Current buffer position */
char *f_setbuf; /* Buffer for setbuf(3) and setvbuf(3) */
int f_univ_newline; /* Handle any newline convention */
int f_newlinetypes; /* Types of newlines seen */
int f_skipnextlf; /* Skip next \n */
PyObject *f_encoding;
PyObject *f_errors;
PyObject *weakreflist; /* List of weak references */
int unlocked_count; /* Num. currently running sections of code
using f_fp with the GIL released. */
int readable;
int writable;
PyObject_HEAD
FILE *f_fp;
PyObject *f_name;
PyObject *f_mode;
int (*f_close)(FILE *);
int f_softspace; /* Flag used by 'print' command */
int f_binary; /* Flag which indicates whether the file is
open in binary (1) or text (0) mode */
char* f_buf; /* Allocated readahead buffer */
char* f_bufend; /* Points after last occupied position */
char* f_bufptr; /* Current buffer position */
char *f_setbuf; /* Buffer for setbuf(3) and setvbuf(3) */
int f_univ_newline; /* Handle any newline convention */
int f_newlinetypes; /* Types of newlines seen */
int f_skipnextlf; /* Skip next \n */
PyObject *f_encoding;
PyObject *f_errors;
PyObject *weakreflist; /* List of weak references */
int unlocked_count; /* Num. currently running sections of code
using f_fp with the GIL released. */
int readable;
int writable;
} PyFileObject;
PyAPI_DATA(PyTypeObject) PyFile_Type;

View file

@ -63,9 +63,9 @@ whose size is determined when the object is allocated.
#ifdef Py_TRACE_REFS
/* Define pointers to support a doubly-linked list of all live heap objects. */
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_EXTRA_INIT 0, 0,
@ -75,17 +75,17 @@ whose size is determined when the object is allocated.
#endif
/* PyObject_HEAD defines the initial segment of every PyObject. */
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
Py_ssize_t ob_refcnt; \
struct _typeobject *ob_type;
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
Py_ssize_t ob_refcnt; \
struct _typeobject *ob_type;
#define PyObject_HEAD_INIT(type) \
_PyObject_EXTRA_INIT \
1, type,
#define PyObject_HEAD_INIT(type) \
_PyObject_EXTRA_INIT \
1, type,
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
/* PyObject_VAR_HEAD defines the initial segment of all variable-size
* container objects. These end with a declaration of an array with 1
@ -93,9 +93,9 @@ whose size is determined when the object is allocated.
* has room for ob_size elements. Note that ob_size is an element count,
* not necessarily a byte count.
*/
#define PyObject_VAR_HEAD \
PyObject_HEAD \
Py_ssize_t ob_size; /* Number of items in variable part */
#define PyObject_VAR_HEAD \
PyObject_HEAD \
Py_ssize_t ob_size; /* Number of items in variable part */
#define Py_INVALID_SIZE (Py_ssize_t)-1
/* Nothing is actually declared to be a PyObject, but every pointer to
@ -104,16 +104,16 @@ whose size is determined when the object is allocated.
* in addition, be cast to PyVarObject*.
*/
typedef struct _object {
PyObject_HEAD
PyObject_HEAD
} PyObject;
typedef struct {
PyObject_VAR_HEAD
PyObject_VAR_HEAD
} PyVarObject;
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
/*
Type objects contain a string containing the type name (to help somewhat
@ -162,26 +162,26 @@ typedef Py_ssize_t (*charbufferproc)(PyObject *, Py_ssize_t, char **);
/* Py3k buffer interface */
typedef struct bufferinfo {
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
Py_ssize_t smalltable[2]; /* static store for shape and strides of
mono-dimensional buffers. */
void *internal;
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
Py_ssize_t smalltable[2]; /* static store for shape and strides of
mono-dimensional buffers. */
void *internal;
} Py_buffer;
typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
/* Flags for getting buffers */
/* Flags for getting buffers */
#define PyBUF_SIMPLE 0
#define PyBUF_WRITABLE 0x0001
/* we used to include an E, backwards compatible alias */
@ -217,88 +217,88 @@ typedef int (*visitproc)(PyObject *, void *);
typedef int (*traverseproc)(PyObject *, visitproc, void *);
typedef struct {
/* For numbers without flag bit Py_TPFLAGS_CHECKTYPES set, all
arguments are guaranteed to be of the object's type (modulo
coercion hacks -- i.e. if the type's coercion function
returns other types, then these are allowed as well). Numbers that
have the Py_TPFLAGS_CHECKTYPES flag bit set should check *both*
arguments for proper type and implement the necessary conversions
in the slot functions themselves. */
/* For numbers without flag bit Py_TPFLAGS_CHECKTYPES set, all
arguments are guaranteed to be of the object's type (modulo
coercion hacks -- i.e. if the type's coercion function
returns other types, then these are allowed as well). Numbers that
have the Py_TPFLAGS_CHECKTYPES flag bit set should check *both*
arguments for proper type and implement the necessary conversions
in the slot functions themselves. */
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_divide;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_nonzero;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
coercion nb_coerce;
unaryfunc nb_int;
unaryfunc nb_long;
unaryfunc nb_float;
unaryfunc nb_oct;
unaryfunc nb_hex;
/* Added in release 2.0 */
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_divide;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_divide;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_nonzero;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
coercion nb_coerce;
unaryfunc nb_int;
unaryfunc nb_long;
unaryfunc nb_float;
unaryfunc nb_oct;
unaryfunc nb_hex;
/* Added in release 2.0 */
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_divide;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
/* Added in release 2.2 */
/* The following require the Py_TPFLAGS_HAVE_CLASS flag */
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
/* Added in release 2.2 */
/* The following require the Py_TPFLAGS_HAVE_CLASS flag */
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
/* Added in release 2.5 */
unaryfunc nb_index;
/* Added in release 2.5 */
unaryfunc nb_index;
} PyNumberMethods;
typedef struct {
lenfunc sq_length;
binaryfunc sq_concat;
ssizeargfunc sq_repeat;
ssizeargfunc sq_item;
ssizessizeargfunc sq_slice;
ssizeobjargproc sq_ass_item;
ssizessizeobjargproc sq_ass_slice;
objobjproc sq_contains;
/* Added in release 2.0 */
binaryfunc sq_inplace_concat;
ssizeargfunc sq_inplace_repeat;
lenfunc sq_length;
binaryfunc sq_concat;
ssizeargfunc sq_repeat;
ssizeargfunc sq_item;
ssizessizeargfunc sq_slice;
ssizeobjargproc sq_ass_item;
ssizessizeobjargproc sq_ass_slice;
objobjproc sq_contains;
/* Added in release 2.0 */
binaryfunc sq_inplace_concat;
ssizeargfunc sq_inplace_repeat;
} PySequenceMethods;
typedef struct {
lenfunc mp_length;
binaryfunc mp_subscript;
objobjargproc mp_ass_subscript;
lenfunc mp_length;
binaryfunc mp_subscript;
objobjargproc mp_ass_subscript;
} PyMappingMethods;
typedef struct {
readbufferproc bf_getreadbuffer;
writebufferproc bf_getwritebuffer;
segcountproc bf_getsegcount;
charbufferproc bf_getcharbuffer;
getbufferproc bf_getbuffer;
releasebufferproc bf_releasebuffer;
readbufferproc bf_getreadbuffer;
writebufferproc bf_getwritebuffer;
segcountproc bf_getsegcount;
charbufferproc bf_getcharbuffer;
getbufferproc bf_getbuffer;
releasebufferproc bf_releasebuffer;
} PyBufferProcs;
@ -322,110 +322,110 @@ typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
typedef struct _typeobject {
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
/* Methods to implement standard operations */
/* Methods to implement standard operations */
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
cmpfunc tp_compare;
reprfunc tp_repr;
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
cmpfunc tp_compare;
reprfunc tp_repr;
/* Method suites for standard classes */
/* Method suites for standard classes */
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
/* More standard operations (here for binary compatibility) */
/* More standard operations (here for binary compatibility) */
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;
/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;
/* Flags to define presence of optional/expanded features */
long tp_flags;
/* Flags to define presence of optional/expanded features */
long tp_flags;
const char *tp_doc; /* Documentation string */
const char *tp_doc; /* Documentation string */
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
traverseproc tp_traverse;
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
traverseproc tp_traverse;
/* delete references to contained objects */
inquiry tp_clear;
/* delete references to contained objects */
inquiry tp_clear;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
richcmpfunc tp_richcompare;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
richcmpfunc tp_richcompare;
/* weak reference enabler */
Py_ssize_t tp_weaklistoffset;
/* weak reference enabler */
Py_ssize_t tp_weaklistoffset;
/* Added in release 2.2 */
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
/* Added in release 2.2 */
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
/* Type attribute cache version tag. Added in version 2.6 */
unsigned int tp_version_tag;
/* Type attribute cache version tag. Added in version 2.6 */
unsigned int tp_version_tag;
#ifdef COUNT_ALLOCS
/* these must be last and never explicitly initialized */
Py_ssize_t tp_allocs;
Py_ssize_t tp_frees;
Py_ssize_t tp_maxalloc;
struct _typeobject *tp_prev;
struct _typeobject *tp_next;
/* these must be last and never explicitly initialized */
Py_ssize_t tp_allocs;
Py_ssize_t tp_frees;
Py_ssize_t tp_maxalloc;
struct _typeobject *tp_prev;
struct _typeobject *tp_next;
#endif
} PyTypeObject;
/* The *real* layout of a type object when allocated on the heap */
typedef struct _heaptypeobject {
/* Note: there's a dependency on the order of these members
in slotptr() in typeobject.c . */
PyTypeObject ht_type;
PyNumberMethods as_number;
PyMappingMethods as_mapping;
PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
so that the mapping wins when both
the mapping and the sequence define
a given operator (e.g. __getitem__).
see add_operators() in typeobject.c . */
PyBufferProcs as_buffer;
PyObject *ht_name, *ht_slots;
/* here are optional user slots, followed by the members. */
/* Note: there's a dependency on the order of these members
in slotptr() in typeobject.c . */
PyTypeObject ht_type;
PyNumberMethods as_number;
PyMappingMethods as_mapping;
PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
so that the mapping wins when both
the mapping and the sequence define
a given operator (e.g. __getitem__).
see add_operators() in typeobject.c . */
PyBufferProcs as_buffer;
PyObject *ht_name, *ht_slots;
/* here are optional user slots, followed by the members. */
} PyHeapTypeObject;
/* access macro to the members which are floating "behind" the object */
@ -436,20 +436,20 @@ typedef struct _heaptypeobject {
/* Generic type check */
PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
#define PyObject_TypeCheck(ob, tp) \
(Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
(Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
#define PyType_Check(op) \
PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **);
PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
@ -479,7 +479,7 @@ PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(long) PyObject_Hash(PyObject *);
PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *);
PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
@ -514,7 +514,7 @@ PyAPI_FUNC(long) _Py_HashPointer(void*);
#define PyObject_REPR(obj) PyString_AS_STRING(PyObject_Repr(obj))
/* Flag bits for printing: */
#define Py_PRINT_RAW 1 /* No string quotes etc. */
#define Py_PRINT_RAW 1 /* No string quotes etc. */
/*
`Type flags (tp_flags)
@ -607,29 +607,29 @@ manually remove this flag though!
#define Py_TPFLAGS_HAVE_NEWBUFFER (1L<<21)
/* These flags are used to determine if a type is a subclass. */
#define Py_TPFLAGS_INT_SUBCLASS (1L<<23)
#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24)
#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25)
#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26)
#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27)
#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28)
#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29)
#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30)
#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31)
#define Py_TPFLAGS_INT_SUBCLASS (1L<<23)
#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24)
#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25)
#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26)
#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27)
#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28)
#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29)
#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30)
#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31)
#define Py_TPFLAGS_DEFAULT_EXTERNAL ( \
Py_TPFLAGS_HAVE_GETCHARBUFFER | \
Py_TPFLAGS_HAVE_SEQUENCE_IN | \
Py_TPFLAGS_HAVE_INPLACEOPS | \
Py_TPFLAGS_HAVE_RICHCOMPARE | \
Py_TPFLAGS_HAVE_WEAKREFS | \
Py_TPFLAGS_HAVE_ITER | \
Py_TPFLAGS_HAVE_CLASS | \
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
Py_TPFLAGS_HAVE_INDEX | \
0)
Py_TPFLAGS_HAVE_GETCHARBUFFER | \
Py_TPFLAGS_HAVE_SEQUENCE_IN | \
Py_TPFLAGS_HAVE_INPLACEOPS | \
Py_TPFLAGS_HAVE_RICHCOMPARE | \
Py_TPFLAGS_HAVE_WEAKREFS | \
Py_TPFLAGS_HAVE_ITER | \
Py_TPFLAGS_HAVE_CLASS | \
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
Py_TPFLAGS_HAVE_INDEX | \
0)
#define Py_TPFLAGS_DEFAULT_CORE (Py_TPFLAGS_DEFAULT_EXTERNAL | \
Py_TPFLAGS_HAVE_VERSION_TAG)
Py_TPFLAGS_HAVE_VERSION_TAG)
#ifdef Py_BUILD_CORE
#define Py_TPFLAGS_DEFAULT Py_TPFLAGS_DEFAULT_CORE
@ -687,32 +687,32 @@ environment the global variable trick is not safe.)
#ifdef Py_REF_DEBUG
PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,
int lineno, PyObject *op);
int lineno, PyObject *op);
PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);
PyAPI_FUNC(PyObject *) _PySet_Dummy(void);
PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
#define _Py_INC_REFTOTAL _Py_RefTotal++
#define _Py_DEC_REFTOTAL _Py_RefTotal--
#define _Py_REF_DEBUG_COMMA ,
#define _Py_CHECK_REFCNT(OP) \
{ if (((PyObject*)OP)->ob_refcnt < 0) \
_Py_NegativeRefcount(__FILE__, __LINE__, \
(PyObject *)(OP)); \
#define _Py_INC_REFTOTAL _Py_RefTotal++
#define _Py_DEC_REFTOTAL _Py_RefTotal--
#define _Py_REF_DEBUG_COMMA ,
#define _Py_CHECK_REFCNT(OP) \
{ if (((PyObject*)OP)->ob_refcnt < 0) \
_Py_NegativeRefcount(__FILE__, __LINE__, \
(PyObject *)(OP)); \
}
#else
#define _Py_INC_REFTOTAL
#define _Py_DEC_REFTOTAL
#define _Py_REF_DEBUG_COMMA
#define _Py_CHECK_REFCNT(OP) /* a semicolon */;
#define _Py_CHECK_REFCNT(OP) /* a semicolon */;
#endif /* Py_REF_DEBUG */
#ifdef COUNT_ALLOCS
PyAPI_FUNC(void) inc_count(PyTypeObject *);
PyAPI_FUNC(void) dec_count(PyTypeObject *);
#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP))
#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP))
#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
#define _Py_COUNT_ALLOCS_COMMA ,
#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP))
#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP))
#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
#define _Py_COUNT_ALLOCS_COMMA ,
#else
#define _Py_INC_TPALLOCS(OP)
#define _Py_INC_TPFREES(OP)
@ -733,30 +733,30 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
/* Without Py_TRACE_REFS, there's little enough to do that we expand code
* inline.
*/
#define _Py_NewReference(op) ( \
_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
Py_REFCNT(op) = 1)
#define _Py_NewReference(op) ( \
_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
Py_REFCNT(op) = 1)
#define _Py_ForgetReference(op) _Py_INC_TPFREES(op)
#define _Py_Dealloc(op) ( \
_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
(*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
#define _Py_Dealloc(op) ( \
_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
(*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
#endif /* !Py_TRACE_REFS */
#define Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject*)(op))->ob_refcnt++)
#define Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject*)(op))->ob_refcnt++)
#define Py_DECREF(op) \
do { \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--((PyObject*)(op))->ob_refcnt != 0) \
_Py_CHECK_REFCNT(op) \
else \
_Py_Dealloc((PyObject *)(op)); \
} while (0)
#define Py_DECREF(op) \
do { \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--((PyObject*)(op))->ob_refcnt != 0) \
_Py_CHECK_REFCNT(op) \
else \
_Py_Dealloc((PyObject *)(op)); \
} while (0)
/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
* and tp_dealloc implementatons.
@ -792,14 +792,14 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
* Python integers aren't currently weakly referencable. Best practice is
* to use Py_CLEAR() even if you can't think of a reason for why you need to.
*/
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(_py_tmp); \
} \
} while (0)
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(_py_tmp); \
} \
} while (0)
/* Macros to use in case the object pointer may be NULL: */
#define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0)
@ -926,13 +926,13 @@ bracketing the body of its tp_dealloc function with a pair of macros:
static void
mytype_dealloc(mytype *p)
{
... declarations go here ...
... declarations go here ...
PyObject_GC_UnTrack(p); // must untrack first
Py_TRASHCAN_SAFE_BEGIN(p)
... The body of the deallocator goes here, including all calls ...
... to Py_DECREF on contained objects. ...
Py_TRASHCAN_SAFE_END(p)
PyObject_GC_UnTrack(p); // must untrack first
Py_TRASHCAN_SAFE_BEGIN(p)
... The body of the deallocator goes here, including all calls ...
... to Py_DECREF on contained objects. ...
Py_TRASHCAN_SAFE_END(p)
}
CAUTION: Never return from the middle of the body! If the body needs to
@ -962,16 +962,16 @@ PyAPI_DATA(PyObject *) _PyTrash_delete_later;
#define PyTrash_UNWIND_LEVEL 50
#define Py_TRASHCAN_SAFE_BEGIN(op) \
if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
++_PyTrash_delete_nesting;
/* The body of the deallocator is here. */
if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
++_PyTrash_delete_nesting;
/* The body of the deallocator is here. */
#define Py_TRASHCAN_SAFE_END(op) \
--_PyTrash_delete_nesting; \
if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
_PyTrash_destroy_chain(); \
} \
else \
_PyTrash_deposit_object((PyObject*)op);
--_PyTrash_delete_nesting; \
if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
_PyTrash_destroy_chain(); \
} \
else \
_PyTrash_deposit_object((PyObject*)op);
#ifdef __cplusplus
}

View file

@ -101,7 +101,7 @@ PyAPI_FUNC(void) PyObject_Free(void *);
/* Macros */
#ifdef WITH_PYMALLOC
#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
@ -115,31 +115,31 @@ PyAPI_FUNC(void) _PyObject_DebugCheckAddressApi(char api, const void *p);
PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyMem_DebugFree(void *p);
#define PyObject_MALLOC _PyObject_DebugMalloc
#define PyObject_Malloc _PyObject_DebugMalloc
#define PyObject_REALLOC _PyObject_DebugRealloc
#define PyObject_Realloc _PyObject_DebugRealloc
#define PyObject_FREE _PyObject_DebugFree
#define PyObject_Free _PyObject_DebugFree
#define PyObject_MALLOC _PyObject_DebugMalloc
#define PyObject_Malloc _PyObject_DebugMalloc
#define PyObject_REALLOC _PyObject_DebugRealloc
#define PyObject_Realloc _PyObject_DebugRealloc
#define PyObject_FREE _PyObject_DebugFree
#define PyObject_Free _PyObject_DebugFree
#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC PyObject_Malloc
#define PyObject_REALLOC PyObject_Realloc
#define PyObject_FREE PyObject_Free
#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC PyObject_Malloc
#define PyObject_REALLOC PyObject_Realloc
#define PyObject_FREE PyObject_Free
#endif
#else /* ! WITH_PYMALLOC */
#define PyObject_MALLOC PyMem_MALLOC
#define PyObject_REALLOC PyMem_REALLOC
#define PyObject_FREE PyMem_FREE
#else /* ! WITH_PYMALLOC */
#define PyObject_MALLOC PyMem_MALLOC
#define PyObject_REALLOC PyMem_REALLOC
#define PyObject_FREE PyMem_FREE
#endif /* WITH_PYMALLOC */
#endif /* WITH_PYMALLOC */
#define PyObject_Del PyObject_Free
#define PyObject_DEL PyObject_FREE
#define PyObject_Del PyObject_Free
#define PyObject_DEL PyObject_FREE
/* for source compatibility with 2.2 */
#define _PyObject_Del PyObject_Free
#define _PyObject_Del PyObject_Free
/*
* Generic object allocator interface
@ -154,16 +154,16 @@ PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
#define PyObject_New(type, typeobj) \
( (type *) _PyObject_New(typeobj) )
( (type *) _PyObject_New(typeobj) )
#define PyObject_NewVar(type, typeobj, n) \
( (type *) _PyObject_NewVar((typeobj), (n)) )
( (type *) _PyObject_NewVar((typeobj), (n)) )
/* Macros trading binary compatibility for speed. See also pymem.h.
Note that these macros expect non-NULL object pointers.*/
#define PyObject_INIT(op, typeobj) \
( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
#define PyObject_INIT_VAR(op, typeobj, size) \
( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
@ -181,17 +181,17 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
#endif
#define _PyObject_VAR_SIZE(typeobj, nitems) \
(size_t) \
( ( (typeobj)->tp_basicsize + \
(nitems)*(typeobj)->tp_itemsize + \
(SIZEOF_VOID_P - 1) \
) & ~(SIZEOF_VOID_P - 1) \
)
#define _PyObject_VAR_SIZE(typeobj, nitems) \
(size_t) \
( ( (typeobj)->tp_basicsize + \
(nitems)*(typeobj)->tp_itemsize + \
(SIZEOF_VOID_P - 1) \
) & ~(SIZEOF_VOID_P - 1) \
)
#define PyObject_NEW(type, typeobj) \
( (type *) PyObject_Init( \
(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
#define PyObject_NEW_VAR(type, typeobj, n) \
( (type *) PyObject_InitVar( \
@ -203,7 +203,7 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
distinction between two steps (at least):
1) the actual allocation of the object storage;
2) the initialization of the Python specific fields
in this storage with PyObject_{Init, InitVar}.
in this storage with PyObject_{Init, InitVar}.
PyObject *
YourObject_New(...)
@ -212,7 +212,7 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
if (op == NULL)
return PyErr_NoMemory();
return PyErr_NoMemory();
PyObject_Init(op, &YourTypeStruct);
@ -239,44 +239,44 @@ PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
/* Test if an object has a GC head */
#define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \
(Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
(Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
#define PyObject_GC_Resize(type, op, n) \
( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
/* for source compatibility with 2.2 */
#define _PyObject_GC_Del PyObject_GC_Del
/* GC information is stored BEFORE the object structure. */
typedef union _gc_head {
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
long double dummy; /* force worst-case alignment */
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
long double dummy; /* force worst-case alignment */
} PyGC_Head;
extern PyGC_Head *_PyGC_generation0;
#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
#define _PyGC_REFS_UNTRACKED (-2)
#define _PyGC_REFS_REACHABLE (-3)
#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
#define _PyGC_REFS_UNTRACKED (-2)
#define _PyGC_REFS_REACHABLE (-3)
#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
/* Tell the GC to track this object. NB: While the object is tracked the
* collector it must be safe to call the ob_traverse method. */
#define _PyObject_GC_TRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
Py_FatalError("GC object already tracked"); \
g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
g->gc.gc_next = _PyGC_generation0; \
g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
g->gc.gc_prev->gc.gc_next = g; \
_PyGC_generation0->gc.gc_prev = g; \
PyGC_Head *g = _Py_AS_GC(o); \
if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
Py_FatalError("GC object already tracked"); \
g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
g->gc.gc_next = _PyGC_generation0; \
g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
g->gc.gc_prev->gc.gc_next = g; \
_PyGC_generation0->gc.gc_prev = g; \
} while (0);
/* Tell the GC to stop tracking this object.
@ -284,23 +284,23 @@ extern PyGC_Head *_PyGC_generation0;
* way to provoke memory errors if calling code is confused.
*/
#define _PyObject_GC_UNTRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
g->gc.gc_next = NULL; \
PyGC_Head *g = _Py_AS_GC(o); \
assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
g->gc.gc_next = NULL; \
} while (0);
/* True if the object is currently tracked by the GC. */
#define _PyObject_GC_IS_TRACKED(o) \
((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
/* True if the object may be tracked by the GC in the future, or already is.
This can be useful to implement some optimizations. */
#define _PyObject_GC_MAY_BE_TRACKED(obj) \
(PyObject_IS_GC(obj) && \
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
(PyObject_IS_GC(obj) && \
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t);
@ -311,9 +311,9 @@ PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
PyAPI_FUNC(void) PyObject_GC_Del(void *);
#define PyObject_GC_New(type, typeobj) \
( (type *) _PyObject_GC_New(typeobj) )
( (type *) _PyObject_GC_New(typeobj) )
#define PyObject_GC_NewVar(type, typeobj, n) \
( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
/* Utility macro to help write tp_traverse functions.
@ -321,14 +321,14 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *);
* "visit" and "arg". This is intended to keep tp_traverse functions
* looking as much alike as possible.
*/
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((PyObject *)(op), arg); \
if (vret) \
return vret; \
} \
} while (0)
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((PyObject *)(op), arg); \
if (vret) \
return vret; \
} \
} while (0)
/* This is here for the sake of backwards compatibility. Extensions that
* use the old GC API will still compile but the objects will not be
@ -342,11 +342,11 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *);
/* Test if a type supports weak references */
#define PyType_SUPPORTS_WEAKREFS(t) \
(PyType_HasFeature((t), Py_TPFLAGS_HAVE_WEAKREFS) \
&& ((t)->tp_weaklistoffset > 0))
(PyType_HasFeature((t), Py_TPFLAGS_HAVE_WEAKREFS) \
&& ((t)->tp_weaklistoffset > 0))
#define PyObject_GET_WEAKREFS_LISTPTR(o) \
((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
#ifdef __cplusplus
}

View file

@ -94,23 +94,23 @@ PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**);
/* */
#define PyExceptionClass_Check(x) \
(PyClass_Check((x)) || (PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)))
#define PyExceptionClass_Check(x) \
(PyClass_Check((x)) || (PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)))
#define PyExceptionInstance_Check(x) \
(PyInstance_Check((x)) || \
PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define PyExceptionInstance_Check(x) \
(PyInstance_Check((x)) || \
PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define PyExceptionClass_Name(x) \
(PyClass_Check((x)) \
? PyString_AS_STRING(((PyClassObject*)(x))->cl_name) \
: (char *)(((PyTypeObject*)(x))->tp_name))
#define PyExceptionClass_Name(x) \
(PyClass_Check((x)) \
? PyString_AS_STRING(((PyClassObject*)(x))->cl_name) \
: (char *)(((PyTypeObject*)(x))->tp_name))
#define PyExceptionInstance_Class(x) \
((PyInstance_Check((x)) \
? (PyObject*)((PyInstanceObject*)(x))->in_class \
: (PyObject*)((x)->ob_type)))
#define PyExceptionInstance_Class(x) \
((PyInstance_Check((x)) \
? (PyObject*)((PyInstanceObject*)(x))->in_class \
: (PyObject*)((x)->ob_type)))
/* Predefined exceptions */
@ -184,31 +184,31 @@ PyAPI_FUNC(int) PyErr_BadArgument(void);
PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
PyObject *, const char *);
PyObject *, const char *);
#ifdef MS_WINDOWS
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename(
PyObject *, const Py_UNICODE *);
PyObject *, const Py_UNICODE *);
#endif /* MS_WINDOWS */
PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...)
Py_GCC_ATTRIBUTE((format(printf, 2, 3)));
Py_GCC_ATTRIBUTE((format(printf, 2, 3)));
#ifdef MS_WINDOWS
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject(
int, const char *);
int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
int, const char *);
int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
int, const Py_UNICODE *);
int, const Py_UNICODE *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
PyObject *,int, PyObject *);
PyObject *,int, PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
PyObject *,int, const char *);
PyObject *,int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
PyObject *,int, const Py_UNICODE *);
PyObject *,int, const Py_UNICODE *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
#endif /* MS_WINDOWS */
@ -221,9 +221,9 @@ PyAPI_FUNC(void) _PyErr_BadInternalCall(char *filename, int lineno);
/* Function to create a new exception */
PyAPI_FUNC(PyObject *) PyErr_NewException(
char *name, PyObject *base, PyObject *dict);
char *name, PyObject *base, PyObject *dict);
PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc(
char *name, char *doc, PyObject *base, PyObject *dict);
char *name, char *doc, PyObject *base, PyObject *dict);
PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *);
/* In sigcheck.c or signalmodule.c */
@ -243,15 +243,15 @@ PyAPI_FUNC(PyObject *) PyErr_ProgramText(const char *, int);
/* create a UnicodeDecodeError object */
PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* create a UnicodeEncodeError object */
PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create(
const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* create a UnicodeTranslateError object */
PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create(
const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* get the encoding attribute */
PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
@ -294,11 +294,11 @@ PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *);
/* assign a new value to the reason attribute
return 0 on success, -1 on failure */
PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
#endif
@ -318,9 +318,9 @@ PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
#include <stdarg.h>
PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...)
Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
#ifdef __cplusplus
}

View file

@ -4,7 +4,7 @@
* This file moves some of the autoconf magic to compile-time
* when building on MacOSX. This is needed for building 4-way
* universal binaries and for 64-bit universal binaries because
* the values redefined below aren't configure-time constant but
* the values redefined below aren't configure-time constant but
* only compile-time constant in these scenarios.
*/
@ -36,40 +36,40 @@
# undef SIZEOF_LONG
# ifdef __LP64__
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# define SIZEOF_LONG 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF_SIZE_T 8
# define SIZEOF_TIME_T 8
# define SIZEOF_VOID_P 8
# define SIZEOF_UINTPTR_T 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# define SIZEOF_LONG 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF_SIZE_T 8
# define SIZEOF_TIME_T 8
# define SIZEOF_VOID_P 8
# define SIZEOF_UINTPTR_T 8
# define SIZEOF_PTHREAD_T 8
# else
# ifdef __ppc__
# define SIZEOF__BOOL 4
# define SIZEOF__BOOL 4
# else
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# endif
# define SIZEOF_LONG 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_SIZE_T 4
# define SIZEOF_TIME_T 4
# define SIZEOF_VOID_P 4
# define SIZEOF_UINTPTR_T 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_LONG 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_SIZE_T 4
# define SIZEOF_TIME_T 4
# define SIZEOF_VOID_P 4
# define SIZEOF_UINTPTR_T 4
# define SIZEOF_PTHREAD_T 4
# endif
# if defined(__LP64__)
/* MacOSX 10.4 (the first release to suppport 64-bit code
* at all) only supports 64-bit in the UNIX layer.
* Therefore surpress the toolbox-glue in 64-bit mode.
*/
/* MacOSX 10.4 (the first release to suppport 64-bit code
* at all) only supports 64-bit in the UNIX layer.
* Therefore surpress the toolbox-glue in 64-bit mode.
*/
/* In 64-bit mode setpgrp always has no argments, in 32-bit
* mode that depends on the compilation environment
*/
# undef SETPGRP_HAVE_ARG
/* In 64-bit mode setpgrp always has no argments, in 32-bit
* mode that depends on the compilation environment
*/
# undef SETPGRP_HAVE_ARG
# endif
@ -84,17 +84,17 @@
# define HAVE_GCC_ASM_FOR_X87
#endif
/*
* The definition in pyconfig.h is only valid on the OS release
* where configure ran on and not necessarily for all systems where
* the executable can be used on.
*
* Specifically: OSX 10.4 has limited supported for '%zd', while
* 10.5 has full support for '%zd'. A binary built on 10.5 won't
* work properly on 10.4 unless we surpress the definition
* of PY_FORMAT_SIZE_T
*/
#undef PY_FORMAT_SIZE_T
/*
* The definition in pyconfig.h is only valid on the OS release
* where configure ran on and not necessarily for all systems where
* the executable can be used on.
*
* Specifically: OSX 10.4 has limited supported for '%zd', while
* 10.5 has full support for '%zd'. A binary built on 10.5 won't
* work properly on 10.4 unless we surpress the definition
* of PY_FORMAT_SIZE_T
*/
#undef PY_FORMAT_SIZE_T
#endif /* defined(_APPLE__) */

View file

@ -143,20 +143,20 @@ Used in: PY_LONG_LONG
* integral type.
*/
#ifdef HAVE_UINTPTR_T
typedef uintptr_t Py_uintptr_t;
typedef intptr_t Py_intptr_t;
typedef uintptr_t Py_uintptr_t;
typedef intptr_t Py_intptr_t;
#elif SIZEOF_VOID_P <= SIZEOF_INT
typedef unsigned int Py_uintptr_t;
typedef int Py_intptr_t;
typedef unsigned int Py_uintptr_t;
typedef int Py_intptr_t;
#elif SIZEOF_VOID_P <= SIZEOF_LONG
typedef unsigned long Py_uintptr_t;
typedef long Py_intptr_t;
typedef unsigned long Py_uintptr_t;
typedef long Py_intptr_t;
#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)
typedef unsigned PY_LONG_LONG Py_uintptr_t;
typedef PY_LONG_LONG Py_intptr_t;
typedef unsigned PY_LONG_LONG Py_uintptr_t;
typedef PY_LONG_LONG Py_intptr_t;
#else
# error "Python needs a typedef for Py_uintptr_t in pyport.h."
@ -167,9 +167,9 @@ typedef PY_LONG_LONG Py_intptr_t;
* unsigned integral type). See PEP 353 for details.
*/
#ifdef HAVE_SSIZE_T
typedef ssize_t Py_ssize_t;
typedef ssize_t Py_ssize_t;
#elif SIZEOF_VOID_P == SIZEOF_SIZE_T
typedef Py_intptr_t Py_ssize_t;
typedef Py_intptr_t Py_ssize_t;
#else
# error "Python needs a typedef for Py_ssize_t in pyport.h."
#endif
@ -177,7 +177,7 @@ typedef Py_intptr_t Py_ssize_t;
/* Largest possible value of size_t.
SIZE_MAX is part of C99, so it might be defined on some
platforms. If it is not defined, (size_t)-1 is a portable
definition for C89, due to the way signed->unsigned
definition for C89, due to the way signed->unsigned
conversion is defined. */
#ifdef SIZE_MAX
#define PY_SIZE_MAX SIZE_MAX
@ -269,7 +269,7 @@ typedef Py_intptr_t Py_ssize_t;
/* enable more aggressive optimization for visual studio */
#pragma optimize("agtw", on)
#endif
/* ignore warnings if the compiler decides not to inline a function */
/* ignore warnings if the compiler decides not to inline a function */
#pragma warning(disable: 4710)
/* fastest possible local call under MSVC */
#define Py_LOCAL(type) static type __fastcall
@ -289,16 +289,16 @@ typedef Py_intptr_t Py_ssize_t;
*/
#if defined(_MSC_VER)
#define Py_MEMCPY(target, source, length) do { \
size_t i_, n_ = (length); \
char *t_ = (void*) (target); \
const char *s_ = (void*) (source); \
if (n_ >= 16) \
memcpy(t_, s_, n_); \
else \
for (i_ = 0; i_ < n_; i_++) \
t_[i_] = s_[i_]; \
} while (0)
#define Py_MEMCPY(target, source, length) do { \
size_t i_, n_ = (length); \
char *t_ = (void*) (target); \
const char *s_ = (void*) (source); \
if (n_ >= 16) \
memcpy(t_, s_, n_); \
else \
for (i_ = 0; i_ < n_; i_++) \
t_[i_] = s_[i_]; \
} while (0)
#else
#define Py_MEMCPY memcpy
#endif
@ -420,7 +420,7 @@ extern "C" {
*/
#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS
#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \
((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
#else
#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))
#endif
@ -440,7 +440,7 @@ extern "C" {
*/
#ifdef Py_DEBUG
#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \
(assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
(assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
#else
#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)
#endif
@ -460,13 +460,13 @@ extern "C" {
#define _Py_SET_EDOM_FOR_NAN(X) ;
#endif
#define Py_SET_ERRNO_ON_MATH_ERROR(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
else _Py_SET_EDOM_FOR_NAN(X) \
} \
} while(0)
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
else _Py_SET_EDOM_FOR_NAN(X) \
} \
} while(0)
/* Py_SET_ERANGE_ON_OVERFLOW(x)
* An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility.
@ -487,26 +487,26 @@ extern "C" {
* This isn't reliable. See Py_OVERFLOWED comments.
* X and Y may be evaluated more than once.
*/
#define Py_ADJUST_ERANGE1(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
} \
else if (errno == ERANGE && (X) == 0.0) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE1(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
} \
else if (errno == ERANGE && (X) == 0.0) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE2(X, Y) \
do { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
(Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
if (errno == 0) \
errno = ERANGE; \
} \
else if (errno == ERANGE) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE2(X, Y) \
do { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
(Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
if (errno == 0) \
errno = ERANGE; \
} \
else if (errno == ERANGE) \
errno = 0; \
} while(0)
/* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are
* required to support the short float repr introduced in Python 3.1) require
@ -535,18 +535,18 @@ extern "C" {
#ifdef HAVE_GCC_ASM_FOR_X87
#define HAVE_PY_SET_53BIT_PRECISION 1
/* _Py_get/set_387controlword functions are defined in Python/pymath.c */
#define _Py_SET_53BIT_PRECISION_HEADER \
unsigned short old_387controlword, new_387controlword
#define _Py_SET_53BIT_PRECISION_START \
do { \
old_387controlword = _Py_get_387controlword(); \
new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(new_387controlword); \
} while (0)
#define _Py_SET_53BIT_PRECISION_END \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(old_387controlword)
#define _Py_SET_53BIT_PRECISION_HEADER \
unsigned short old_387controlword, new_387controlword
#define _Py_SET_53BIT_PRECISION_START \
do { \
old_387controlword = _Py_get_387controlword(); \
new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(new_387controlword); \
} while (0)
#define _Py_SET_53BIT_PRECISION_END \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(old_387controlword)
#endif
/* default definitions are empty */
@ -589,7 +589,7 @@ extern "C" {
* extern int x() Py_DEPRECATED(2.5);
*/
#if defined(__GNUC__) && ((__GNUC__ >= 4) || \
(__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
(__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
#else
#define Py_DEPRECATED(VERSION_UNUSED)
@ -615,7 +615,7 @@ int shutdown( int, int );
#endif
#ifdef HAVE__GETPTY
#include <sys/types.h> /* we need to import mode_t */
#include <sys/types.h> /* we need to import mode_t */
extern char * _getpty(int *, int, mode_t, int);
#endif
@ -715,71 +715,71 @@ extern int fdatasync(int);
linkage handling and both of these use __declspec().
*/
#if defined(__CYGWIN__) || defined(__BEOS__)
# define HAVE_DECLSPEC_DLL
# define HAVE_DECLSPEC_DLL
#endif
/* only get special linkage if built as shared or platform is Cygwin */
#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
# if defined(HAVE_DECLSPEC_DLL)
# ifdef Py_BUILD_CORE
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding (FIXME: BeOS too?) */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) void
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC void
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to http://python.org/doc/FAQ.html#3.24 */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) void
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) void
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC */
# if defined(HAVE_DECLSPEC_DLL)
# ifdef Py_BUILD_CORE
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding (FIXME: BeOS too?) */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) void
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC void
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to http://python.org/doc/FAQ.html#3.24 */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) void
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) void
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC */
#endif /* Py_ENABLE_SHARED */
/* If no external linkage macros defined by now, create defaults */
#ifndef PyAPI_FUNC
# define PyAPI_FUNC(RTYPE) RTYPE
# define PyAPI_FUNC(RTYPE) RTYPE
#endif
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern RTYPE
# define PyAPI_DATA(RTYPE) extern RTYPE
#endif
#ifndef PyMODINIT_FUNC
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" void
# else /* __cplusplus */
# define PyMODINIT_FUNC void
# endif /* __cplusplus */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" void
# else /* __cplusplus */
# define PyMODINIT_FUNC void
# endif /* __cplusplus */
#endif
/* Deprecated DL_IMPORT and DL_EXPORT macros */
#if defined(Py_ENABLE_SHARED) && defined (HAVE_DECLSPEC_DLL)
# if defined(Py_BUILD_CORE)
# define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE
# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
# else
# define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE
# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
# endif
# if defined(Py_BUILD_CORE)
# define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE
# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
# else
# define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE
# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE
# endif
#endif
#ifndef DL_EXPORT
# define DL_EXPORT(RTYPE) RTYPE
# define DL_EXPORT(RTYPE) RTYPE
#endif
#ifndef DL_IMPORT
# define DL_IMPORT(RTYPE) RTYPE
# define DL_IMPORT(RTYPE) RTYPE
#endif
/* End of deprecated DL_* macros */
@ -788,27 +788,27 @@ extern int fdatasync(int);
#if 0 /* disabled and probably obsolete */
#ifndef FD_SETSIZE
#define FD_SETSIZE 256
#ifndef FD_SETSIZE
#define FD_SETSIZE 256
#endif
#ifndef FD_SET
typedef long fd_mask;
#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
#ifndef howmany
#define howmany(x, y) (((x)+((y)-1))/(y))
#define howmany(x, y) (((x)+((y)-1))/(y))
#endif /* howmany */
typedef struct fd_set {
fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
typedef struct fd_set {
fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
} fd_set;
#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p)))
#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p)))
#endif /* FD_SET */

View file

@ -16,7 +16,7 @@ extern "C" {
#define PyCF_ONLY_AST 0x0400
typedef struct {
int cf_flags; /* bitmask of CO_xxx flags relevant to future */
int cf_flags; /* bitmask of CO_xxx flags relevant to future */
} PyCompilerFlags;
PyAPI_FUNC(void) Py_SetProgramName(char *);
@ -39,32 +39,32 @@ PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, const char *, int, PyCompilerFla
PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *);
PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *);
PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
int, PyCompilerFlags *flags,
PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
int, PyCompilerFlags *flags,
PyArena *);
PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, int,
char *, char *,
PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, int,
char *, char *,
PyCompilerFlags *, int *,
PyArena *);
#define PyParser_SimpleParseString(S, B) \
PyParser_SimpleParseStringFlags(S, B, 0)
PyParser_SimpleParseStringFlags(S, B, 0)
#define PyParser_SimpleParseFile(FP, S, B) \
PyParser_SimpleParseFileFlags(FP, S, B, 0)
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
int);
PyParser_SimpleParseFileFlags(FP, S, B, 0)
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
int);
PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *,
int, int);
int, int);
PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
PyObject *, PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
PyObject *, PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
PyObject *, PyObject *, int,
PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
PyObject *, PyObject *, int,
PyCompilerFlags *);
#define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL)
PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int,
PyCompilerFlags *);
PyCompilerFlags *);
PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int);
PyAPI_FUNC(void) PyErr_Print(void);
@ -84,20 +84,20 @@ PyAPI_FUNC(int) Py_Main(int argc, char **argv);
#define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL)
#define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL)
#define PyRun_AnyFileEx(fp, name, closeit) \
PyRun_AnyFileExFlags(fp, name, closeit, NULL)
PyRun_AnyFileExFlags(fp, name, closeit, NULL)
#define PyRun_AnyFileFlags(fp, name, flags) \
PyRun_AnyFileExFlags(fp, name, 0, flags)
PyRun_AnyFileExFlags(fp, name, 0, flags)
#define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL)
#define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL)
#define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL)
#define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL)
#define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL)
#define PyRun_File(fp, p, s, g, l) \
PyRun_FileExFlags(fp, p, s, g, l, 0, NULL)
PyRun_FileExFlags(fp, p, s, g, l, 0, NULL)
#define PyRun_FileEx(fp, p, s, g, l, c) \
PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
#define PyRun_FileFlags(fp, p, s, g, l, flags) \
PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
/* In getpath.c */
PyAPI_FUNC(char *) Py_GetProgramFullPath(void);

View file

@ -22,8 +22,8 @@ no meaning otherwise.
#define PySet_MINSIZE 8
typedef struct {
long hash; /* cached hash code for the entry key */
PyObject *key;
long hash; /* cached hash code for the entry key */
PyObject *key;
} setentry;
@ -33,27 +33,27 @@ This data structure is shared by set and frozenset objects.
typedef struct _setobject PySetObject;
struct _setobject {
PyObject_HEAD
PyObject_HEAD
Py_ssize_t fill; /* # Active + # Dummy */
Py_ssize_t used; /* # Active */
Py_ssize_t fill; /* # Active + # Dummy */
Py_ssize_t used; /* # Active */
/* The table contains mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t mask;
/* The table contains mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t mask;
/* table points to smalltable for small tables, else to
* additional malloc'ed memory. table is never NULL! This rule
* saves repeated runtime null-tests.
*/
setentry *table;
setentry *(*lookup)(PySetObject *so, PyObject *key, long hash);
setentry smalltable[PySet_MINSIZE];
/* table points to smalltable for small tables, else to
* additional malloc'ed memory. table is never NULL! This rule
* saves repeated runtime null-tests.
*/
setentry *table;
setentry *(*lookup)(PySetObject *so, PyObject *key, long hash);
setentry smalltable[PySet_MINSIZE];
long hash; /* only used by frozenset objects */
PyObject *weakreflist; /* List of weak references */
long hash; /* only used by frozenset objects */
PyObject *weakreflist; /* List of weak references */
};
PyAPI_DATA(PyTypeObject) PySet_Type;
@ -68,17 +68,17 @@ PyAPI_DATA(PyTypeObject) PyFrozenSet_Type;
#define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type)
#define PyAnySet_CheckExact(ob) \
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type)
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type)
#define PyAnySet_Check(ob) \
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
#define PySet_Check(ob) \
(Py_TYPE(ob) == &PySet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
(Py_TYPE(ob) == &PySet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
#define PyFrozenSet_Check(ob) \
(Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
(Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);

View file

@ -26,50 +26,50 @@ extern "C" {
pointer is NULL. */
struct memberlist {
/* Obsolete version, for binary backwards compatibility */
char *name;
int type;
int offset;
int flags;
/* Obsolete version, for binary backwards compatibility */
char *name;
int type;
int offset;
int flags;
};
typedef struct PyMemberDef {
/* Current version, use this */
char *name;
int type;
Py_ssize_t offset;
int flags;
char *doc;
/* Current version, use this */
char *name;
int type;
Py_ssize_t offset;
int flags;
char *doc;
} PyMemberDef;
/* Types */
#define T_SHORT 0
#define T_INT 1
#define T_LONG 2
#define T_FLOAT 3
#define T_DOUBLE 4
#define T_STRING 5
#define T_OBJECT 6
#define T_SHORT 0
#define T_INT 1
#define T_LONG 2
#define T_FLOAT 3
#define T_DOUBLE 4
#define T_STRING 5
#define T_OBJECT 6
/* XXX the ordering here is weird for binary compatibility */
#define T_CHAR 7 /* 1-character string */
#define T_BYTE 8 /* 8-bit signed int */
#define T_CHAR 7 /* 1-character string */
#define T_BYTE 8 /* 8-bit signed int */
/* unsigned variants: */
#define T_UBYTE 9
#define T_USHORT 10
#define T_UINT 11
#define T_ULONG 12
#define T_UBYTE 9
#define T_USHORT 10
#define T_UINT 11
#define T_ULONG 12
/* Added by Jack: strings contained in the structure */
#define T_STRING_INPLACE 13
#define T_STRING_INPLACE 13
/* Added by Lillo: bools contained in the structure (assumed char) */
#define T_BOOL 14
#define T_BOOL 14
#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
when the value is NULL, instead of
converting to None. */
#define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError
when the value is NULL, instead of
converting to None. */
#ifdef HAVE_LONG_LONG
#define T_LONGLONG 17
#define T_LONGLONG 17
#define T_ULONGLONG 18
#endif /* HAVE_LONG_LONG */
@ -77,11 +77,11 @@ typedef struct PyMemberDef {
/* Flags */
#define READONLY 1
#define RO READONLY /* Shorthand */
#define READ_RESTRICTED 2
#define READONLY 1
#define RO READONLY /* Shorthand */
#define READ_RESTRICTED 2
#define PY_WRITE_RESTRICTED 4
#define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED)
#define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED)
/* Obsolete API, for binary backwards compatibility */

View file

@ -11,39 +11,39 @@ typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock }
struct _symtable_entry;
struct symtable {
const char *st_filename; /* name of file being compiled */
struct _symtable_entry *st_cur; /* current symbol table entry */
struct _symtable_entry *st_top; /* module entry */
PyObject *st_symbols; /* dictionary of symbol table entries */
PyObject *st_stack; /* stack of namespace info */
PyObject *st_global; /* borrowed ref to MODULE in st_symbols */
int st_nblocks; /* number of blocks */
PyObject *st_private; /* name of current class or NULL */
PyFutureFeatures *st_future; /* module's future features */
const char *st_filename; /* name of file being compiled */
struct _symtable_entry *st_cur; /* current symbol table entry */
struct _symtable_entry *st_top; /* module entry */
PyObject *st_symbols; /* dictionary of symbol table entries */
PyObject *st_stack; /* stack of namespace info */
PyObject *st_global; /* borrowed ref to MODULE in st_symbols */
int st_nblocks; /* number of blocks */
PyObject *st_private; /* name of current class or NULL */
PyFutureFeatures *st_future; /* module's future features */
};
typedef struct _symtable_entry {
PyObject_HEAD
PyObject *ste_id; /* int: key in st_symbols */
PyObject *ste_symbols; /* dict: name to flags */
PyObject *ste_name; /* string: name of block */
PyObject *ste_varnames; /* list of variable names */
PyObject *ste_children; /* list of child ids */
_Py_block_ty ste_type; /* module, class, or function */
int ste_unoptimized; /* false if namespace is optimized */
int ste_nested; /* true if block is nested */
unsigned ste_free : 1; /* true if block has free variables */
unsigned ste_child_free : 1; /* true if a child block has free vars,
including free refs to globals */
unsigned ste_generator : 1; /* true if namespace is a generator */
unsigned ste_varargs : 1; /* true if block has varargs */
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
unsigned ste_returns_value : 1; /* true if namespace uses return with
an argument */
int ste_lineno; /* first line of block */
int ste_opt_lineno; /* lineno of last exec or import * */
int ste_tmpname; /* counter for listcomp temp vars */
struct symtable *ste_table;
PyObject_HEAD
PyObject *ste_id; /* int: key in st_symbols */
PyObject *ste_symbols; /* dict: name to flags */
PyObject *ste_name; /* string: name of block */
PyObject *ste_varnames; /* list of variable names */
PyObject *ste_children; /* list of child ids */
_Py_block_ty ste_type; /* module, class, or function */
int ste_unoptimized; /* false if namespace is optimized */
int ste_nested; /* true if block is nested */
unsigned ste_free : 1; /* true if block has free variables */
unsigned ste_child_free : 1; /* true if a child block has free vars,
including free refs to globals */
unsigned ste_generator : 1; /* true if namespace is a generator */
unsigned ste_varargs : 1; /* true if block has varargs */
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
unsigned ste_returns_value : 1; /* true if namespace uses return with
an argument */
int ste_lineno; /* first line of block */
int ste_opt_lineno; /* lineno of last exec or import * */
int ste_tmpname; /* counter for listcomp temp vars */
struct symtable *ste_table;
} PySTEntryObject;
PyAPI_DATA(PyTypeObject) PySTEntry_Type;
@ -52,8 +52,8 @@ PyAPI_DATA(PyTypeObject) PySTEntry_Type;
PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *);
PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
PyFutureFeatures *);
PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
PyFutureFeatures *);
PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
@ -71,7 +71,7 @@ PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
/* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
table. GLOBAL is returned from PyST_GetScope() for either of them.
table. GLOBAL is returned from PyST_GetScope() for either of them.
It is stored in ste_symbols at bits 12-14.
*/
#define SCOPE_OFF 11

View file

@ -28,14 +28,14 @@ Copyright (c) Corporation for National Research Initiatives.
*
* --------------------------------------------------------------------
* This Unicode String Type is
*
*
* Copyright (c) 1999 by Secret Labs AB
* Copyright (c) 1999 by Fredrik Lundh
*
*
* By obtaining, using, and/or copying this software and/or its
* associated documentation, you agree that you have read, understood,
* and will comply with the following terms and conditions:
*
*
* Permission to use, copy, modify, and distribute this software and its
* associated documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appears in all
@ -44,7 +44,7 @@ Copyright (c) Corporation for National Research Initiatives.
* AB or the author not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission.
*
*
* SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
@ -124,10 +124,10 @@ Copyright (c) Corporation for National Research Initiatives.
* Use this typedef when you need to represent a UTF-16 surrogate pair
* as single unsigned integer.
*/
#if SIZEOF_INT >= 4
typedef unsigned int Py_UCS4;
#if SIZEOF_INT >= 4
typedef unsigned int Py_UCS4;
#elif SIZEOF_LONG >= 4
typedef unsigned long Py_UCS4;
typedef unsigned long Py_UCS4;
#endif
/* Py_UNICODE is the native Unicode storage format (code unit) used by
@ -361,7 +361,7 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
*/
#define Py_UNICODE_ISSPACE(ch) \
((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
#define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch)
#define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch)
@ -386,16 +386,16 @@ typedef PY_UNICODE_TYPE Py_UNICODE;
#define Py_UNICODE_ISALNUM(ch) \
(Py_UNICODE_ISALPHA(ch) || \
Py_UNICODE_ISDECIMAL(ch) || \
Py_UNICODE_ISDIGIT(ch) || \
Py_UNICODE_ISNUMERIC(ch))
Py_UNICODE_ISDECIMAL(ch) || \
Py_UNICODE_ISDIGIT(ch) || \
Py_UNICODE_ISNUMERIC(ch))
#define Py_UNICODE_COPY(target, source, length) \
Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE))
#define Py_UNICODE_COPY(target, source, length) \
Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE))
#define Py_UNICODE_FILL(target, value, length) \
do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
} while (0)
/* Check if substring matches at given offset. the offset must be
@ -414,12 +414,12 @@ extern "C" {
typedef struct {
PyObject_HEAD
Py_ssize_t length; /* Length of raw Unicode data in buffer */
Py_UNICODE *str; /* Raw Unicode buffer */
long hash; /* Hash value; -1 if not set */
PyObject *defenc; /* (Default) Encoded version as Python
string, or NULL; this is used for
implementing the buffer protocol */
Py_ssize_t length; /* Length of raw Unicode data in buffer */
Py_UNICODE *str; /* Raw Unicode buffer */
long hash; /* Hash value; -1 if not set */
PyObject *defenc; /* (Default) Encoded version as Python
string, or NULL; this is used for
implementing the buffer protocol */
} PyUnicodeObject;
PyAPI_DATA(PyTypeObject) PyUnicode_Type;
@ -430,13 +430,13 @@ PyAPI_DATA(PyTypeObject) PyUnicode_Type;
/* Fast access macros */
#define PyUnicode_GET_SIZE(op) \
(((PyUnicodeObject *)(op))->length)
(((PyUnicodeObject *)(op))->length)
#define PyUnicode_GET_DATA_SIZE(op) \
(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))
(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))
#define PyUnicode_AS_UNICODE(op) \
(((PyUnicodeObject *)(op))->str)
(((PyUnicodeObject *)(op))->str)
#define PyUnicode_AS_DATA(op) \
((const char *)((PyUnicodeObject *)(op))->str)
((const char *)((PyUnicodeObject *)(op))->str)
/* --- Constants ---------------------------------------------------------- */
@ -452,7 +452,7 @@ PyAPI_DATA(PyTypeObject) PyUnicode_Type;
/* --- Plain Py_UNICODE --------------------------------------------------- */
/* Create a Unicode Object from the Py_UNICODE buffer u of the given
size.
size.
u may be NULL which causes the contents to be undefined. It is the
user's responsibility to fill in the needed data afterwards. Note
@ -482,13 +482,13 @@ PyAPI_FUNC(PyObject*) PyUnicode_FromString(
Py_UNICODE buffer. */
PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
/* Get the length of the Unicode object. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
/* Get the maximum ordinal for a Unicode character. */
@ -509,8 +509,8 @@ PyAPI_FUNC(Py_UNICODE) PyUnicode_GetMax(void);
*/
PyAPI_FUNC(int) PyUnicode_Resize(
PyObject **unicode, /* Pointer to the Unicode object */
Py_ssize_t length /* New length */
PyObject **unicode, /* Pointer to the Unicode object */
Py_ssize_t length /* New length */
);
/* Coerce obj to an Unicode object and return a reference with
@ -531,14 +531,14 @@ PyAPI_FUNC(int) PyUnicode_Resize(
*/
PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
register PyObject *obj, /* Object */
register PyObject *obj, /* Object */
const char *encoding, /* encoding */
const char *errors /* error handling */
);
/* Coerce obj to an Unicode object and return a reference with
*incremented* refcount.
Unicode objects are passed back as-is (subclasses are converted to
true Unicode objects), all other objects are delegated to
PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in
@ -550,7 +550,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject(
*/
PyAPI_FUNC(PyObject*) PyUnicode_FromObject(
register PyObject *obj /* Object */
register PyObject *obj /* Object */
);
PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list);
@ -559,8 +559,8 @@ PyAPI_FUNC(PyObject *) PyUnicode_FromFormat(const char*, ...);
/* Format the object based on the format_spec, as defined in PEP 3101
(Advanced String Formatting). */
PyAPI_FUNC(PyObject *) _PyUnicode_FormatAdvanced(PyObject *obj,
Py_UNICODE *format_spec,
Py_ssize_t format_spec_len);
Py_UNICODE *format_spec,
Py_ssize_t format_spec_len);
/* --- wchar_t support for platforms which support it --------------------- */
@ -598,8 +598,8 @@ PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar(
/* --- Unicode ordinals --------------------------------------------------- */
/* Create a Unicode Object from the given Unicode code point ordinal.
/* Create a Unicode Object from the given Unicode code point ordinal.
The ordinal must be in range(0x10000) on narrow Python builds
(UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is
raised in case it is not.
@ -619,11 +619,11 @@ PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal);
PyAPI_FUNC(int) PyUnicode_ClearFreeList(void);
/* === Builtin Codecs =====================================================
/* === Builtin Codecs =====================================================
Many of these APIs take two arguments encoding and errors. These
parameters encoding and errors have the same semantics as the ones
of the builtin unicode() API.
of the builtin unicode() API.
Setting encoding to NULL causes the default encoding to be used.
@ -640,7 +640,7 @@ PyAPI_FUNC(int) PyUnicode_ClearFreeList(void);
/* --- Manage the default encoding ---------------------------------------- */
/* Return a Python string holding the default encoded value of the
Unicode object.
Unicode object.
The resulting string is cached in the Unicode object for subsequent
usage by this function. The cached version is needed to implement
@ -662,7 +662,7 @@ PyAPI_FUNC(PyObject *) _PyUnicode_AsDefaultEncodedString(
process global. This may change in future versions of the
interpreter to become a parameter which is managed on a per-thread
basis.
*/
PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
@ -670,11 +670,11 @@ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
/* Sets the currently active default encoding.
Returns 0 on success, -1 in case of an error.
*/
PyAPI_FUNC(int) PyUnicode_SetDefaultEncoding(
const char *encoding /* Encoding name in standard form */
const char *encoding /* Encoding name in standard form */
);
/* --- Generic Codecs ----------------------------------------------------- */
@ -689,7 +689,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_Decode(
const char *errors /* error handling */
);
/* Encodes a Py_UNICODE buffer of the given size and returns a
/* Encodes a Py_UNICODE buffer of the given size and returns a
Python string object. */
PyAPI_FUNC(PyObject*) PyUnicode_Encode(
@ -703,18 +703,18 @@ PyAPI_FUNC(PyObject*) PyUnicode_Encode(
object. */
PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
);
/* Encodes a Unicode object and returns the result as Python string
object. */
PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString(
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
PyObject *unicode, /* Unicode object */
const char *encoding, /* encoding */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap(
@ -725,49 +725,49 @@ PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap(
/* --- UTF-7 Codecs ------------------------------------------------------- */
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7(
const char *string, /* UTF-7 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* UTF-7 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful(
const char *string, /* UTF-7 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
Py_ssize_t *consumed /* bytes consumed */
const char *string, /* UTF-7 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
Py_ssize_t *consumed /* bytes consumed */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
int base64SetO, /* Encode RFC2152 Set O characters in base64 */
int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
int base64SetO, /* Encode RFC2152 Set O characters in base64 */
int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */
const char *errors /* error handling */
);
/* --- UTF-8 Codecs ------------------------------------------------------- */
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8(
const char *string, /* UTF-8 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* UTF-8 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful(
const char *string, /* UTF-8 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
Py_ssize_t *consumed /* bytes consumed */
const char *string, /* UTF-8 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
Py_ssize_t *consumed /* bytes consumed */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors /* error handling */
);
/* --- UTF-32 Codecs ------------------------------------------------------ */
@ -776,14 +776,14 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
the corresponding Unicode object.
errors (if non-NULL) defines the error handling. It defaults
to "strict".
to "strict".
If byteorder is non-NULL, the decoder starts decoding using the
given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
In native mode, the first four bytes of the stream are checked for a
BOM mark. If found, the BOM mark is analysed, the byte order
@ -796,29 +796,29 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
*/
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32(
const char *string, /* UTF-32 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
const char *string, /* UTF-32 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
);
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful(
const char *string, /* UTF-32 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder, /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
Py_ssize_t *consumed /* bytes consumed */
const char *string, /* UTF-32 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder, /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
Py_ssize_t *consumed /* bytes consumed */
);
/* Returns a Python string using the UTF-32 encoding in native byte
order. The string always starts with a BOM mark. */
PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
/* Returns a Python string object holding the UTF-32 encoded value of
@ -838,10 +838,10 @@ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String(
*/
PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors, /* error handling */
int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors, /* error handling */
int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
);
/* --- UTF-16 Codecs ------------------------------------------------------ */
@ -850,14 +850,14 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
the corresponding Unicode object.
errors (if non-NULL) defines the error handling. It defaults
to "strict".
to "strict".
If byteorder is non-NULL, the decoder starts decoding using the
given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
In native mode, the first two bytes of the stream are checked for a
BOM mark. If found, the BOM mark is analysed, the byte order
@ -870,29 +870,29 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
*/
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16(
const char *string, /* UTF-16 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
const char *string, /* UTF-16 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
);
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful(
const char *string, /* UTF-16 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder, /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
Py_ssize_t *consumed /* bytes consumed */
const char *string, /* UTF-16 encoded string */
Py_ssize_t length, /* size of string */
const char *errors, /* error handling */
int *byteorder, /* pointer to byteorder to use
0=native;-1=LE,1=BE; updated on
exit */
Py_ssize_t *consumed /* bytes consumed */
);
/* Returns a Python string using the UTF-16 encoding in native byte
order. The string always starts with a BOM mark. */
PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
/* Returns a Python string object holding the UTF-16 encoded value of
@ -916,44 +916,44 @@ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String(
*/
PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors, /* error handling */
int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* number of Py_UNICODE chars to encode */
const char *errors, /* error handling */
int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */
);
/* --- Unicode-Escape Codecs ---------------------------------------------- */
PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape(
const char *string, /* Unicode-Escape encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* Unicode-Escape encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length /* Number of Py_UNICODE chars to encode */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length /* Number of Py_UNICODE chars to encode */
);
/* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape(
const char *string, /* Raw-Unicode-Escape encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* Raw-Unicode-Escape encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length /* Number of Py_UNICODE chars to encode */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length /* Number of Py_UNICODE chars to encode */
);
/* --- Unicode Internal Codec ---------------------------------------------
@ -966,53 +966,53 @@ PyObject *_PyUnicode_DecodeUnicodeInternal(
const char *errors
);
/* --- Latin-1 Codecs -----------------------------------------------------
/* --- Latin-1 Codecs -----------------------------------------------------
Note: Latin-1 corresponds to the first 256 Unicode ordinals.
*/
PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1(
const char *string, /* Latin-1 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* Latin-1 encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
const char *errors /* error handling */
);
/* --- ASCII Codecs -------------------------------------------------------
/* --- ASCII Codecs -------------------------------------------------------
Only 7-bit ASCII data is excepted. All other codes generate errors.
*/
PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII(
const char *string, /* ASCII encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
const char *string, /* ASCII encoded string */
Py_ssize_t length, /* size of string */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString(
PyObject *unicode /* Unicode object */
PyObject *unicode /* Unicode object */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
const char *errors /* error handling */
);
/* --- Character Map Codecs -----------------------------------------------
/* --- Character Map Codecs -----------------------------------------------
This codec uses mappings to encode and decode characters.
This codec uses mappings to encode and decode characters.
Decoding mappings must map single string characters to single
Unicode characters, integers (which are then interpreted as Unicode
@ -1033,25 +1033,25 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
*/
PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap(
const char *string, /* Encoded string */
Py_ssize_t length, /* size of string */
PyObject *mapping, /* character mapping
(char ordinal -> unicode ordinal) */
const char *errors /* error handling */
const char *string, /* Encoded string */
Py_ssize_t length, /* size of string */
PyObject *mapping, /* character mapping
(char ordinal -> unicode ordinal) */
const char *errors /* error handling */
);
PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString(
PyObject *unicode, /* Unicode object */
PyObject *mapping /* character mapping
(unicode ordinal -> char ordinal) */
PyObject *unicode, /* Unicode object */
PyObject *mapping /* character mapping
(unicode ordinal -> char ordinal) */
);
PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
PyObject *mapping, /* character mapping
(unicode ordinal -> char ordinal) */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
PyObject *mapping, /* character mapping
(unicode ordinal -> char ordinal) */
const char *errors /* error handling */
);
/* Translate a Py_UNICODE buffer of the given length by applying a
@ -1059,7 +1059,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
object.
The mapping table must map Unicode ordinal integers to Unicode
ordinal integers or None (causing deletion of the character).
ordinal integers or None (causing deletion of the character).
Mapping tables may be dictionaries or sequences. Unmapped character
ordinals (ones which cause a LookupError) are left untouched and
@ -1068,10 +1068,10 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
*/
PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
PyObject *table, /* Translate table */
const char *errors /* error handling */
const Py_UNICODE *data, /* Unicode char buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
PyObject *table, /* Translate table */
const char *errors /* error handling */
);
#ifdef MS_WIN32
@ -1120,7 +1120,7 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
NULL or "strict": raise a ValueError
"ignore": ignore the wrong characters (these are not copied to the
output buffer)
output buffer)
"replace": replaces illegal characters with '?'
Returns 0 on success, -1 on failure.
@ -1128,10 +1128,10 @@ PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
*/
PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
Py_UNICODE *s, /* Unicode buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
char *output, /* Output buffer; must have size >= length */
const char *errors /* error handling */
Py_UNICODE *s, /* Unicode buffer */
Py_ssize_t length, /* Number of Py_UNICODE chars to encode */
char *output, /* Output buffer; must have size >= length */
const char *errors /* error handling */
);
/* --- Methods & Slots ----------------------------------------------------
@ -1143,8 +1143,8 @@ PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
/* Concat two strings giving a new Unicode string. */
PyAPI_FUNC(PyObject*) PyUnicode_Concat(
PyObject *left, /* Left string */
PyObject *right /* Right string */
PyObject *left, /* Left string */
PyObject *right /* Right string */
);
/* Split a string giving a list of Unicode strings.
@ -1159,35 +1159,35 @@ PyAPI_FUNC(PyObject*) PyUnicode_Concat(
*/
PyAPI_FUNC(PyObject*) PyUnicode_Split(
PyObject *s, /* String to split */
PyObject *sep, /* String separator */
Py_ssize_t maxsplit /* Maxsplit count */
);
PyObject *s, /* String to split */
PyObject *sep, /* String separator */
Py_ssize_t maxsplit /* Maxsplit count */
);
/* Dito, but split at line breaks.
CRLF is considered to be one line break. Line breaks are not
included in the resulting list. */
PyAPI_FUNC(PyObject*) PyUnicode_Splitlines(
PyObject *s, /* String to split */
int keepends /* If true, line end markers are included */
);
PyObject *s, /* String to split */
int keepends /* If true, line end markers are included */
);
/* Partition a string using a given separator. */
PyAPI_FUNC(PyObject*) PyUnicode_Partition(
PyObject *s, /* String to partition */
PyObject *sep /* String separator */
);
PyObject *s, /* String to partition */
PyObject *sep /* String separator */
);
/* Partition a string using a given separator, searching from the end of the
string. */
PyAPI_FUNC(PyObject*) PyUnicode_RPartition(
PyObject *s, /* String to partition */
PyObject *sep /* String separator */
);
PyObject *s, /* String to partition */
PyObject *sep /* String separator */
);
/* Split a string giving a list of Unicode strings.
@ -1203,16 +1203,16 @@ PyAPI_FUNC(PyObject*) PyUnicode_RPartition(
*/
PyAPI_FUNC(PyObject*) PyUnicode_RSplit(
PyObject *s, /* String to split */
PyObject *sep, /* String separator */
Py_ssize_t maxsplit /* Maxsplit count */
);
PyObject *s, /* String to split */
PyObject *sep, /* String separator */
Py_ssize_t maxsplit /* Maxsplit count */
);
/* Translate a string by applying a character mapping table to it and
return the resulting Unicode object.
The mapping table must map Unicode ordinal integers to Unicode
ordinal integers or None (causing deletion of the character).
ordinal integers or None (causing deletion of the character).
Mapping tables may be dictionaries or sequences. Unmapped character
ordinals (ones which cause a LookupError) are left untouched and
@ -1221,28 +1221,28 @@ PyAPI_FUNC(PyObject*) PyUnicode_RSplit(
*/
PyAPI_FUNC(PyObject *) PyUnicode_Translate(
PyObject *str, /* String */
PyObject *table, /* Translate table */
const char *errors /* error handling */
PyObject *str, /* String */
PyObject *table, /* Translate table */
const char *errors /* error handling */
);
/* Join a sequence of strings using the given separator and return
the resulting Unicode string. */
PyAPI_FUNC(PyObject*) PyUnicode_Join(
PyObject *separator, /* Separator string */
PyObject *seq /* Sequence object */
PyObject *separator, /* Separator string */
PyObject *seq /* Sequence object */
);
/* Return 1 if substr matches str[start:end] at the given tail end, 0
otherwise. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch(
PyObject *str, /* String */
PyObject *substr, /* Prefix or Suffix string */
Py_ssize_t start, /* Start index */
Py_ssize_t end, /* Stop index */
int direction /* Tail end: -1 prefix, +1 suffix */
PyObject *str, /* String */
PyObject *substr, /* Prefix or Suffix string */
Py_ssize_t start, /* Start index */
Py_ssize_t end, /* Stop index */
int direction /* Tail end: -1 prefix, +1 suffix */
);
/* Return the first position of substr in str[start:end] using the
@ -1250,39 +1250,39 @@ PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch(
an error occurred and an exception is set. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_Find(
PyObject *str, /* String */
PyObject *substr, /* Substring to find */
Py_ssize_t start, /* Start index */
Py_ssize_t end, /* Stop index */
int direction /* Find direction: +1 forward, -1 backward */
PyObject *str, /* String */
PyObject *substr, /* Substring to find */
Py_ssize_t start, /* Start index */
Py_ssize_t end, /* Stop index */
int direction /* Find direction: +1 forward, -1 backward */
);
/* Count the number of occurrences of substr in str[start:end]. */
PyAPI_FUNC(Py_ssize_t) PyUnicode_Count(
PyObject *str, /* String */
PyObject *substr, /* Substring to count */
Py_ssize_t start, /* Start index */
Py_ssize_t end /* Stop index */
PyObject *str, /* String */
PyObject *substr, /* Substring to count */
Py_ssize_t start, /* Start index */
Py_ssize_t end /* Stop index */
);
/* Replace at most maxcount occurrences of substr in str with replstr
and return the resulting Unicode object. */
PyAPI_FUNC(PyObject *) PyUnicode_Replace(
PyObject *str, /* String */
PyObject *substr, /* Substring to find */
PyObject *replstr, /* Substring to replace */
Py_ssize_t maxcount /* Max. number of replacements to apply;
-1 = all */
PyObject *str, /* String */
PyObject *substr, /* Substring to find */
PyObject *replstr, /* Substring to replace */
Py_ssize_t maxcount /* Max. number of replacements to apply;
-1 = all */
);
/* Compare two strings and return -1, 0, 1 for less than, equal,
greater than resp. */
PyAPI_FUNC(int) PyUnicode_Compare(
PyObject *left, /* Left string */
PyObject *right /* Right string */
PyObject *left, /* Left string */
PyObject *right /* Right string */
);
/* Rich compare two strings and return one of the following:
@ -1302,17 +1302,17 @@ PyAPI_FUNC(int) PyUnicode_Compare(
*/
PyAPI_FUNC(PyObject *) PyUnicode_RichCompare(
PyObject *left, /* Left string */
PyObject *right, /* Right string */
int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */
PyObject *left, /* Left string */
PyObject *right, /* Right string */
int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */
);
/* Apply a argument tuple or dictionary to a format string and return
the resulting Unicode string. */
PyAPI_FUNC(PyObject *) PyUnicode_Format(
PyObject *format, /* Format string */
PyObject *args /* Argument tuple or dictionary */
PyObject *format, /* Format string */
PyObject *args /* Argument tuple or dictionary */
);
/* Checks whether element is contained in container and return 1/0
@ -1322,8 +1322,8 @@ PyAPI_FUNC(PyObject *) PyUnicode_Format(
returned in case of an error. */
PyAPI_FUNC(int) PyUnicode_Contains(
PyObject *container, /* Container string */
PyObject *element /* Element string */
PyObject *container, /* Container string */
PyObject *element /* Element string */
);
/* Externally visible for str.strip(unicode) */
@ -1340,70 +1340,70 @@ PyAPI_FUNC(PyObject *) _PyUnicode_XStrip(
PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
/* These should not be used directly. Use the Py_UNICODE_IS* and
Py_UNICODE_TO* macros instead.
Py_UNICODE_TO* macros instead.
These APIs are implemented in Objects/unicodectype.c.
*/
PyAPI_FUNC(int) _PyUnicode_IsLowercase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsUppercase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsTitlecase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsWhitespace(
const Py_UNICODE ch /* Unicode character */
const Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsLinebreak(
const Py_UNICODE ch /* Unicode character */
const Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_ToDigit(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(double) _PyUnicode_ToNumeric(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsDigit(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsNumeric(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
PyAPI_FUNC(int) _PyUnicode_IsAlpha(
Py_UNICODE ch /* Unicode character */
Py_UNICODE ch /* Unicode character */
);
#ifdef __cplusplus

View file

@ -7,15 +7,15 @@ Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Just van Rossum not be
used in advertising or publicity pertaining to distribution of the
supporting documentation, and that the name of Just van Rossum not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
JUST VAN ROSSUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL JUST VAN ROSSUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
JUST VAN ROSSUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL JUST VAN ROSSUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@ -37,17 +37,17 @@ static char cp_GetColor__doc__[] =
static PyObject *
cp_GetColor(PyObject *self, PyObject *args)
{
RGBColor inColor, outColor;
Boolean ok;
Point where = {0, 0};
Str255 prompt;
if (!PyArg_ParseTuple(args, "O&O&", PyMac_GetStr255, prompt, QdRGB_Convert, &inColor))
return NULL;
ok = GetColor(where, prompt, &inColor, &outColor);
return Py_BuildValue("O&h", QdRGB_New, &outColor, ok);
RGBColor inColor, outColor;
Boolean ok;
Point where = {0, 0};
Str255 prompt;
if (!PyArg_ParseTuple(args, "O&O&", PyMac_GetStr255, prompt, QdRGB_Convert, &inColor))
return NULL;
ok = GetColor(where, prompt, &inColor, &outColor);
return Py_BuildValue("O&h", QdRGB_New, &outColor, ok);
}
#endif /* __LP64__ */
@ -55,36 +55,36 @@ cp_GetColor(PyObject *self, PyObject *args)
static struct PyMethodDef cp_methods[] = {
#ifndef __LP64__
{"GetColor", (PyCFunction)cp_GetColor, METH_VARARGS, cp_GetColor__doc__},
{"GetColor", (PyCFunction)cp_GetColor, METH_VARARGS, cp_GetColor__doc__},
#endif /* __LP64__ */
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initColorPicker) */
static char cp_module_documentation[] =
static char cp_module_documentation[] =
""
;
void initColorPicker(void)
{
PyObject *m;
if (PyErr_WarnPy3k("In 3.x, the ColorPicker module is removed.", 1) < 0)
return;
PyObject *m;
/* Create the module and add the functions */
m = Py_InitModule4("ColorPicker", cp_methods,
cp_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
if (PyErr_WarnPy3k("In 3.x, the ColorPicker module is removed.", 1) < 0)
return;
/* Add symbolic constants to the module here */
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module ColorPicker");
/* Create the module and add the functions */
m = Py_InitModule4("ColorPicker", cp_methods,
cp_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
/* Add symbolic constants to the module here */
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module ColorPicker");
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -18,85 +18,85 @@
static PyObject *
PyOSA_GetAppTerminology(PyObject* self, PyObject* args)
{
AEDesc theDesc = {0,0};
FSSpec fss;
ComponentInstance defaultComponent = NULL;
SInt16 defaultTerminology = 0;
Boolean didLaunch = 0;
OSAError err;
long modeFlags = 0;
if (!PyArg_ParseTuple(args, "O&|i", PyMac_GetFSSpec, &fss, &modeFlags))
return NULL;
/*
** Note that we have to use the AppleScript component here. Who knows why
** OSAGetAppTerminology should require a scripting component in the
** first place, but it does. Note: doesn't work with the generic scripting
** component, which is unfortunate as the AS component is currently very
** slow (~1 sec?) to load, but we just have to live with this.
*/
defaultComponent = OpenDefaultComponent (kOSAComponentType, 'ascr');
err = GetComponentInstanceError (defaultComponent);
if (err) return PyMac_Error(err);
err = OSAGetAppTerminology (
defaultComponent,
kOSAModeNull,
&fss,
defaultTerminology,
&didLaunch,
&theDesc
);
if (err) return PyMac_Error(err);
return Py_BuildValue("O&i", AEDesc_New, &theDesc, didLaunch);
AEDesc theDesc = {0,0};
FSSpec fss;
ComponentInstance defaultComponent = NULL;
SInt16 defaultTerminology = 0;
Boolean didLaunch = 0;
OSAError err;
long modeFlags = 0;
if (!PyArg_ParseTuple(args, "O&|i", PyMac_GetFSSpec, &fss, &modeFlags))
return NULL;
/*
** Note that we have to use the AppleScript component here. Who knows why
** OSAGetAppTerminology should require a scripting component in the
** first place, but it does. Note: doesn't work with the generic scripting
** component, which is unfortunate as the AS component is currently very
** slow (~1 sec?) to load, but we just have to live with this.
*/
defaultComponent = OpenDefaultComponent (kOSAComponentType, 'ascr');
err = GetComponentInstanceError (defaultComponent);
if (err) return PyMac_Error(err);
err = OSAGetAppTerminology (
defaultComponent,
kOSAModeNull,
&fss,
defaultTerminology,
&didLaunch,
&theDesc
);
if (err) return PyMac_Error(err);
return Py_BuildValue("O&i", AEDesc_New, &theDesc, didLaunch);
}
static PyObject *
PyOSA_GetSysTerminology(PyObject* self, PyObject* args)
{
AEDesc theDesc = {0,0};
ComponentInstance defaultComponent = NULL;
SInt16 defaultTerminology = 0;
OSAError err;
/* Accept any args for sake of backwards compatibility, then ignore them. */
AEDesc theDesc = {0,0};
ComponentInstance defaultComponent = NULL;
SInt16 defaultTerminology = 0;
OSAError err;
defaultComponent = OpenDefaultComponent (kOSAComponentType, 'ascr');
err = GetComponentInstanceError (defaultComponent);
if (err) return PyMac_Error(err);
err = OSAGetSysTerminology (
defaultComponent,
kOSAModeNull,
defaultTerminology,
&theDesc
);
if (err) return PyMac_Error(err);
return Py_BuildValue("O&", AEDesc_New, &theDesc);
/* Accept any args for sake of backwards compatibility, then ignore them. */
defaultComponent = OpenDefaultComponent (kOSAComponentType, 'ascr');
err = GetComponentInstanceError (defaultComponent);
if (err) return PyMac_Error(err);
err = OSAGetSysTerminology (
defaultComponent,
kOSAModeNull,
defaultTerminology,
&theDesc
);
if (err) return PyMac_Error(err);
return Py_BuildValue("O&", AEDesc_New, &theDesc);
}
#endif /* !__LP64__ */
/*
/*
* List of methods defined in the module
*/
static struct PyMethodDef OSATerminology_methods[] =
{
#ifndef __LP64__
{"GetAppTerminology",
(PyCFunction) PyOSA_GetAppTerminology,
METH_VARARGS,
"Get an application's terminology. GetAppTerminology(path) --> AEDesc"},
{"GetSysTerminology",
(PyCFunction) PyOSA_GetSysTerminology,
METH_VARARGS,
"Get the AppleScript language's terminology. GetSysTerminology() --> AEDesc"},
{"GetAppTerminology",
(PyCFunction) PyOSA_GetAppTerminology,
METH_VARARGS,
"Get an application's terminology. GetAppTerminology(path) --> AEDesc"},
{"GetSysTerminology",
(PyCFunction) PyOSA_GetSysTerminology,
METH_VARARGS,
"Get the AppleScript language's terminology. GetSysTerminology() --> AEDesc"},
#endif /* !__LP64__ */
{NULL, (PyCFunction) NULL, 0, NULL}
{NULL, (PyCFunction) NULL, 0, NULL}
};
void
initOSATerminology(void)
{
if (PyErr_WarnPy3k("In 3.x, the OSATerminology module is removed.", 1) < 0)
return;
Py_InitModule("OSATerminology", OSATerminology_methods);
if (PyErr_WarnPy3k("In 3.x, the OSATerminology module is removed.", 1) < 0)
return;
Py_InitModule("OSATerminology", OSATerminology_methods);
}

View file

@ -5,162 +5,162 @@
#include <Python.h>
#include <SystemConfiguration/SystemConfiguration.h>
static int32_t
static int32_t
cfnum_to_int32(CFNumberRef num)
{
int32_t result;
int32_t result;
CFNumberGetValue(num, kCFNumberSInt32Type, &result);
return result;
CFNumberGetValue(num, kCFNumberSInt32Type, &result);
return result;
}
static PyObject*
cfstring_to_pystring(CFStringRef ref)
{
const char* s;
const char* s;
s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
if (s) {
return PyString_FromString(s);
s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
if (s) {
return PyString_FromString(s);
} else {
CFIndex len = CFStringGetLength(ref);
Boolean ok;
PyObject* result;
result = PyString_FromStringAndSize(NULL, len*4);
} else {
CFIndex len = CFStringGetLength(ref);
Boolean ok;
PyObject* result;
result = PyString_FromStringAndSize(NULL, len*4);
ok = CFStringGetCString(ref,
PyString_AS_STRING(result),
PyString_GET_SIZE(result),
kCFStringEncodingUTF8);
if (!ok) {
Py_DECREF(result);
return NULL;
} else {
_PyString_Resize(&result,
strlen(PyString_AS_STRING(result)));
}
return result;
}
ok = CFStringGetCString(ref,
PyString_AS_STRING(result),
PyString_GET_SIZE(result),
kCFStringEncodingUTF8);
if (!ok) {
Py_DECREF(result);
return NULL;
} else {
_PyString_Resize(&result,
strlen(PyString_AS_STRING(result)));
}
return result;
}
}
static PyObject*
get_proxy_settings(PyObject* mod __attribute__((__unused__)))
{
CFDictionaryRef proxyDict = NULL;
CFNumberRef aNum = NULL;
CFArrayRef anArray = NULL;
PyObject* result = NULL;
PyObject* v;
int r;
CFDictionaryRef proxyDict = NULL;
CFNumberRef aNum = NULL;
CFArrayRef anArray = NULL;
PyObject* result = NULL;
PyObject* v;
int r;
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (!proxyDict) {
Py_INCREF(Py_None);
return Py_None;
}
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (!proxyDict) {
Py_INCREF(Py_None);
return Py_None;
}
result = PyDict_New();
if (result == NULL) goto error;
result = PyDict_New();
if (result == NULL) goto error;
if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
aNum = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExcludeSimpleHostnames);
if (aNum == NULL) {
v = PyBool_FromLong(1);
} else {
v = PyBool_FromLong(cfnum_to_int32(aNum));
}
} else {
v = PyBool_FromLong(1);
}
if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
aNum = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExcludeSimpleHostnames);
if (aNum == NULL) {
v = PyBool_FromLong(1);
} else {
v = PyBool_FromLong(cfnum_to_int32(aNum));
}
} else {
v = PyBool_FromLong(1);
}
if (v == NULL) goto error;
if (v == NULL) goto error;
r = PyDict_SetItemString(result, "exclude_simple", v);
Py_DECREF(v); v = NULL;
if (r == -1) goto error;
r = PyDict_SetItemString(result, "exclude_simple", v);
Py_DECREF(v); v = NULL;
if (r == -1) goto error;
anArray = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExceptionsList);
if (anArray != NULL) {
CFIndex len = CFArrayGetCount(anArray);
CFIndex i;
v = PyTuple_New(len);
if (v == NULL) goto error;
anArray = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExceptionsList);
if (anArray != NULL) {
CFIndex len = CFArrayGetCount(anArray);
CFIndex i;
v = PyTuple_New(len);
if (v == NULL) goto error;
r = PyDict_SetItemString(result, "exceptions", v);
Py_DECREF(v);
if (r == -1) goto error;
r = PyDict_SetItemString(result, "exceptions", v);
Py_DECREF(v);
if (r == -1) goto error;
for (i = 0; i < len; i++) {
CFStringRef aString = NULL;
for (i = 0; i < len; i++) {
CFStringRef aString = NULL;
aString = CFArrayGetValueAtIndex(anArray, i);
if (aString == NULL) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyObject* t = cfstring_to_pystring(aString);
if (!t) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyTuple_SetItem(v, i, t);
}
}
}
}
aString = CFArrayGetValueAtIndex(anArray, i);
if (aString == NULL) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyObject* t = cfstring_to_pystring(aString);
if (!t) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyTuple_SetItem(v, i, t);
}
}
}
}
CFRelease(proxyDict);
return result;
CFRelease(proxyDict);
return result;
error:
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
}
static int
set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
CFStringRef enabledKey,
CFStringRef hostKey, CFStringRef portKey)
CFStringRef enabledKey,
CFStringRef hostKey, CFStringRef portKey)
{
CFNumberRef aNum;
CFNumberRef aNum;
aNum = CFDictionaryGetValue(proxyDict, enabledKey);
if (aNum && cfnum_to_int32(aNum)) {
CFStringRef hostString;
aNum = CFDictionaryGetValue(proxyDict, enabledKey);
if (aNum && cfnum_to_int32(aNum)) {
CFStringRef hostString;
hostString = CFDictionaryGetValue(proxyDict, hostKey);
aNum = CFDictionaryGetValue(proxyDict, portKey);
hostString = CFDictionaryGetValue(proxyDict, hostKey);
aNum = CFDictionaryGetValue(proxyDict, portKey);
if (hostString) {
int r;
PyObject* h = cfstring_to_pystring(hostString);
PyObject* v;
if (h) {
if (aNum) {
int32_t port = cfnum_to_int32(aNum);
v = PyString_FromFormat("http://%s:%ld",
PyString_AS_STRING(h),
(long)port);
} else {
v = PyString_FromFormat("http://%s",
PyString_AS_STRING(h));
}
Py_DECREF(h);
if (!v) return -1;
r = PyDict_SetItemString(proxies, proto,
v);
Py_DECREF(v);
return r;
}
}
if (hostString) {
int r;
PyObject* h = cfstring_to_pystring(hostString);
PyObject* v;
if (h) {
if (aNum) {
int32_t port = cfnum_to_int32(aNum);
v = PyString_FromFormat("http://%s:%ld",
PyString_AS_STRING(h),
(long)port);
} else {
v = PyString_FromFormat("http://%s",
PyString_AS_STRING(h));
}
Py_DECREF(h);
if (!v) return -1;
r = PyDict_SetItemString(proxies, proto,
v);
Py_DECREF(v);
return r;
}
}
}
return 0;
}
return 0;
}
@ -168,64 +168,64 @@ set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
static PyObject*
get_proxies(PyObject* mod __attribute__((__unused__)))
{
PyObject* result = NULL;
int r;
CFDictionaryRef proxyDict = NULL;
PyObject* result = NULL;
int r;
CFDictionaryRef proxyDict = NULL;
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (proxyDict == NULL) {
return PyDict_New();
}
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (proxyDict == NULL) {
return PyDict_New();
}
result = PyDict_New();
if (result == NULL) goto error;
result = PyDict_New();
if (result == NULL) goto error;
r = set_proxy(result, "http", proxyDict,
kSCPropNetProxiesHTTPEnable,
kSCPropNetProxiesHTTPProxy,
kSCPropNetProxiesHTTPPort);
if (r == -1) goto error;
r = set_proxy(result, "https", proxyDict,
kSCPropNetProxiesHTTPSEnable,
kSCPropNetProxiesHTTPSProxy,
kSCPropNetProxiesHTTPSPort);
if (r == -1) goto error;
r = set_proxy(result, "ftp", proxyDict,
kSCPropNetProxiesFTPEnable,
kSCPropNetProxiesFTPProxy,
kSCPropNetProxiesFTPPort);
if (r == -1) goto error;
r = set_proxy(result, "gopher", proxyDict,
kSCPropNetProxiesGopherEnable,
kSCPropNetProxiesGopherProxy,
kSCPropNetProxiesGopherPort);
if (r == -1) goto error;
r = set_proxy(result, "http", proxyDict,
kSCPropNetProxiesHTTPEnable,
kSCPropNetProxiesHTTPProxy,
kSCPropNetProxiesHTTPPort);
if (r == -1) goto error;
r = set_proxy(result, "https", proxyDict,
kSCPropNetProxiesHTTPSEnable,
kSCPropNetProxiesHTTPSProxy,
kSCPropNetProxiesHTTPSPort);
if (r == -1) goto error;
r = set_proxy(result, "ftp", proxyDict,
kSCPropNetProxiesFTPEnable,
kSCPropNetProxiesFTPProxy,
kSCPropNetProxiesFTPPort);
if (r == -1) goto error;
r = set_proxy(result, "gopher", proxyDict,
kSCPropNetProxiesGopherEnable,
kSCPropNetProxiesGopherProxy,
kSCPropNetProxiesGopherPort);
if (r == -1) goto error;
CFRelease(proxyDict);
return result;
CFRelease(proxyDict);
return result;
error:
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
}
static PyMethodDef mod_methods[] = {
{
"_get_proxy_settings",
(PyCFunction)get_proxy_settings,
METH_NOARGS,
NULL,
},
{
"_get_proxies",
(PyCFunction)get_proxies,
METH_NOARGS,
NULL,
},
{ 0, 0, 0, 0 }
{
"_get_proxy_settings",
(PyCFunction)get_proxy_settings,
METH_NOARGS,
NULL,
},
{
"_get_proxies",
(PyCFunction)get_proxies,
METH_NOARGS,
NULL,
},
{ 0, 0, 0, 0 }
};
void init_scproxy(void)
{
(void)Py_InitModule4("_scproxy", mod_methods, NULL, NULL, PYTHON_API_VERSION);
(void)Py_InitModule4("_scproxy", mod_methods, NULL, NULL, PYTHON_API_VERSION);
}

File diff suppressed because it is too large Load diff

View file

@ -9,9 +9,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -22,103 +22,103 @@ static PyObject *Ah_Error;
static PyObject *Ah_AHSearch(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef query;
if (!PyArg_ParseTuple(_args, "O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &query))
return NULL;
_err = AHSearch(bookname,
query);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef query;
if (!PyArg_ParseTuple(_args, "O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &query))
return NULL;
_err = AHSearch(bookname,
query);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Ah_AHGotoMainTOC(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
AHTOCType toctype;
if (!PyArg_ParseTuple(_args, "h",
&toctype))
return NULL;
_err = AHGotoMainTOC(toctype);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
AHTOCType toctype;
if (!PyArg_ParseTuple(_args, "h",
&toctype))
return NULL;
_err = AHGotoMainTOC(toctype);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Ah_AHGotoPage(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef path;
CFStringRef anchor;
if (!PyArg_ParseTuple(_args, "O&O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &path,
CFStringRefObj_Convert, &anchor))
return NULL;
_err = AHGotoPage(bookname,
path,
anchor);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef path;
CFStringRef anchor;
if (!PyArg_ParseTuple(_args, "O&O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &path,
CFStringRefObj_Convert, &anchor))
return NULL;
_err = AHGotoPage(bookname,
path,
anchor);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Ah_AHLookupAnchor(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef anchor;
if (!PyArg_ParseTuple(_args, "O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &anchor))
return NULL;
_err = AHLookupAnchor(bookname,
anchor);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef bookname;
CFStringRef anchor;
if (!PyArg_ParseTuple(_args, "O&O&",
CFStringRefObj_Convert, &bookname,
CFStringRefObj_Convert, &anchor))
return NULL;
_err = AHLookupAnchor(bookname,
anchor);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Ah_AHRegisterHelpBook(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef appBundleRef;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &appBundleRef))
return NULL;
_err = AHRegisterHelpBook(&appBundleRef);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef appBundleRef;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &appBundleRef))
return NULL;
_err = AHRegisterHelpBook(&appBundleRef);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyMethodDef Ah_methods[] = {
{"AHSearch", (PyCFunction)Ah_AHSearch, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef query) -> None")},
{"AHGotoMainTOC", (PyCFunction)Ah_AHGotoMainTOC, 1,
PyDoc_STR("(AHTOCType toctype) -> None")},
{"AHGotoPage", (PyCFunction)Ah_AHGotoPage, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef path, CFStringRef anchor) -> None")},
{"AHLookupAnchor", (PyCFunction)Ah_AHLookupAnchor, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef anchor) -> None")},
{"AHRegisterHelpBook", (PyCFunction)Ah_AHRegisterHelpBook, 1,
PyDoc_STR("(FSRef appBundleRef) -> None")},
{NULL, NULL, 0}
{"AHSearch", (PyCFunction)Ah_AHSearch, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef query) -> None")},
{"AHGotoMainTOC", (PyCFunction)Ah_AHGotoMainTOC, 1,
PyDoc_STR("(AHTOCType toctype) -> None")},
{"AHGotoPage", (PyCFunction)Ah_AHGotoPage, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef path, CFStringRef anchor) -> None")},
{"AHLookupAnchor", (PyCFunction)Ah_AHLookupAnchor, 1,
PyDoc_STR("(CFStringRef bookname, CFStringRef anchor) -> None")},
{"AHRegisterHelpBook", (PyCFunction)Ah_AHRegisterHelpBook, 1,
PyDoc_STR("(FSRef appBundleRef) -> None")},
{NULL, NULL, 0}
};
@ -126,18 +126,18 @@ static PyMethodDef Ah_methods[] = {
void init_AH(void)
{
PyObject *m;
PyObject *d;
PyObject *m;
PyObject *d;
m = Py_InitModule("_AH", Ah_methods);
d = PyModule_GetDict(m);
Ah_Error = PyMac_GetOSErrException();
if (Ah_Error == NULL ||
PyDict_SetItemString(d, "Error", Ah_Error) != 0)
return;
m = Py_InitModule("_AH", Ah_methods);
d = PyModule_GetDict(m);
Ah_Error = PyMac_GetOSErrException();
if (Ah_Error == NULL ||
PyDict_SetItemString(d, "Error", Ah_Error) != 0)
return;
}
/* ========================= End module _AH ========================= */

File diff suppressed because it is too large Load diff

View file

@ -16,93 +16,93 @@ static PyObject *AutoGILError;
static void autoGILCallback(CFRunLoopObserverRef observer,
CFRunLoopActivity activity,
void *info) {
PyThreadState **p_tstate = (PyThreadState **)info;
CFRunLoopActivity activity,
void *info) {
PyThreadState **p_tstate = (PyThreadState **)info;
switch (activity) {
case kCFRunLoopBeforeWaiting:
/* going to sleep, release GIL */
switch (activity) {
case kCFRunLoopBeforeWaiting:
/* going to sleep, release GIL */
#ifdef AUTOGIL_DEBUG
fprintf(stderr, "going to sleep, release GIL\n");
fprintf(stderr, "going to sleep, release GIL\n");
#endif
*p_tstate = PyEval_SaveThread();
break;
case kCFRunLoopAfterWaiting:
/* waking up, acquire GIL */
*p_tstate = PyEval_SaveThread();
break;
case kCFRunLoopAfterWaiting:
/* waking up, acquire GIL */
#ifdef AUTOGIL_DEBUG
fprintf(stderr, "waking up, acquire GIL\n");
fprintf(stderr, "waking up, acquire GIL\n");
#endif
PyEval_RestoreThread(*p_tstate);
*p_tstate = NULL;
break;
default:
break;
}
PyEval_RestoreThread(*p_tstate);
*p_tstate = NULL;
break;
default:
break;
}
}
static void infoRelease(const void *info) {
/* XXX This should get called when the run loop is deallocated,
but this doesn't seem to happen. So for now: leak. */
PyMem_Free((void *)info);
/* XXX This should get called when the run loop is deallocated,
but this doesn't seem to happen. So for now: leak. */
PyMem_Free((void *)info);
}
static PyObject *
autoGIL_installAutoGIL(PyObject *self)
{
PyObject *tstate_dict = PyThreadState_GetDict();
PyObject *v;
CFRunLoopRef rl;
PyThreadState **p_tstate; /* for use in the info field */
CFRunLoopObserverContext context = {0, NULL, NULL, NULL, NULL};
CFRunLoopObserverRef observer;
PyObject *tstate_dict = PyThreadState_GetDict();
PyObject *v;
CFRunLoopRef rl;
PyThreadState **p_tstate; /* for use in the info field */
CFRunLoopObserverContext context = {0, NULL, NULL, NULL, NULL};
CFRunLoopObserverRef observer;
if (tstate_dict == NULL)
return NULL;
v = PyDict_GetItemString(tstate_dict, "autoGIL.InstalledAutoGIL");
if (v != NULL) {
/* we've already installed a callback for this thread */
Py_INCREF(Py_None);
return Py_None;
}
if (tstate_dict == NULL)
return NULL;
v = PyDict_GetItemString(tstate_dict, "autoGIL.InstalledAutoGIL");
if (v != NULL) {
/* we've already installed a callback for this thread */
Py_INCREF(Py_None);
return Py_None;
}
rl = CFRunLoopGetCurrent();
if (rl == NULL) {
PyErr_SetString(AutoGILError,
"can't get run loop for current thread");
return NULL;
}
rl = CFRunLoopGetCurrent();
if (rl == NULL) {
PyErr_SetString(AutoGILError,
"can't get run loop for current thread");
return NULL;
}
p_tstate = PyMem_Malloc(sizeof(PyThreadState *));
if (p_tstate == NULL) {
PyErr_SetString(PyExc_MemoryError,
"not enough memory to allocate "
"tstate pointer");
return NULL;
}
*p_tstate = NULL;
context.info = (void *)p_tstate;
context.release = infoRelease;
p_tstate = PyMem_Malloc(sizeof(PyThreadState *));
if (p_tstate == NULL) {
PyErr_SetString(PyExc_MemoryError,
"not enough memory to allocate "
"tstate pointer");
return NULL;
}
*p_tstate = NULL;
context.info = (void *)p_tstate;
context.release = infoRelease;
observer = CFRunLoopObserverCreate(
NULL,
kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting,
1, 0, autoGILCallback, &context);
if (observer == NULL) {
PyErr_SetString(AutoGILError,
"can't create event loop observer");
return NULL;
}
CFRunLoopAddObserver(rl, observer, kCFRunLoopDefaultMode);
/* XXX how to check for errors? */
observer = CFRunLoopObserverCreate(
NULL,
kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting,
1, 0, autoGILCallback, &context);
if (observer == NULL) {
PyErr_SetString(AutoGILError,
"can't create event loop observer");
return NULL;
}
CFRunLoopAddObserver(rl, observer, kCFRunLoopDefaultMode);
/* XXX how to check for errors? */
/* register that we have installed a callback for this thread */
if (PyDict_SetItemString(tstate_dict, "autoGIL.InstalledAutoGIL",
Py_None) < 0)
return NULL;
/* register that we have installed a callback for this thread */
if (PyDict_SetItemString(tstate_dict, "autoGIL.InstalledAutoGIL",
Py_None) < 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(autoGIL_installAutoGIL_doc,
@ -114,13 +114,13 @@ the event loop is idle."
);
static PyMethodDef autoGIL_methods[] = {
{
"installAutoGIL",
(PyCFunction)autoGIL_installAutoGIL,
METH_NOARGS,
autoGIL_installAutoGIL_doc
},
{ 0, 0, 0, 0 } /* sentinel */
{
"installAutoGIL",
(PyCFunction)autoGIL_installAutoGIL,
METH_NOARGS,
autoGIL_installAutoGIL_doc
},
{ 0, 0, 0, 0 } /* sentinel */
};
PyDoc_STRVAR(autoGIL_docs,
@ -132,21 +132,21 @@ when running an event loop."
PyMODINIT_FUNC
initautoGIL(void)
{
PyObject *mod;
PyObject *mod;
if (PyErr_WarnPy3k("In 3.x, the autoGIL module is removed.", 1) < 0)
return;
if (PyErr_WarnPy3k("In 3.x, the autoGIL module is removed.", 1) < 0)
return;
mod = Py_InitModule4("autoGIL", autoGIL_methods, autoGIL_docs,
NULL, PYTHON_API_VERSION);
if (mod == NULL)
return;
AutoGILError = PyErr_NewException("autoGIL.AutoGILError",
PyExc_Exception, NULL);
if (AutoGILError == NULL)
return;
Py_INCREF(AutoGILError);
if (PyModule_AddObject(mod, "AutoGILError",
AutoGILError) < 0)
return;
mod = Py_InitModule4("autoGIL", autoGIL_methods, autoGIL_docs,
NULL, PYTHON_API_VERSION);
if (mod == NULL)
return;
AutoGILError = PyErr_NewException("autoGIL.AutoGILError",
PyExc_Exception, NULL);
if (AutoGILError == NULL)
return;
Py_INCREF(AutoGILError);
if (PyModule_AddObject(mod, "AutoGILError",
AutoGILError) < 0)
return;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -15,128 +15,128 @@
PyObject *
PyCF_CF2Python(CFTypeRef src) {
CFTypeID typeid;
if( src == NULL ) {
Py_INCREF(Py_None);
return Py_None;
}
typeid = CFGetTypeID(src);
if (typeid == CFArrayGetTypeID())
return PyCF_CF2Python_sequence((CFArrayRef)src);
if (typeid == CFDictionaryGetTypeID())
return PyCF_CF2Python_mapping((CFDictionaryRef)src);
return PyCF_CF2Python_simple(src);
CFTypeID typeid;
if( src == NULL ) {
Py_INCREF(Py_None);
return Py_None;
}
typeid = CFGetTypeID(src);
if (typeid == CFArrayGetTypeID())
return PyCF_CF2Python_sequence((CFArrayRef)src);
if (typeid == CFDictionaryGetTypeID())
return PyCF_CF2Python_mapping((CFDictionaryRef)src);
return PyCF_CF2Python_simple(src);
}
PyObject *
PyCF_CF2Python_sequence(CFArrayRef src) {
int size = CFArrayGetCount(src);
PyObject *rv;
CFTypeRef item_cf;
PyObject *item_py = NULL;
int i;
if ( (rv=PyList_New(size)) == NULL )
return NULL;
for(i=0; i<size; i++) {
item_cf = CFArrayGetValueAtIndex(src, i);
if (item_cf == NULL ) goto err;
item_py = PyCF_CF2Python(item_cf);
if (item_py == NULL ) goto err;
if (PyList_SetItem(rv, i, item_py) < 0) goto err;
item_py = NULL;
}
return rv;
int size = CFArrayGetCount(src);
PyObject *rv;
CFTypeRef item_cf;
PyObject *item_py = NULL;
int i;
if ( (rv=PyList_New(size)) == NULL )
return NULL;
for(i=0; i<size; i++) {
item_cf = CFArrayGetValueAtIndex(src, i);
if (item_cf == NULL ) goto err;
item_py = PyCF_CF2Python(item_cf);
if (item_py == NULL ) goto err;
if (PyList_SetItem(rv, i, item_py) < 0) goto err;
item_py = NULL;
}
return rv;
err:
Py_XDECREF(item_py);
Py_DECREF(rv);
return NULL;
Py_XDECREF(item_py);
Py_DECREF(rv);
return NULL;
}
PyObject *
PyCF_CF2Python_mapping(CFTypeRef src) {
int size = CFDictionaryGetCount(src);
PyObject *rv = NULL;
CFTypeRef *allkeys = NULL, *allvalues = NULL;
CFTypeRef key_cf, value_cf;
PyObject *key_py = NULL, *value_py = NULL;
int i;
allkeys = malloc(size*sizeof(CFTypeRef *));
if (allkeys == NULL) {
PyErr_NoMemory();
goto err;
}
allvalues = malloc(size*sizeof(CFTypeRef *));
if (allvalues == NULL) {
PyErr_NoMemory();
goto err;
}
if ( (rv=PyDict_New()) == NULL ) goto err;
CFDictionaryGetKeysAndValues(src, allkeys, allvalues);
for(i=0; i<size; i++) {
key_cf = allkeys[i];
value_cf = allvalues[i];
key_py = PyCF_CF2Python(key_cf);
if (key_py == NULL ) goto err;
value_py = PyCF_CF2Python(value_cf);
if (value_py == NULL ) goto err;
if (PyDict_SetItem(rv, key_py, value_py) < 0) goto err;
key_py = NULL;
value_py = NULL;
}
return rv;
int size = CFDictionaryGetCount(src);
PyObject *rv = NULL;
CFTypeRef *allkeys = NULL, *allvalues = NULL;
CFTypeRef key_cf, value_cf;
PyObject *key_py = NULL, *value_py = NULL;
int i;
allkeys = malloc(size*sizeof(CFTypeRef *));
if (allkeys == NULL) {
PyErr_NoMemory();
goto err;
}
allvalues = malloc(size*sizeof(CFTypeRef *));
if (allvalues == NULL) {
PyErr_NoMemory();
goto err;
}
if ( (rv=PyDict_New()) == NULL ) goto err;
CFDictionaryGetKeysAndValues(src, allkeys, allvalues);
for(i=0; i<size; i++) {
key_cf = allkeys[i];
value_cf = allvalues[i];
key_py = PyCF_CF2Python(key_cf);
if (key_py == NULL ) goto err;
value_py = PyCF_CF2Python(value_cf);
if (value_py == NULL ) goto err;
if (PyDict_SetItem(rv, key_py, value_py) < 0) goto err;
key_py = NULL;
value_py = NULL;
}
return rv;
err:
Py_XDECREF(key_py);
Py_XDECREF(value_py);
Py_XDECREF(rv);
free(allkeys);
free(allvalues);
return NULL;
Py_XDECREF(key_py);
Py_XDECREF(value_py);
Py_XDECREF(rv);
free(allkeys);
free(allvalues);
return NULL;
}
PyObject *
PyCF_CF2Python_simple(CFTypeRef src) {
CFTypeID typeid;
typeid = CFGetTypeID(src);
if (typeid == CFStringGetTypeID())
return PyCF_CF2Python_string((CFStringRef)src);
if (typeid == CFBooleanGetTypeID())
return PyBool_FromLong((long)CFBooleanGetValue(src));
if (typeid == CFNumberGetTypeID()) {
if (CFNumberIsFloatType(src)) {
double d;
CFNumberGetValue(src, kCFNumberDoubleType, &d);
return PyFloat_FromDouble(d);
} else {
long l;
if (!CFNumberGetValue(src, kCFNumberLongType, &l))
/* XXXX Out of range! */;
return PyInt_FromLong(l);
}
}
/* XXXX Should return as CFTypeRef, really... */
PyMac_Error(resNotFound);
return NULL;
CFTypeID typeid;
typeid = CFGetTypeID(src);
if (typeid == CFStringGetTypeID())
return PyCF_CF2Python_string((CFStringRef)src);
if (typeid == CFBooleanGetTypeID())
return PyBool_FromLong((long)CFBooleanGetValue(src));
if (typeid == CFNumberGetTypeID()) {
if (CFNumberIsFloatType(src)) {
double d;
CFNumberGetValue(src, kCFNumberDoubleType, &d);
return PyFloat_FromDouble(d);
} else {
long l;
if (!CFNumberGetValue(src, kCFNumberLongType, &l))
/* XXXX Out of range! */;
return PyInt_FromLong(l);
}
}
/* XXXX Should return as CFTypeRef, really... */
PyMac_Error(resNotFound);
return NULL;
}
/* Unsure - Return unicode or 8 bit strings? */
PyObject *
PyCF_CF2Python_string(CFStringRef src) {
int size = CFStringGetLength(src)+1;
Py_UNICODE *data = malloc(size*sizeof(Py_UNICODE));
CFRange range;
PyObject *rv;
int size = CFStringGetLength(src)+1;
Py_UNICODE *data = malloc(size*sizeof(Py_UNICODE));
CFRange range;
PyObject *rv;
range.location = 0;
range.length = size;
if( data == NULL ) return PyErr_NoMemory();
CFStringGetCharacters(src, range, data);
rv = (PyObject *)PyUnicode_FromUnicode(data, size-1);
free(data);
return rv;
range.location = 0;
range.length = size;
if( data == NULL ) return PyErr_NoMemory();
CFStringGetCharacters(src, range, data);
rv = (PyObject *)PyUnicode_FromUnicode(data, size-1);
free(data);
return rv;
}
/* ---------------------------------------- */
@ -146,158 +146,158 @@ PyCF_CF2Python_string(CFStringRef src) {
int
PyCF_Python2CF(PyObject *src, CFTypeRef *dst) {
if (PyString_Check(src) || PyUnicode_Check(src))
return PyCF_Python2CF_simple(src, dst);
if (PySequence_Check(src))
return PyCF_Python2CF_sequence(src, (CFArrayRef *)dst);
if (PyMapping_Check(src))
return PyCF_Python2CF_mapping(src, (CFDictionaryRef *)dst);
return PyCF_Python2CF_simple(src, dst);
if (PyString_Check(src) || PyUnicode_Check(src))
return PyCF_Python2CF_simple(src, dst);
if (PySequence_Check(src))
return PyCF_Python2CF_sequence(src, (CFArrayRef *)dst);
if (PyMapping_Check(src))
return PyCF_Python2CF_mapping(src, (CFDictionaryRef *)dst);
return PyCF_Python2CF_simple(src, dst);
}
int
PyCF_Python2CF_sequence(PyObject *src, CFArrayRef *dst) {
CFMutableArrayRef rv = NULL;
CFTypeRef item_cf = NULL;
PyObject *item_py = NULL;
int size, i;
if( !PySequence_Check(src) ) {
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFArray",
src->ob_type->tp_name);
return 0;
}
size = PySequence_Size(src);
rv = CFArrayCreateMutable((CFAllocatorRef)NULL, size, &kCFTypeArrayCallBacks);
if (rv == NULL) {
PyMac_Error(resNotFound);
goto err;
}
CFMutableArrayRef rv = NULL;
CFTypeRef item_cf = NULL;
PyObject *item_py = NULL;
int size, i;
for( i=0; i<size; i++) {
item_py = PySequence_GetItem(src, i);
if (item_py == NULL) goto err;
if ( !PyCF_Python2CF(item_py, &item_cf)) goto err;
Py_DECREF(item_py);
CFArraySetValueAtIndex(rv, i, item_cf);
CFRelease(item_cf);
item_cf = NULL;
}
*dst = rv;
return 1;
if( !PySequence_Check(src) ) {
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFArray",
src->ob_type->tp_name);
return 0;
}
size = PySequence_Size(src);
rv = CFArrayCreateMutable((CFAllocatorRef)NULL, size, &kCFTypeArrayCallBacks);
if (rv == NULL) {
PyMac_Error(resNotFound);
goto err;
}
for( i=0; i<size; i++) {
item_py = PySequence_GetItem(src, i);
if (item_py == NULL) goto err;
if ( !PyCF_Python2CF(item_py, &item_cf)) goto err;
Py_DECREF(item_py);
CFArraySetValueAtIndex(rv, i, item_cf);
CFRelease(item_cf);
item_cf = NULL;
}
*dst = rv;
return 1;
err:
Py_XDECREF(item_py);
if (rv) CFRelease(rv);
if (item_cf) CFRelease(item_cf);
return 0;
Py_XDECREF(item_py);
if (rv) CFRelease(rv);
if (item_cf) CFRelease(item_cf);
return 0;
}
int
PyCF_Python2CF_mapping(PyObject *src, CFDictionaryRef *dst) {
CFMutableDictionaryRef rv = NULL;
PyObject *aslist = NULL;
CFTypeRef key_cf = NULL, value_cf = NULL;
PyObject *item_py = NULL, *key_py = NULL, *value_py = NULL;
int size, i;
if( !PyMapping_Check(src) ) {
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFDictionary",
src->ob_type->tp_name);
return 0;
}
size = PyMapping_Size(src);
rv = CFDictionaryCreateMutable((CFAllocatorRef)NULL, size,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (rv == NULL) {
PyMac_Error(resNotFound);
goto err;
}
if ( (aslist = PyMapping_Items(src)) == NULL ) goto err;
CFMutableDictionaryRef rv = NULL;
PyObject *aslist = NULL;
CFTypeRef key_cf = NULL, value_cf = NULL;
PyObject *item_py = NULL, *key_py = NULL, *value_py = NULL;
int size, i;
for( i=0; i<size; i++) {
item_py = PySequence_GetItem(aslist, i);
if (item_py == NULL) goto err;
if (!PyArg_ParseTuple(item_py, "OO", &key_py, &value_py)) goto err;
if ( !PyCF_Python2CF(key_py, &key_cf) ) goto err;
if ( !PyCF_Python2CF(value_py, &value_cf) ) goto err;
CFDictionaryAddValue(rv, key_cf, value_cf);
CFRelease(key_cf);
key_cf = NULL;
CFRelease(value_cf);
value_cf = NULL;
}
*dst = rv;
return 1;
if( !PyMapping_Check(src) ) {
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFDictionary",
src->ob_type->tp_name);
return 0;
}
size = PyMapping_Size(src);
rv = CFDictionaryCreateMutable((CFAllocatorRef)NULL, size,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (rv == NULL) {
PyMac_Error(resNotFound);
goto err;
}
if ( (aslist = PyMapping_Items(src)) == NULL ) goto err;
for( i=0; i<size; i++) {
item_py = PySequence_GetItem(aslist, i);
if (item_py == NULL) goto err;
if (!PyArg_ParseTuple(item_py, "OO", &key_py, &value_py)) goto err;
if ( !PyCF_Python2CF(key_py, &key_cf) ) goto err;
if ( !PyCF_Python2CF(value_py, &value_cf) ) goto err;
CFDictionaryAddValue(rv, key_cf, value_cf);
CFRelease(key_cf);
key_cf = NULL;
CFRelease(value_cf);
value_cf = NULL;
}
*dst = rv;
return 1;
err:
Py_XDECREF(item_py);
Py_XDECREF(aslist);
if (rv) CFRelease(rv);
if (key_cf) CFRelease(key_cf);
if (value_cf) CFRelease(value_cf);
return 0;
Py_XDECREF(item_py);
Py_XDECREF(aslist);
if (rv) CFRelease(rv);
if (key_cf) CFRelease(key_cf);
if (value_cf) CFRelease(value_cf);
return 0;
}
int
PyCF_Python2CF_simple(PyObject *src, CFTypeRef *dst) {
#if 0
if (PyObject_HasAttrString(src, "CFType")) {
*dst = PyObject_CallMethod(src, "CFType", "");
return (*dst != NULL);
}
if (PyObject_HasAttrString(src, "CFType")) {
*dst = PyObject_CallMethod(src, "CFType", "");
return (*dst != NULL);
}
#endif
if (PyString_Check(src) || PyUnicode_Check(src))
return PyCF_Python2CF_string(src, (CFStringRef *)dst);
if (PyBool_Check(src)) {
if (src == Py_True)
*dst = kCFBooleanTrue;
else
*dst = kCFBooleanFalse;
return 1;
}
if (PyInt_Check(src)) {
long v = PyInt_AsLong(src);
*dst = CFNumberCreate(NULL, kCFNumberLongType, &v);
return 1;
}
if (PyFloat_Check(src)) {
double d = PyFloat_AsDouble(src);
*dst = CFNumberCreate(NULL, kCFNumberDoubleType, &d);
return 1;
}
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFType",
src->ob_type->tp_name);
return 0;
if (PyString_Check(src) || PyUnicode_Check(src))
return PyCF_Python2CF_string(src, (CFStringRef *)dst);
if (PyBool_Check(src)) {
if (src == Py_True)
*dst = kCFBooleanTrue;
else
*dst = kCFBooleanFalse;
return 1;
}
if (PyInt_Check(src)) {
long v = PyInt_AsLong(src);
*dst = CFNumberCreate(NULL, kCFNumberLongType, &v);
return 1;
}
if (PyFloat_Check(src)) {
double d = PyFloat_AsDouble(src);
*dst = CFNumberCreate(NULL, kCFNumberDoubleType, &d);
return 1;
}
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFType",
src->ob_type->tp_name);
return 0;
}
int
PyCF_Python2CF_string(PyObject *src, CFStringRef *dst) {
char *chars;
CFIndex size;
UniChar *unichars;
if (PyString_Check(src)) {
if (!PyArg_Parse(src, "es", "ascii", &chars))
return 0; /* This error is more descriptive than the general one below */
*dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII);
PyMem_Free(chars);
return 1;
}
if (PyUnicode_Check(src)) {
/* We use the CF types here, if Python was configured differently that will give an error */
size = PyUnicode_GetSize(src);
if ((unichars = PyUnicode_AsUnicode(src)) == NULL ) goto err;
*dst = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
return 1;
}
char *chars;
CFIndex size;
UniChar *unichars;
if (PyString_Check(src)) {
if (!PyArg_Parse(src, "es", "ascii", &chars))
return 0; /* This error is more descriptive than the general one below */
*dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII);
PyMem_Free(chars);
return 1;
}
if (PyUnicode_Check(src)) {
/* We use the CF types here, if Python was configured differently that will give an error */
size = PyUnicode_GetSize(src);
if ((unichars = PyUnicode_AsUnicode(src)) == NULL ) goto err;
*dst = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
return 1;
}
err:
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFString",
src->ob_type->tp_name);
return 0;
PyErr_Format(PyExc_TypeError,
"Cannot convert %.500s objects to CFString",
src->ob_type->tp_name);
return 0;
}

File diff suppressed because it is too large Load diff

View file

@ -1,33 +1,33 @@
/*
File: CFMLateImport.h
File: CFMLateImport.h
Contains: Interface to CFM late import library.
Contains: Interface to CFM late import library.
Written by: Quinn
Written by: Quinn
Copyright: Copyright © 1999 by Apple Computer, Inc., all rights reserved.
Copyright: Copyright © 1999 by Apple Computer, Inc., all rights reserved.
You may incorporate this Apple sample source code into your program(s) without
restriction. This Apple sample source code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to redistribute
this Apple sample source code as "Apple sample source code" after having made
changes. If you're going to re-distribute the source, we require that you make
it clear in the source that the code was descended from Apple sample source
code, but that you've made changes.
You may incorporate this Apple sample source code into your program(s) without
restriction. This Apple sample source code has been provided "AS IS" and the
responsibility for its operation is yours. You are not permitted to redistribute
this Apple sample source code as "Apple sample source code" after having made
changes. If you're going to re-distribute the source, we require that you make
it clear in the source that the code was descended from Apple sample source
code, but that you've made changes.
Change History (most recent first):
Change History (most recent first):
<6> 21/9/01 Quinn Changes for CWPro7 Mach-O build.
<5> 19/9/01 Quinn Change comments to reflect the fact that an unpacked data
section is no longer required.
<4> 19/9/01 Quinn Simplified API and implementation after a suggestion by Eric
Grant. You no longer have to CFM export a dummy function; you
can just pass in the address of your fragment's init routine.
<3> 16/11/00 Quinn Allow symbol finding via a callback and use that to implement
CFBundle support.
<2> 18/10/99 Quinn Renamed CFMLateImport to CFMLateImportLibrary to allow for
possible future API expansion.
<1> 15/6/99 Quinn First checked in.
<6> 21/9/01 Quinn Changes for CWPro7 Mach-O build.
<5> 19/9/01 Quinn Change comments to reflect the fact that an unpacked data
section is no longer required.
<4> 19/9/01 Quinn Simplified API and implementation after a suggestion by Eric
Grant. You no longer have to CFM export a dummy function; you
can just pass in the address of your fragment's init routine.
<3> 16/11/00 Quinn Allow symbol finding via a callback and use that to implement
CFBundle support.
<2> 18/10/99 Quinn Renamed CFMLateImport to CFMLateImportLibrary to allow for
possible future API expansion.
<1> 15/6/99 Quinn First checked in.
*/
#pragma once
@ -41,10 +41,10 @@
// Mac OS Interfaces
#if ! MORE_FRAMEWORK_INCLUDES
#include <MacTypes.h>
#include <CodeFragments.h>
#include <Devices.h>
#include <CFBundle.h>
#include <MacTypes.h>
#include <CodeFragments.h>
#include <Devices.h>
#include <CFBundle.h>
#endif
/////////////////////////////////////////////////////////////////
@ -53,219 +53,219 @@
extern "C" {
#endif
/* FAQ
---
Q: What does this library do?
A: It allows you to resolve a weak linked library at runtime,
by supply a CFM connection to the library that should substitute
for the weak linked one.
Q: Does the substituted library have to have the same name as the
weak linked library.
A: No.
Q: What's this useful for?
A: The most obvious example of where this is useful is when
you rely on shared libraries that the user might delete
or move. To can find the shared library (possibly even
using CatSearch), call GetDiskFragment to open a connection
to it, late import it using this library, and then the
rest of your code can continue to use the shared library
as if nothing had happened. No more defining thousands
of stub routines which call through routine pointers.
There are, however, numerous less obvious uses. You can
use this code to make a 'self repairing' application. If
the user removes your shared library from the Extensions
folder, the startup code for your application can offer
tor re-install it. If the user agrees, you can then
re-install your shared library, late import it, and then
continue running your application if nothing happened.
You can even use this code to free yourself from the
Extensions folder entirely. Say you have a suite of
applications that currently installs a dozen shared
libraries in the Extensions folder. You can move those
libraries to another folder entirely and each application's
startup code can track down the library (using an alias
in the Preferences file) and late import it.
An even cooler use is to provide easy abstraction layers.
Say you have a network code for both the MacTCP
API and the Open Transport API. Typically, you would be
force to do this by having an abstraction layer where every
routine contains a switch between MacTCP and OT. Your
OpenSocket routine might look like:
/* FAQ
---
static int OpenSocket(void)
{
if (gOTAvailable) {
return OpenSocketOT();
} else {
return OpenSocketMacTCP();
}
}
With this code, you can avoid that entirely. Simply
weak link to a shared library that you know is never
going to be implemented ("crea;MySocketsDummy") and then,
at runtime, decide whether the system has MacTCP or OT
and late import the relevant real implementation
("crea;MySocketsMacTCP" or "crea;MySocketsOT").
One benefit of this approach is that only the MacTCP or
the OT code is resident in memory on any given system.
Q: What does this library do?
A: It allows you to resolve a weak linked library at runtime,
by supply a CFM connection to the library that should substitute
for the weak linked one.
Q: Does the substituted library have to have the same name as the
weak linked library.
A: No.
Q: What's this useful for?
A: The most obvious example of where this is useful is when
you rely on shared libraries that the user might delete
or move. To can find the shared library (possibly even
using CatSearch), call GetDiskFragment to open a connection
to it, late import it using this library, and then the
rest of your code can continue to use the shared library
as if nothing had happened. No more defining thousands
of stub routines which call through routine pointers.
There are, however, numerous less obvious uses. You can
use this code to make a 'self repairing' application. If
the user removes your shared library from the Extensions
folder, the startup code for your application can offer
tor re-install it. If the user agrees, you can then
re-install your shared library, late import it, and then
continue running your application if nothing happened.
You can even use this code to free yourself from the
Extensions folder entirely. Say you have a suite of
applications that currently installs a dozen shared
libraries in the Extensions folder. You can move those
libraries to another folder entirely and each application's
startup code can track down the library (using an alias
in the Preferences file) and late import it.
An even cooler use is to provide easy abstraction layers.
Say you have a network code for both the MacTCP
API and the Open Transport API. Typically, you would be
force to do this by having an abstraction layer where every
routine contains a switch between MacTCP and OT. Your
OpenSocket routine might look like:
static int OpenSocket(void)
{
if (gOTAvailable) {
return OpenSocketOT();
} else {
return OpenSocketMacTCP();
}
}
With this code, you can avoid that entirely. Simply
weak link to a shared library that you know is never
going to be implemented ("crea;MySocketsDummy") and then,
at runtime, decide whether the system has MacTCP or OT
and late import the relevant real implementation
("crea;MySocketsMacTCP" or "crea;MySocketsOT").
One benefit of this approach is that only the MacTCP or
the OT code is resident in memory on any given system.
*/
typedef pascal OSStatus (*CFMLateImportLookupProc)(ConstStr255Param symName, CFragSymbolClass symClass,
void **symAddr, void *refCon);
// CFMLateImportLookupProc defines a callback for CFMLateImportCore.
// The routine is expected to look up the address of the symbol named
// symName and return it in *symAddr. The symbol should be of class
// symClass, although the callback decides whether a class mismatch is
// an error. refCon is an application defined value that was originally
// passed in to CFMLateImportCore.
//
// If this routine returns an error, a symbol address of 0 is assumed.
// If the symbol is marked as a weak import, the CFMLateImportCore will
// continue, otherwise the CFMLateImportCore routine will fail with the
// error.
void **symAddr, void *refCon);
// CFMLateImportLookupProc defines a callback for CFMLateImportCore.
// The routine is expected to look up the address of the symbol named
// symName and return it in *symAddr. The symbol should be of class
// symClass, although the callback decides whether a class mismatch is
// an error. refCon is an application defined value that was originally
// passed in to CFMLateImportCore.
//
// If this routine returns an error, a symbol address of 0 is assumed.
// If the symbol is marked as a weak import, the CFMLateImportCore will
// continue, otherwise the CFMLateImportCore routine will fail with the
// error.
extern pascal OSStatus CFMLateImportCore(const CFragSystem7DiskFlatLocator *fragToFixLocator,
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFMLateImportLookupProc lookup,
void *refCon);
// This routine will link you, at runtime, to some library
// that you were weak linked to and wasn't present when your
// fragment was prepared. As well as the obvious functionality
// of being able to resolve weak links after prepare time,
// this functionality can be put to a number of less obvious uses,
// some of which are discussed at the top of this header file.
//
// To call this routine, you need a number of pieces of information:
//
// 1. fragToFixLocator, fragToFixConnID: The location of your own
// code fragment on disk and the CFM connection ID to your own
// code fragment. Typically you get this information from your
// fragment's CFM init routine. You must ensure that
// fragToFixLocator->fileSpec points to an FSSpec of the
// file which holds your code fragment.
//
// IMPORTANT:
// The fact that you pass in a CFragSystem7DiskFlatLocator as the
// fragToFixLocator implies that the fragment to be fixed up must
// be in the data fork of a file. The code could be modified
// to remove this requirement, but on disk code fragments are the most
// common case.
//
// IMPORTANT:
// The fragment to fix may have a packed data section. Packing the
// data section will reduce the size of your fragment on disk, but it
// will significantly increase the memory needed by this routine
// (it increases memory usage by the sum of the sizes of the packed
// and unpacked data section). See below for instructions on how to
// create an unpacked data section.
//
// 2. fragToFixInitRoutine: A pointer to your own code fragment's
// fragment initialiser routine. You necessarily have one of these
// because you need it to get values for the fragToFixLocator and
// fragToFixConnID parameters. Just pass its address in as a parameter
// as well.
//
// 3. weakLinkedLibraryName: The name of the weak linked library which
// failed to link. You must have weak linked to this library.
// It is oxymoric for you to pass a strong linked library here,
// because your code would not have prepared if a strong linked
// library failed to prepare, and so you couldn't supply a valid
/// fragToFix.
//
// 4. lookup, refCon: A pointer to a callback function that the
// routine calls to look up the address of a symbol, and a refCon
// for that callback routine.
//
// Note:
// The fragToFixLocator and fragToFixInitRoutine parameters
// are artifacts of the way in which this functionality is implemented.
// In an ideal world, where CFM exported decent introspection APIs
// to third party developers, these parameters would not be necessary.
// If you're using this code inside Apple, you probably should investigate
// using the CFM private APIs for getting at the information these
// parameters are needed for. See the comments inside the implementation
// for more details.
//
// Note:
// The extra memory taken when you use a packed data section is also an
// artifact of my workaround for the lack of CFM introspection APIs. In
// my opinion it's better to use an unpacked data section and consume more
// space on disk while saving memory. In CodeWarrior you can switch to an
// unpacked data section by checking the "Expand Uninitialized Data"
// checkbox in the "PPC PEF" settings panel. In MPW, specified the
// "-packdata off" option to PPCLink.
//
// When the routine returns, any symbols that you imported from the
// library named weakLinkedLibraryName will be resolved to the address
// of the symbol provided by the "lookup" callback routine.
//
// It is possible for an unresolved import to remain unresolved after
// this routine returns. If the symbol import is marked as weak (as
// opposed to the library, which *must* be marked as weak) and the symbol
// is not found by the "lookup" callback, the routine will simple skip
// that symbol. If the symbol isn't marked as weak, the routine will fail
// in that case.
//
// Most of the possible error results are co-opted CFM errors. These
// include:
//
// cfragFragmentFormatErr -- The fragment to fix is is an unknown format.
// cfragNoSectionErr -- Could not find the loader section in the fragment to fix.
// cfragNoLibraryErr -- The fragment to fix is not weak linked to weakLinkedLibraryName.
// cfragFragmentUsageErr -- The fragment to fix doesn't have a data section.
// -- The fragment to fix is strong linked to weakLinkedLibraryName.
// -- The fragment doesn't have an init routine.
// cfragFragmentCorruptErr -- Encountered an undefined relocation opcode.
// unimpErr -- Encountered an unimplement relocation opcode. The
// relocation engine only implements a subset of the CFM
// relocation opcodes, the subset most commonly used by
// MPW and CodeWarrior PEF containers. If you encounter
// this error, you'll probably have to add the weird
// relocation opcode to the engine, which shouldn't be
// be too hard.
// memFullErr -- It's likely that this error is triggered by the memory
// needed to unpack your data section. Either make your
// data section smaller, or unpack it (see above).
// errors returned by FindSymbol
// errors returned by Memory Manager
//
// The routine needs enough memory to hold the loader section of the fragment
// to fix in memory. It allocates that memory using NewPtr and dispsoses of
// it before it returns. You may want to change the memory allocator, which
// is very simple.
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFMLateImportLookupProc lookup,
void *refCon);
// This routine will link you, at runtime, to some library
// that you were weak linked to and wasn't present when your
// fragment was prepared. As well as the obvious functionality
// of being able to resolve weak links after prepare time,
// this functionality can be put to a number of less obvious uses,
// some of which are discussed at the top of this header file.
//
// To call this routine, you need a number of pieces of information:
//
// 1. fragToFixLocator, fragToFixConnID: The location of your own
// code fragment on disk and the CFM connection ID to your own
// code fragment. Typically you get this information from your
// fragment's CFM init routine. You must ensure that
// fragToFixLocator->fileSpec points to an FSSpec of the
// file which holds your code fragment.
//
// IMPORTANT:
// The fact that you pass in a CFragSystem7DiskFlatLocator as the
// fragToFixLocator implies that the fragment to be fixed up must
// be in the data fork of a file. The code could be modified
// to remove this requirement, but on disk code fragments are the most
// common case.
//
// IMPORTANT:
// The fragment to fix may have a packed data section. Packing the
// data section will reduce the size of your fragment on disk, but it
// will significantly increase the memory needed by this routine
// (it increases memory usage by the sum of the sizes of the packed
// and unpacked data section). See below for instructions on how to
// create an unpacked data section.
//
// 2. fragToFixInitRoutine: A pointer to your own code fragment's
// fragment initialiser routine. You necessarily have one of these
// because you need it to get values for the fragToFixLocator and
// fragToFixConnID parameters. Just pass its address in as a parameter
// as well.
//
// 3. weakLinkedLibraryName: The name of the weak linked library which
// failed to link. You must have weak linked to this library.
// It is oxymoric for you to pass a strong linked library here,
// because your code would not have prepared if a strong linked
// library failed to prepare, and so you couldn't supply a valid
/// fragToFix.
//
// 4. lookup, refCon: A pointer to a callback function that the
// routine calls to look up the address of a symbol, and a refCon
// for that callback routine.
//
// Note:
// The fragToFixLocator and fragToFixInitRoutine parameters
// are artifacts of the way in which this functionality is implemented.
// In an ideal world, where CFM exported decent introspection APIs
// to third party developers, these parameters would not be necessary.
// If you're using this code inside Apple, you probably should investigate
// using the CFM private APIs for getting at the information these
// parameters are needed for. See the comments inside the implementation
// for more details.
//
// Note:
// The extra memory taken when you use a packed data section is also an
// artifact of my workaround for the lack of CFM introspection APIs. In
// my opinion it's better to use an unpacked data section and consume more
// space on disk while saving memory. In CodeWarrior you can switch to an
// unpacked data section by checking the "Expand Uninitialized Data"
// checkbox in the "PPC PEF" settings panel. In MPW, specified the
// "-packdata off" option to PPCLink.
//
// When the routine returns, any symbols that you imported from the
// library named weakLinkedLibraryName will be resolved to the address
// of the symbol provided by the "lookup" callback routine.
//
// It is possible for an unresolved import to remain unresolved after
// this routine returns. If the symbol import is marked as weak (as
// opposed to the library, which *must* be marked as weak) and the symbol
// is not found by the "lookup" callback, the routine will simple skip
// that symbol. If the symbol isn't marked as weak, the routine will fail
// in that case.
//
// Most of the possible error results are co-opted CFM errors. These
// include:
//
// cfragFragmentFormatErr -- The fragment to fix is is an unknown format.
// cfragNoSectionErr -- Could not find the loader section in the fragment to fix.
// cfragNoLibraryErr -- The fragment to fix is not weak linked to weakLinkedLibraryName.
// cfragFragmentUsageErr -- The fragment to fix doesn't have a data section.
// -- The fragment to fix is strong linked to weakLinkedLibraryName.
// -- The fragment doesn't have an init routine.
// cfragFragmentCorruptErr -- Encountered an undefined relocation opcode.
// unimpErr -- Encountered an unimplement relocation opcode. The
// relocation engine only implements a subset of the CFM
// relocation opcodes, the subset most commonly used by
// MPW and CodeWarrior PEF containers. If you encounter
// this error, you'll probably have to add the weird
// relocation opcode to the engine, which shouldn't be
// be too hard.
// memFullErr -- It's likely that this error is triggered by the memory
// needed to unpack your data section. Either make your
// data section smaller, or unpack it (see above).
// errors returned by FindSymbol
// errors returned by Memory Manager
//
// The routine needs enough memory to hold the loader section of the fragment
// to fix in memory. It allocates that memory using NewPtr and dispsoses of
// it before it returns. You may want to change the memory allocator, which
// is very simple.
extern pascal OSStatus CFMLateImportLibrary(const CFragSystem7DiskFlatLocator *fragToFixLocator,
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFragConnectionID connIDToImport);
// A wrapper around CFMLateImportCore that looks up symbols by calling
// FindSymbol on a connection to a CFM library (connIDToImport).
// You can get this connection ID through any standard CFM API, for example
// GetSharedLibrary, GetDiskFragment, or GetMemFragment.
//
// IMPORTANT:
// The fragment name for connIDToImport *does not* have to match
// weakLinkedLibraryName. This is part of the power of this library.
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFragConnectionID connIDToImport);
// A wrapper around CFMLateImportCore that looks up symbols by calling
// FindSymbol on a connection to a CFM library (connIDToImport).
// You can get this connection ID through any standard CFM API, for example
// GetSharedLibrary, GetDiskFragment, or GetMemFragment.
//
// IMPORTANT:
// The fragment name for connIDToImport *does not* have to match
// weakLinkedLibraryName. This is part of the power of this library.
extern pascal OSStatus CFMLateImportBundle(const CFragSystem7DiskFlatLocator *fragToFixLocator,
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFBundleRef bundleToImport);
// A wrapper around CFMLateImportCore that looks up symbols by calling
// CFBundleGetFunctionPointerForName on a reference to a Core Foundation
// bundle (bundleToImport). You can get this reference through any
// Core Foundation bundle API, for example CFBundleCreate.
CFragConnectionID fragToFixConnID,
CFragInitFunction fragToFixInitRoutine,
ConstStr255Param weakLinkedLibraryName,
CFBundleRef bundleToImport);
// A wrapper around CFMLateImportCore that looks up symbols by calling
// CFBundleGetFunctionPointerForName on a reference to a Core Foundation
// bundle (bundleToImport). You can get this reference through any
// Core Foundation bundle API, for example CFBundleCreate.
#ifdef __cplusplus
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -23,535 +23,535 @@ static PyObject *Evt_Error;
static PyObject *Evt_GetMouse(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Point mouseLoc;
PyObject *_res = NULL;
Point mouseLoc;
#ifndef GetMouse
PyMac_PRECHECK(GetMouse);
PyMac_PRECHECK(GetMouse);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetMouse(&mouseLoc);
_res = Py_BuildValue("O&",
PyMac_BuildPoint, mouseLoc);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetMouse(&mouseLoc);
_res = Py_BuildValue("O&",
PyMac_BuildPoint, mouseLoc);
return _res;
}
static PyObject *Evt_Button(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef Button
PyMac_PRECHECK(Button);
PyMac_PRECHECK(Button);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = Button();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = Button();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_StillDown(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef StillDown
PyMac_PRECHECK(StillDown);
PyMac_PRECHECK(StillDown);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = StillDown();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = StillDown();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_WaitMouseUp(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef WaitMouseUp
PyMac_PRECHECK(WaitMouseUp);
PyMac_PRECHECK(WaitMouseUp);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = WaitMouseUp();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = WaitMouseUp();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_GetCaretTime(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt32 _rv;
PyObject *_res = NULL;
UInt32 _rv;
#ifndef GetCaretTime
PyMac_PRECHECK(GetCaretTime);
PyMac_PRECHECK(GetCaretTime);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetCaretTime();
_res = Py_BuildValue("l",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetCaretTime();
_res = Py_BuildValue("l",
_rv);
return _res;
}
static PyObject *Evt_GetKeys(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
KeyMap theKeys__out__;
PyObject *_res = NULL;
KeyMap theKeys__out__;
#ifndef GetKeys
PyMac_PRECHECK(GetKeys);
PyMac_PRECHECK(GetKeys);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetKeys(theKeys__out__);
_res = Py_BuildValue("s#",
(char *)&theKeys__out__, (int)sizeof(KeyMap));
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetKeys(theKeys__out__);
_res = Py_BuildValue("s#",
(char *)&theKeys__out__, (int)sizeof(KeyMap));
return _res;
}
static PyObject *Evt_GetDblTime(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt32 _rv;
PyObject *_res = NULL;
UInt32 _rv;
#ifndef GetDblTime
PyMac_PRECHECK(GetDblTime);
PyMac_PRECHECK(GetDblTime);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetDblTime();
_res = Py_BuildValue("l",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetDblTime();
_res = Py_BuildValue("l",
_rv);
return _res;
}
static PyObject *Evt_SetEventMask(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
EventMask value;
PyObject *_res = NULL;
EventMask value;
#ifndef SetEventMask
PyMac_PRECHECK(SetEventMask);
PyMac_PRECHECK(SetEventMask);
#endif
if (!PyArg_ParseTuple(_args, "H",
&value))
return NULL;
SetEventMask(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "H",
&value))
return NULL;
SetEventMask(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_GetNextEvent(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
PyObject *_res = NULL;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
#ifndef GetNextEvent
PyMac_PRECHECK(GetNextEvent);
PyMac_PRECHECK(GetNextEvent);
#endif
if (!PyArg_ParseTuple(_args, "H",
&eventMask))
return NULL;
_rv = GetNextEvent(eventMask,
&theEvent);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
if (!PyArg_ParseTuple(_args, "H",
&eventMask))
return NULL;
_rv = GetNextEvent(eventMask,
&theEvent);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
}
static PyObject *Evt_EventAvail(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
PyObject *_res = NULL;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
#ifndef EventAvail
PyMac_PRECHECK(EventAvail);
PyMac_PRECHECK(EventAvail);
#endif
if (!PyArg_ParseTuple(_args, "H",
&eventMask))
return NULL;
_rv = EventAvail(eventMask,
&theEvent);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
if (!PyArg_ParseTuple(_args, "H",
&eventMask))
return NULL;
_rv = EventAvail(eventMask,
&theEvent);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
}
static PyObject *Evt_PostEvent(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
EventKind eventNum;
UInt32 eventMsg;
PyObject *_res = NULL;
OSErr _err;
EventKind eventNum;
UInt32 eventMsg;
#ifndef PostEvent
PyMac_PRECHECK(PostEvent);
PyMac_PRECHECK(PostEvent);
#endif
if (!PyArg_ParseTuple(_args, "Hl",
&eventNum,
&eventMsg))
return NULL;
_err = PostEvent(eventNum,
eventMsg);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "Hl",
&eventNum,
&eventMsg))
return NULL;
_err = PostEvent(eventNum,
eventMsg);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_FlushEvents(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
EventMask whichMask;
EventMask stopMask;
PyObject *_res = NULL;
EventMask whichMask;
EventMask stopMask;
#ifndef FlushEvents
PyMac_PRECHECK(FlushEvents);
PyMac_PRECHECK(FlushEvents);
#endif
if (!PyArg_ParseTuple(_args, "HH",
&whichMask,
&stopMask))
return NULL;
FlushEvents(whichMask,
stopMask);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "HH",
&whichMask,
&stopMask))
return NULL;
FlushEvents(whichMask,
stopMask);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_GetGlobalMouse(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Point globalMouse;
PyObject *_res = NULL;
Point globalMouse;
#ifndef GetGlobalMouse
PyMac_PRECHECK(GetGlobalMouse);
PyMac_PRECHECK(GetGlobalMouse);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetGlobalMouse(&globalMouse);
_res = Py_BuildValue("O&",
PyMac_BuildPoint, globalMouse);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
GetGlobalMouse(&globalMouse);
_res = Py_BuildValue("O&",
PyMac_BuildPoint, globalMouse);
return _res;
}
static PyObject *Evt_GetCurrentKeyModifiers(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt32 _rv;
PyObject *_res = NULL;
UInt32 _rv;
#ifndef GetCurrentKeyModifiers
PyMac_PRECHECK(GetCurrentKeyModifiers);
PyMac_PRECHECK(GetCurrentKeyModifiers);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetCurrentKeyModifiers();
_res = Py_BuildValue("l",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetCurrentKeyModifiers();
_res = Py_BuildValue("l",
_rv);
return _res;
}
static PyObject *Evt_CheckEventQueueForUserCancel(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef CheckEventQueueForUserCancel
PyMac_PRECHECK(CheckEventQueueForUserCancel);
PyMac_PRECHECK(CheckEventQueueForUserCancel);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = CheckEventQueueForUserCancel();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = CheckEventQueueForUserCancel();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_KeyScript(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
short code;
PyObject *_res = NULL;
short code;
#ifndef KeyScript
PyMac_PRECHECK(KeyScript);
PyMac_PRECHECK(KeyScript);
#endif
if (!PyArg_ParseTuple(_args, "h",
&code))
return NULL;
KeyScript(code);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "h",
&code))
return NULL;
KeyScript(code);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_IsCmdChar(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
EventRecord event;
short test;
PyObject *_res = NULL;
Boolean _rv;
EventRecord event;
short test;
#ifndef IsCmdChar
PyMac_PRECHECK(IsCmdChar);
PyMac_PRECHECK(IsCmdChar);
#endif
if (!PyArg_ParseTuple(_args, "O&h",
PyMac_GetEventRecord, &event,
&test))
return NULL;
_rv = IsCmdChar(&event,
test);
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, "O&h",
PyMac_GetEventRecord, &event,
&test))
return NULL;
_rv = IsCmdChar(&event,
test);
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_LMGetKeyThresh(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
SInt16 _rv;
PyObject *_res = NULL;
SInt16 _rv;
#ifndef LMGetKeyThresh
PyMac_PRECHECK(LMGetKeyThresh);
PyMac_PRECHECK(LMGetKeyThresh);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKeyThresh();
_res = Py_BuildValue("h",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKeyThresh();
_res = Py_BuildValue("h",
_rv);
return _res;
}
static PyObject *Evt_LMSetKeyThresh(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
SInt16 value;
PyObject *_res = NULL;
SInt16 value;
#ifndef LMSetKeyThresh
PyMac_PRECHECK(LMSetKeyThresh);
PyMac_PRECHECK(LMSetKeyThresh);
#endif
if (!PyArg_ParseTuple(_args, "h",
&value))
return NULL;
LMSetKeyThresh(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "h",
&value))
return NULL;
LMSetKeyThresh(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_LMGetKeyRepThresh(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
SInt16 _rv;
PyObject *_res = NULL;
SInt16 _rv;
#ifndef LMGetKeyRepThresh
PyMac_PRECHECK(LMGetKeyRepThresh);
PyMac_PRECHECK(LMGetKeyRepThresh);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKeyRepThresh();
_res = Py_BuildValue("h",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKeyRepThresh();
_res = Py_BuildValue("h",
_rv);
return _res;
}
static PyObject *Evt_LMSetKeyRepThresh(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
SInt16 value;
PyObject *_res = NULL;
SInt16 value;
#ifndef LMSetKeyRepThresh
PyMac_PRECHECK(LMSetKeyRepThresh);
PyMac_PRECHECK(LMSetKeyRepThresh);
#endif
if (!PyArg_ParseTuple(_args, "h",
&value))
return NULL;
LMSetKeyRepThresh(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "h",
&value))
return NULL;
LMSetKeyRepThresh(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_LMGetKbdLast(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt8 _rv;
PyObject *_res = NULL;
UInt8 _rv;
#ifndef LMGetKbdLast
PyMac_PRECHECK(LMGetKbdLast);
PyMac_PRECHECK(LMGetKbdLast);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKbdLast();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKbdLast();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_LMSetKbdLast(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt8 value;
PyObject *_res = NULL;
UInt8 value;
#ifndef LMSetKbdLast
PyMac_PRECHECK(LMSetKbdLast);
PyMac_PRECHECK(LMSetKbdLast);
#endif
if (!PyArg_ParseTuple(_args, "b",
&value))
return NULL;
LMSetKbdLast(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&value))
return NULL;
LMSetKbdLast(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_LMGetKbdType(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt8 _rv;
PyObject *_res = NULL;
UInt8 _rv;
#ifndef LMGetKbdType
PyMac_PRECHECK(LMGetKbdType);
PyMac_PRECHECK(LMGetKbdType);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKbdType();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = LMGetKbdType();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Evt_LMSetKbdType(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt8 value;
PyObject *_res = NULL;
UInt8 value;
#ifndef LMSetKbdType
PyMac_PRECHECK(LMSetKbdType);
PyMac_PRECHECK(LMSetKbdType);
#endif
if (!PyArg_ParseTuple(_args, "b",
&value))
return NULL;
LMSetKbdType(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&value))
return NULL;
LMSetKbdType(value);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Evt_TickCount(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
UInt32 _rv;
PyObject *_res = NULL;
UInt32 _rv;
#ifndef TickCount
PyMac_PRECHECK(TickCount);
PyMac_PRECHECK(TickCount);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = TickCount();
_res = Py_BuildValue("l",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = TickCount();
_res = Py_BuildValue("l",
_rv);
return _res;
}
static PyObject *Evt_WaitNextEvent(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
PyObject *_res = NULL;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
UInt32 sleep;
Handle mouseregion = (Handle)0;
Boolean _rv;
EventMask eventMask;
EventRecord theEvent;
UInt32 sleep;
Handle mouseregion = (Handle)0;
if (!PyArg_ParseTuple(_args, "Hl|O&",
&eventMask,
&sleep,
OptResObj_Convert, &mouseregion))
return NULL;
_rv = WaitNextEvent(eventMask,
&theEvent,
sleep,
(RgnHandle)mouseregion);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
if (!PyArg_ParseTuple(_args, "Hl|O&",
&eventMask,
&sleep,
OptResObj_Convert, &mouseregion))
return NULL;
_rv = WaitNextEvent(eventMask,
&theEvent,
sleep,
(RgnHandle)mouseregion);
_res = Py_BuildValue("bO&",
_rv,
PyMac_BuildEventRecord, &theEvent);
return _res;
}
static PyMethodDef Evt_methods[] = {
{"GetMouse", (PyCFunction)Evt_GetMouse, 1,
PyDoc_STR("() -> (Point mouseLoc)")},
{"Button", (PyCFunction)Evt_Button, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"StillDown", (PyCFunction)Evt_StillDown, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"WaitMouseUp", (PyCFunction)Evt_WaitMouseUp, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"GetCaretTime", (PyCFunction)Evt_GetCaretTime, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"GetKeys", (PyCFunction)Evt_GetKeys, 1,
PyDoc_STR("() -> (KeyMap theKeys)")},
{"GetDblTime", (PyCFunction)Evt_GetDblTime, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"SetEventMask", (PyCFunction)Evt_SetEventMask, 1,
PyDoc_STR("(EventMask value) -> None")},
{"GetNextEvent", (PyCFunction)Evt_GetNextEvent, 1,
PyDoc_STR("(EventMask eventMask) -> (Boolean _rv, EventRecord theEvent)")},
{"EventAvail", (PyCFunction)Evt_EventAvail, 1,
PyDoc_STR("(EventMask eventMask) -> (Boolean _rv, EventRecord theEvent)")},
{"PostEvent", (PyCFunction)Evt_PostEvent, 1,
PyDoc_STR("(EventKind eventNum, UInt32 eventMsg) -> None")},
{"FlushEvents", (PyCFunction)Evt_FlushEvents, 1,
PyDoc_STR("(EventMask whichMask, EventMask stopMask) -> None")},
{"GetGlobalMouse", (PyCFunction)Evt_GetGlobalMouse, 1,
PyDoc_STR("() -> (Point globalMouse)")},
{"GetCurrentKeyModifiers", (PyCFunction)Evt_GetCurrentKeyModifiers, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"CheckEventQueueForUserCancel", (PyCFunction)Evt_CheckEventQueueForUserCancel, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"KeyScript", (PyCFunction)Evt_KeyScript, 1,
PyDoc_STR("(short code) -> None")},
{"IsCmdChar", (PyCFunction)Evt_IsCmdChar, 1,
PyDoc_STR("(EventRecord event, short test) -> (Boolean _rv)")},
{"LMGetKeyThresh", (PyCFunction)Evt_LMGetKeyThresh, 1,
PyDoc_STR("() -> (SInt16 _rv)")},
{"LMSetKeyThresh", (PyCFunction)Evt_LMSetKeyThresh, 1,
PyDoc_STR("(SInt16 value) -> None")},
{"LMGetKeyRepThresh", (PyCFunction)Evt_LMGetKeyRepThresh, 1,
PyDoc_STR("() -> (SInt16 _rv)")},
{"LMSetKeyRepThresh", (PyCFunction)Evt_LMSetKeyRepThresh, 1,
PyDoc_STR("(SInt16 value) -> None")},
{"LMGetKbdLast", (PyCFunction)Evt_LMGetKbdLast, 1,
PyDoc_STR("() -> (UInt8 _rv)")},
{"LMSetKbdLast", (PyCFunction)Evt_LMSetKbdLast, 1,
PyDoc_STR("(UInt8 value) -> None")},
{"LMGetKbdType", (PyCFunction)Evt_LMGetKbdType, 1,
PyDoc_STR("() -> (UInt8 _rv)")},
{"LMSetKbdType", (PyCFunction)Evt_LMSetKbdType, 1,
PyDoc_STR("(UInt8 value) -> None")},
{"TickCount", (PyCFunction)Evt_TickCount, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"WaitNextEvent", (PyCFunction)Evt_WaitNextEvent, 1,
PyDoc_STR("(EventMask eventMask, UInt32 sleep [,RegionHandle]) -> (Boolean _rv, EventRecord theEvent)")},
{NULL, NULL, 0}
{"GetMouse", (PyCFunction)Evt_GetMouse, 1,
PyDoc_STR("() -> (Point mouseLoc)")},
{"Button", (PyCFunction)Evt_Button, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"StillDown", (PyCFunction)Evt_StillDown, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"WaitMouseUp", (PyCFunction)Evt_WaitMouseUp, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"GetCaretTime", (PyCFunction)Evt_GetCaretTime, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"GetKeys", (PyCFunction)Evt_GetKeys, 1,
PyDoc_STR("() -> (KeyMap theKeys)")},
{"GetDblTime", (PyCFunction)Evt_GetDblTime, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"SetEventMask", (PyCFunction)Evt_SetEventMask, 1,
PyDoc_STR("(EventMask value) -> None")},
{"GetNextEvent", (PyCFunction)Evt_GetNextEvent, 1,
PyDoc_STR("(EventMask eventMask) -> (Boolean _rv, EventRecord theEvent)")},
{"EventAvail", (PyCFunction)Evt_EventAvail, 1,
PyDoc_STR("(EventMask eventMask) -> (Boolean _rv, EventRecord theEvent)")},
{"PostEvent", (PyCFunction)Evt_PostEvent, 1,
PyDoc_STR("(EventKind eventNum, UInt32 eventMsg) -> None")},
{"FlushEvents", (PyCFunction)Evt_FlushEvents, 1,
PyDoc_STR("(EventMask whichMask, EventMask stopMask) -> None")},
{"GetGlobalMouse", (PyCFunction)Evt_GetGlobalMouse, 1,
PyDoc_STR("() -> (Point globalMouse)")},
{"GetCurrentKeyModifiers", (PyCFunction)Evt_GetCurrentKeyModifiers, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"CheckEventQueueForUserCancel", (PyCFunction)Evt_CheckEventQueueForUserCancel, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"KeyScript", (PyCFunction)Evt_KeyScript, 1,
PyDoc_STR("(short code) -> None")},
{"IsCmdChar", (PyCFunction)Evt_IsCmdChar, 1,
PyDoc_STR("(EventRecord event, short test) -> (Boolean _rv)")},
{"LMGetKeyThresh", (PyCFunction)Evt_LMGetKeyThresh, 1,
PyDoc_STR("() -> (SInt16 _rv)")},
{"LMSetKeyThresh", (PyCFunction)Evt_LMSetKeyThresh, 1,
PyDoc_STR("(SInt16 value) -> None")},
{"LMGetKeyRepThresh", (PyCFunction)Evt_LMGetKeyRepThresh, 1,
PyDoc_STR("() -> (SInt16 _rv)")},
{"LMSetKeyRepThresh", (PyCFunction)Evt_LMSetKeyRepThresh, 1,
PyDoc_STR("(SInt16 value) -> None")},
{"LMGetKbdLast", (PyCFunction)Evt_LMGetKbdLast, 1,
PyDoc_STR("() -> (UInt8 _rv)")},
{"LMSetKbdLast", (PyCFunction)Evt_LMSetKbdLast, 1,
PyDoc_STR("(UInt8 value) -> None")},
{"LMGetKbdType", (PyCFunction)Evt_LMGetKbdType, 1,
PyDoc_STR("() -> (UInt8 _rv)")},
{"LMSetKbdType", (PyCFunction)Evt_LMSetKbdType, 1,
PyDoc_STR("(UInt8 value) -> None")},
{"TickCount", (PyCFunction)Evt_TickCount, 1,
PyDoc_STR("() -> (UInt32 _rv)")},
{"WaitNextEvent", (PyCFunction)Evt_WaitNextEvent, 1,
PyDoc_STR("(EventMask eventMask, UInt32 sleep [,RegionHandle]) -> (Boolean _rv, EventRecord theEvent)")},
{NULL, NULL, 0}
};
#else /* __LP64__ */
static PyMethodDef Evt_methods[] = {
{NULL, NULL, 0}
{NULL, NULL, 0}
};
#endif /* __LP64__ */
void init_Evt(void)
{
PyObject *m;
PyObject *m;
#ifndef __LP64__
PyObject *d;
PyObject *d;
#endif /* __LP64__ */
m = Py_InitModule("_Evt", Evt_methods);
m = Py_InitModule("_Evt", Evt_methods);
#ifndef __LP64__
d = PyModule_GetDict(m);
Evt_Error = PyMac_GetOSErrException();
if (Evt_Error == NULL ||
PyDict_SetItemString(d, "Error", Evt_Error) != 0)
return;
d = PyModule_GetDict(m);
Evt_Error = PyMac_GetOSErrException();
if (Evt_Error == NULL ||
PyDict_SetItemString(d, "Error", Evt_Error) != 0)
return;
#endif /* __LP64__ */
}

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -26,12 +26,12 @@ static PyObject *
FMRec_New(FMetricRec *itself)
{
return Py_BuildValue("O&O&O&O&O&",
PyMac_BuildFixed, itself->ascent,
PyMac_BuildFixed, itself->descent,
PyMac_BuildFixed, itself->leading,
PyMac_BuildFixed, itself->widMax,
ResObj_New, itself->wTabHandle);
return Py_BuildValue("O&O&O&O&O&",
PyMac_BuildFixed, itself->ascent,
PyMac_BuildFixed, itself->descent,
PyMac_BuildFixed, itself->leading,
PyMac_BuildFixed, itself->widMax,
ResObj_New, itself->wTabHandle);
}
#if 0
@ -39,12 +39,12 @@ FMRec_New(FMetricRec *itself)
static int
FMRec_Convert(PyObject *v, FMetricRec *p_itself)
{
return PyArg_ParseTuple(v, "O&O&O&O&O&",
PyMac_GetFixed, &itself->ascent,
PyMac_GetFixed, &itself->descent,
PyMac_GetFixed, &itself->leading,
PyMac_GetFixed, &itself->widMax,
ResObj_Convert, &itself->wTabHandle);
return PyArg_ParseTuple(v, "O&O&O&O&O&",
PyMac_GetFixed, &itself->ascent,
PyMac_GetFixed, &itself->descent,
PyMac_GetFixed, &itself->leading,
PyMac_GetFixed, &itself->widMax,
ResObj_Convert, &itself->wTabHandle);
}
#endif
@ -53,314 +53,314 @@ static PyObject *Fm_Error;
static PyObject *Fm_GetFontName(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
short familyID;
Str255 name;
PyObject *_res = NULL;
short familyID;
Str255 name;
#ifndef GetFontName
PyMac_PRECHECK(GetFontName);
PyMac_PRECHECK(GetFontName);
#endif
if (!PyArg_ParseTuple(_args, "h",
&familyID))
return NULL;
GetFontName(familyID,
name);
_res = Py_BuildValue("O&",
PyMac_BuildStr255, name);
return _res;
if (!PyArg_ParseTuple(_args, "h",
&familyID))
return NULL;
GetFontName(familyID,
name);
_res = Py_BuildValue("O&",
PyMac_BuildStr255, name);
return _res;
}
static PyObject *Fm_GetFNum(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Str255 name;
short familyID;
PyObject *_res = NULL;
Str255 name;
short familyID;
#ifndef GetFNum
PyMac_PRECHECK(GetFNum);
PyMac_PRECHECK(GetFNum);
#endif
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetStr255, name))
return NULL;
GetFNum(name,
&familyID);
_res = Py_BuildValue("h",
familyID);
return _res;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetStr255, name))
return NULL;
GetFNum(name,
&familyID);
_res = Py_BuildValue("h",
familyID);
return _res;
}
static PyObject *Fm_RealFont(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
short fontNum;
short size;
PyObject *_res = NULL;
Boolean _rv;
short fontNum;
short size;
#ifndef RealFont
PyMac_PRECHECK(RealFont);
PyMac_PRECHECK(RealFont);
#endif
if (!PyArg_ParseTuple(_args, "hh",
&fontNum,
&size))
return NULL;
_rv = RealFont(fontNum,
size);
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, "hh",
&fontNum,
&size))
return NULL;
_rv = RealFont(fontNum,
size);
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Fm_SetFScaleDisable(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean fscaleDisable;
PyObject *_res = NULL;
Boolean fscaleDisable;
#ifndef SetFScaleDisable
PyMac_PRECHECK(SetFScaleDisable);
PyMac_PRECHECK(SetFScaleDisable);
#endif
if (!PyArg_ParseTuple(_args, "b",
&fscaleDisable))
return NULL;
SetFScaleDisable(fscaleDisable);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&fscaleDisable))
return NULL;
SetFScaleDisable(fscaleDisable);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Fm_FontMetrics(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
FMetricRec theMetrics;
PyObject *_res = NULL;
FMetricRec theMetrics;
#ifndef FontMetrics
PyMac_PRECHECK(FontMetrics);
PyMac_PRECHECK(FontMetrics);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
FontMetrics(&theMetrics);
_res = Py_BuildValue("O&",
FMRec_New, &theMetrics);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
FontMetrics(&theMetrics);
_res = Py_BuildValue("O&",
FMRec_New, &theMetrics);
return _res;
}
static PyObject *Fm_SetFractEnable(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean fractEnable;
PyObject *_res = NULL;
Boolean fractEnable;
#ifndef SetFractEnable
PyMac_PRECHECK(SetFractEnable);
PyMac_PRECHECK(SetFractEnable);
#endif
if (!PyArg_ParseTuple(_args, "b",
&fractEnable))
return NULL;
SetFractEnable(fractEnable);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&fractEnable))
return NULL;
SetFractEnable(fractEnable);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Fm_GetDefFontSize(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
short _rv;
PyObject *_res = NULL;
short _rv;
#ifndef GetDefFontSize
PyMac_PRECHECK(GetDefFontSize);
PyMac_PRECHECK(GetDefFontSize);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetDefFontSize();
_res = Py_BuildValue("h",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetDefFontSize();
_res = Py_BuildValue("h",
_rv);
return _res;
}
static PyObject *Fm_IsOutline(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
Point numer;
Point denom;
PyObject *_res = NULL;
Boolean _rv;
Point numer;
Point denom;
#ifndef IsOutline
PyMac_PRECHECK(IsOutline);
PyMac_PRECHECK(IsOutline);
#endif
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetPoint, &numer,
PyMac_GetPoint, &denom))
return NULL;
_rv = IsOutline(numer,
denom);
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetPoint, &numer,
PyMac_GetPoint, &denom))
return NULL;
_rv = IsOutline(numer,
denom);
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Fm_SetOutlinePreferred(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean outlinePreferred;
PyObject *_res = NULL;
Boolean outlinePreferred;
#ifndef SetOutlinePreferred
PyMac_PRECHECK(SetOutlinePreferred);
PyMac_PRECHECK(SetOutlinePreferred);
#endif
if (!PyArg_ParseTuple(_args, "b",
&outlinePreferred))
return NULL;
SetOutlinePreferred(outlinePreferred);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&outlinePreferred))
return NULL;
SetOutlinePreferred(outlinePreferred);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Fm_GetOutlinePreferred(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef GetOutlinePreferred
PyMac_PRECHECK(GetOutlinePreferred);
PyMac_PRECHECK(GetOutlinePreferred);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetOutlinePreferred();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetOutlinePreferred();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Fm_SetPreserveGlyph(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean preserveGlyph;
PyObject *_res = NULL;
Boolean preserveGlyph;
#ifndef SetPreserveGlyph
PyMac_PRECHECK(SetPreserveGlyph);
PyMac_PRECHECK(SetPreserveGlyph);
#endif
if (!PyArg_ParseTuple(_args, "b",
&preserveGlyph))
return NULL;
SetPreserveGlyph(preserveGlyph);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
if (!PyArg_ParseTuple(_args, "b",
&preserveGlyph))
return NULL;
SetPreserveGlyph(preserveGlyph);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Fm_GetPreserveGlyph(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
PyObject *_res = NULL;
Boolean _rv;
#ifndef GetPreserveGlyph
PyMac_PRECHECK(GetPreserveGlyph);
PyMac_PRECHECK(GetPreserveGlyph);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetPreserveGlyph();
_res = Py_BuildValue("b",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetPreserveGlyph();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Fm_GetSysFont(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
short _rv;
PyObject *_res = NULL;
short _rv;
#ifndef GetSysFont
PyMac_PRECHECK(GetSysFont);
PyMac_PRECHECK(GetSysFont);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetSysFont();
_res = Py_BuildValue("h",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetSysFont();
_res = Py_BuildValue("h",
_rv);
return _res;
}
static PyObject *Fm_GetAppFont(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
short _rv;
PyObject *_res = NULL;
short _rv;
#ifndef GetAppFont
PyMac_PRECHECK(GetAppFont);
PyMac_PRECHECK(GetAppFont);
#endif
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetAppFont();
_res = Py_BuildValue("h",
_rv);
return _res;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = GetAppFont();
_res = Py_BuildValue("h",
_rv);
return _res;
}
static PyObject *Fm_QDTextBounds(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
char *inText__in__;
int inText__len__;
int inText__in_len__;
Rect bounds;
PyObject *_res = NULL;
char *inText__in__;
int inText__len__;
int inText__in_len__;
Rect bounds;
#ifndef QDTextBounds
PyMac_PRECHECK(QDTextBounds);
PyMac_PRECHECK(QDTextBounds);
#endif
if (!PyArg_ParseTuple(_args, "s#",
&inText__in__, &inText__in_len__))
return NULL;
inText__len__ = inText__in_len__;
QDTextBounds(inText__len__, inText__in__,
&bounds);
_res = Py_BuildValue("O&",
PyMac_BuildRect, &bounds);
return _res;
if (!PyArg_ParseTuple(_args, "s#",
&inText__in__, &inText__in_len__))
return NULL;
inText__len__ = inText__in_len__;
QDTextBounds(inText__len__, inText__in__,
&bounds);
_res = Py_BuildValue("O&",
PyMac_BuildRect, &bounds);
return _res;
}
static PyMethodDef Fm_methods[] = {
{"GetFontName", (PyCFunction)Fm_GetFontName, 1,
PyDoc_STR("(short familyID) -> (Str255 name)")},
{"GetFNum", (PyCFunction)Fm_GetFNum, 1,
PyDoc_STR("(Str255 name) -> (short familyID)")},
{"RealFont", (PyCFunction)Fm_RealFont, 1,
PyDoc_STR("(short fontNum, short size) -> (Boolean _rv)")},
{"SetFScaleDisable", (PyCFunction)Fm_SetFScaleDisable, 1,
PyDoc_STR("(Boolean fscaleDisable) -> None")},
{"FontMetrics", (PyCFunction)Fm_FontMetrics, 1,
PyDoc_STR("() -> (FMetricRec theMetrics)")},
{"SetFractEnable", (PyCFunction)Fm_SetFractEnable, 1,
PyDoc_STR("(Boolean fractEnable) -> None")},
{"GetDefFontSize", (PyCFunction)Fm_GetDefFontSize, 1,
PyDoc_STR("() -> (short _rv)")},
{"IsOutline", (PyCFunction)Fm_IsOutline, 1,
PyDoc_STR("(Point numer, Point denom) -> (Boolean _rv)")},
{"SetOutlinePreferred", (PyCFunction)Fm_SetOutlinePreferred, 1,
PyDoc_STR("(Boolean outlinePreferred) -> None")},
{"GetOutlinePreferred", (PyCFunction)Fm_GetOutlinePreferred, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"SetPreserveGlyph", (PyCFunction)Fm_SetPreserveGlyph, 1,
PyDoc_STR("(Boolean preserveGlyph) -> None")},
{"GetPreserveGlyph", (PyCFunction)Fm_GetPreserveGlyph, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"GetSysFont", (PyCFunction)Fm_GetSysFont, 1,
PyDoc_STR("() -> (short _rv)")},
{"GetAppFont", (PyCFunction)Fm_GetAppFont, 1,
PyDoc_STR("() -> (short _rv)")},
{"QDTextBounds", (PyCFunction)Fm_QDTextBounds, 1,
PyDoc_STR("(Buffer inText) -> (Rect bounds)")},
{NULL, NULL, 0}
{"GetFontName", (PyCFunction)Fm_GetFontName, 1,
PyDoc_STR("(short familyID) -> (Str255 name)")},
{"GetFNum", (PyCFunction)Fm_GetFNum, 1,
PyDoc_STR("(Str255 name) -> (short familyID)")},
{"RealFont", (PyCFunction)Fm_RealFont, 1,
PyDoc_STR("(short fontNum, short size) -> (Boolean _rv)")},
{"SetFScaleDisable", (PyCFunction)Fm_SetFScaleDisable, 1,
PyDoc_STR("(Boolean fscaleDisable) -> None")},
{"FontMetrics", (PyCFunction)Fm_FontMetrics, 1,
PyDoc_STR("() -> (FMetricRec theMetrics)")},
{"SetFractEnable", (PyCFunction)Fm_SetFractEnable, 1,
PyDoc_STR("(Boolean fractEnable) -> None")},
{"GetDefFontSize", (PyCFunction)Fm_GetDefFontSize, 1,
PyDoc_STR("() -> (short _rv)")},
{"IsOutline", (PyCFunction)Fm_IsOutline, 1,
PyDoc_STR("(Point numer, Point denom) -> (Boolean _rv)")},
{"SetOutlinePreferred", (PyCFunction)Fm_SetOutlinePreferred, 1,
PyDoc_STR("(Boolean outlinePreferred) -> None")},
{"GetOutlinePreferred", (PyCFunction)Fm_GetOutlinePreferred, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"SetPreserveGlyph", (PyCFunction)Fm_SetPreserveGlyph, 1,
PyDoc_STR("(Boolean preserveGlyph) -> None")},
{"GetPreserveGlyph", (PyCFunction)Fm_GetPreserveGlyph, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"GetSysFont", (PyCFunction)Fm_GetSysFont, 1,
PyDoc_STR("() -> (short _rv)")},
{"GetAppFont", (PyCFunction)Fm_GetAppFont, 1,
PyDoc_STR("() -> (short _rv)")},
{"QDTextBounds", (PyCFunction)Fm_QDTextBounds, 1,
PyDoc_STR("(Buffer inText) -> (Rect bounds)")},
{NULL, NULL, 0}
};
#else /* __LP64__ */
static PyMethodDef Fm_methods[] = {
{NULL, NULL, 0}
{NULL, NULL, 0}
};
#endif /* __LP64__ */
void init_Fm(void)
{
PyObject *m;
PyObject *m;
#ifndef __LP64__
PyObject *d;
PyObject *d;
#endif /* __LP64__ */
m = Py_InitModule("_Fm", Fm_methods);
m = Py_InitModule("_Fm", Fm_methods);
#ifndef __LP64__
d = PyModule_GetDict(m);
Fm_Error = PyMac_GetOSErrException();
if (Fm_Error == NULL ||
PyDict_SetItemString(d, "Error", Fm_Error) != 0)
return;
d = PyModule_GetDict(m);
Fm_Error = PyMac_GetOSErrException();
if (Fm_Error == NULL ||
PyDict_SetItemString(d, "Error", Fm_Error) != 0)
return;
#endif /* __LP64__ */
}

View file

@ -9,9 +9,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -22,301 +22,301 @@ static PyObject *Folder_Error;
static PyObject *Folder_FindFolder(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
Boolean createFolder;
FSVolumeRefNum foundVRefNum;
SInt32 foundDirID;
if (!PyArg_ParseTuple(_args, "hO&b",
&vRefNum,
PyMac_GetOSType, &folderType,
&createFolder))
return NULL;
_err = FindFolder(vRefNum,
folderType,
createFolder,
&foundVRefNum,
&foundDirID);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("hl",
foundVRefNum,
foundDirID);
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
Boolean createFolder;
FSVolumeRefNum foundVRefNum;
SInt32 foundDirID;
if (!PyArg_ParseTuple(_args, "hO&b",
&vRefNum,
PyMac_GetOSType, &folderType,
&createFolder))
return NULL;
_err = FindFolder(vRefNum,
folderType,
createFolder,
&foundVRefNum,
&foundDirID);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("hl",
foundVRefNum,
foundDirID);
return _res;
}
static PyObject *Folder_ReleaseFolder(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
if (!PyArg_ParseTuple(_args, "hO&",
&vRefNum,
PyMac_GetOSType, &folderType))
return NULL;
_err = ReleaseFolder(vRefNum,
folderType);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
if (!PyArg_ParseTuple(_args, "hO&",
&vRefNum,
PyMac_GetOSType, &folderType))
return NULL;
_err = ReleaseFolder(vRefNum,
folderType);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Folder_FSFindFolder(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
Boolean createFolder;
FSRef foundRef;
if (!PyArg_ParseTuple(_args, "hO&b",
&vRefNum,
PyMac_GetOSType, &folderType,
&createFolder))
return NULL;
_err = FSFindFolder(vRefNum,
folderType,
createFolder,
&foundRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildFSRef, &foundRef);
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType folderType;
Boolean createFolder;
FSRef foundRef;
if (!PyArg_ParseTuple(_args, "hO&b",
&vRefNum,
PyMac_GetOSType, &folderType,
&createFolder))
return NULL;
_err = FSFindFolder(vRefNum,
folderType,
createFolder,
&foundRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildFSRef, &foundRef);
return _res;
}
static PyObject *Folder_AddFolderDescriptor(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
FolderType foldType;
FolderDescFlags flags;
FolderClass foldClass;
FolderLocation foldLocation;
OSType badgeSignature;
OSType badgeType;
Str255 name;
Boolean replaceFlag;
if (!PyArg_ParseTuple(_args, "O&lO&O&O&O&O&b",
PyMac_GetOSType, &foldType,
&flags,
PyMac_GetOSType, &foldClass,
PyMac_GetOSType, &foldLocation,
PyMac_GetOSType, &badgeSignature,
PyMac_GetOSType, &badgeType,
PyMac_GetStr255, name,
&replaceFlag))
return NULL;
_err = AddFolderDescriptor(foldType,
flags,
foldClass,
foldLocation,
badgeSignature,
badgeType,
name,
replaceFlag);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
FolderType foldType;
FolderDescFlags flags;
FolderClass foldClass;
FolderLocation foldLocation;
OSType badgeSignature;
OSType badgeType;
Str255 name;
Boolean replaceFlag;
if (!PyArg_ParseTuple(_args, "O&lO&O&O&O&O&b",
PyMac_GetOSType, &foldType,
&flags,
PyMac_GetOSType, &foldClass,
PyMac_GetOSType, &foldLocation,
PyMac_GetOSType, &badgeSignature,
PyMac_GetOSType, &badgeType,
PyMac_GetStr255, name,
&replaceFlag))
return NULL;
_err = AddFolderDescriptor(foldType,
flags,
foldClass,
foldLocation,
badgeSignature,
badgeType,
name,
replaceFlag);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Folder_GetFolderTypes(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
UInt32 requestedTypeCount;
UInt32 totalTypeCount;
FolderType theTypes;
if (!PyArg_ParseTuple(_args, "l",
&requestedTypeCount))
return NULL;
_err = GetFolderTypes(requestedTypeCount,
&totalTypeCount,
&theTypes);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("lO&",
totalTypeCount,
PyMac_BuildOSType, theTypes);
return _res;
PyObject *_res = NULL;
OSErr _err;
UInt32 requestedTypeCount;
UInt32 totalTypeCount;
FolderType theTypes;
if (!PyArg_ParseTuple(_args, "l",
&requestedTypeCount))
return NULL;
_err = GetFolderTypes(requestedTypeCount,
&totalTypeCount,
&theTypes);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("lO&",
totalTypeCount,
PyMac_BuildOSType, theTypes);
return _res;
}
static PyObject *Folder_RemoveFolderDescriptor(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
FolderType foldType;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &foldType))
return NULL;
_err = RemoveFolderDescriptor(foldType);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
FolderType foldType;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &foldType))
return NULL;
_err = RemoveFolderDescriptor(foldType);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
#ifndef __LP64__
static PyObject *Folder_GetFolderName(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType foldType;
short foundVRefNum;
Str255 name;
if (!PyArg_ParseTuple(_args, "hO&O&",
&vRefNum,
PyMac_GetOSType, &foldType,
PyMac_GetStr255, name))
return NULL;
_err = GetFolderName(vRefNum,
foldType,
&foundVRefNum,
name);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("h",
foundVRefNum);
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
OSType foldType;
short foundVRefNum;
Str255 name;
if (!PyArg_ParseTuple(_args, "hO&O&",
&vRefNum,
PyMac_GetOSType, &foldType,
PyMac_GetStr255, name))
return NULL;
_err = GetFolderName(vRefNum,
foldType,
&foundVRefNum,
name);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("h",
foundVRefNum);
return _res;
}
static PyObject *Folder_AddFolderRouting(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
FolderType routeToFolder;
RoutingFlags flags;
Boolean replaceFlag;
if (!PyArg_ParseTuple(_args, "O&O&O&lb",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder,
PyMac_GetOSType, &routeToFolder,
&flags,
&replaceFlag))
return NULL;
_err = AddFolderRouting(fileType,
routeFromFolder,
routeToFolder,
flags,
replaceFlag);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
FolderType routeToFolder;
RoutingFlags flags;
Boolean replaceFlag;
if (!PyArg_ParseTuple(_args, "O&O&O&lb",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder,
PyMac_GetOSType, &routeToFolder,
&flags,
&replaceFlag))
return NULL;
_err = AddFolderRouting(fileType,
routeFromFolder,
routeToFolder,
flags,
replaceFlag);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Folder_RemoveFolderRouting(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder))
return NULL;
_err = RemoveFolderRouting(fileType,
routeFromFolder);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder))
return NULL;
_err = RemoveFolderRouting(fileType,
routeFromFolder);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Folder_FindFolderRouting(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
FolderType routeToFolder;
RoutingFlags flags;
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder))
return NULL;
_err = FindFolderRouting(fileType,
routeFromFolder,
&routeToFolder,
&flags);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&l",
PyMac_BuildOSType, routeToFolder,
flags);
return _res;
PyObject *_res = NULL;
OSErr _err;
OSType fileType;
FolderType routeFromFolder;
FolderType routeToFolder;
RoutingFlags flags;
if (!PyArg_ParseTuple(_args, "O&O&",
PyMac_GetOSType, &fileType,
PyMac_GetOSType, &routeFromFolder))
return NULL;
_err = FindFolderRouting(fileType,
routeFromFolder,
&routeToFolder,
&flags);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&l",
PyMac_BuildOSType, routeToFolder,
flags);
return _res;
}
#endif /* !__LP64__ */
static PyObject *Folder_InvalidateFolderDescriptorCache(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
long dirID;
if (!PyArg_ParseTuple(_args, "hl",
&vRefNum,
&dirID))
return NULL;
_err = InvalidateFolderDescriptorCache(vRefNum,
dirID);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
long dirID;
if (!PyArg_ParseTuple(_args, "hl",
&vRefNum,
&dirID))
return NULL;
_err = InvalidateFolderDescriptorCache(vRefNum,
dirID);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Folder_IdentifyFolder(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
long dirID;
FolderType foldType;
if (!PyArg_ParseTuple(_args, "hl",
&vRefNum,
&dirID))
return NULL;
_err = IdentifyFolder(vRefNum,
dirID,
&foldType);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildOSType, foldType);
return _res;
PyObject *_res = NULL;
OSErr _err;
short vRefNum;
long dirID;
FolderType foldType;
if (!PyArg_ParseTuple(_args, "hl",
&vRefNum,
&dirID))
return NULL;
_err = IdentifyFolder(vRefNum,
dirID,
&foldType);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildOSType, foldType);
return _res;
}
static PyMethodDef Folder_methods[] = {
{"FindFolder", (PyCFunction)Folder_FindFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (short foundVRefNum, long foundDirID)")},
{"ReleaseFolder", (PyCFunction)Folder_ReleaseFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType) -> None")},
{"FSFindFolder", (PyCFunction)Folder_FSFindFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (FSRef foundRef)")},
{"AddFolderDescriptor", (PyCFunction)Folder_AddFolderDescriptor, 1,
PyDoc_STR("(FolderType foldType, FolderDescFlags flags, FolderClass foldClass, FolderLocation foldLocation, OSType badgeSignature, OSType badgeType, Str255 name, Boolean replaceFlag) -> None")},
{"GetFolderTypes", (PyCFunction)Folder_GetFolderTypes, 1,
PyDoc_STR("(UInt32 requestedTypeCount) -> (UInt32 totalTypeCount, FolderType theTypes)")},
{"RemoveFolderDescriptor", (PyCFunction)Folder_RemoveFolderDescriptor, 1,
PyDoc_STR("(FolderType foldType) -> None")},
{"FindFolder", (PyCFunction)Folder_FindFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (short foundVRefNum, long foundDirID)")},
{"ReleaseFolder", (PyCFunction)Folder_ReleaseFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType) -> None")},
{"FSFindFolder", (PyCFunction)Folder_FSFindFolder, 1,
PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (FSRef foundRef)")},
{"AddFolderDescriptor", (PyCFunction)Folder_AddFolderDescriptor, 1,
PyDoc_STR("(FolderType foldType, FolderDescFlags flags, FolderClass foldClass, FolderLocation foldLocation, OSType badgeSignature, OSType badgeType, Str255 name, Boolean replaceFlag) -> None")},
{"GetFolderTypes", (PyCFunction)Folder_GetFolderTypes, 1,
PyDoc_STR("(UInt32 requestedTypeCount) -> (UInt32 totalTypeCount, FolderType theTypes)")},
{"RemoveFolderDescriptor", (PyCFunction)Folder_RemoveFolderDescriptor, 1,
PyDoc_STR("(FolderType foldType) -> None")},
#ifndef __LP64__
{"GetFolderName", (PyCFunction)Folder_GetFolderName, 1,
PyDoc_STR("(short vRefNum, OSType foldType, Str255 name) -> (short foundVRefNum)")},
{"AddFolderRouting", (PyCFunction)Folder_AddFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder, FolderType routeToFolder, RoutingFlags flags, Boolean replaceFlag) -> None")},
{"RemoveFolderRouting", (PyCFunction)Folder_RemoveFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> None")},
{"FindFolderRouting", (PyCFunction)Folder_FindFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> (FolderType routeToFolder, RoutingFlags flags)")},
{"GetFolderName", (PyCFunction)Folder_GetFolderName, 1,
PyDoc_STR("(short vRefNum, OSType foldType, Str255 name) -> (short foundVRefNum)")},
{"AddFolderRouting", (PyCFunction)Folder_AddFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder, FolderType routeToFolder, RoutingFlags flags, Boolean replaceFlag) -> None")},
{"RemoveFolderRouting", (PyCFunction)Folder_RemoveFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> None")},
{"FindFolderRouting", (PyCFunction)Folder_FindFolderRouting, 1,
PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> (FolderType routeToFolder, RoutingFlags flags)")},
#endif /* !__LP64__ */
{"InvalidateFolderDescriptorCache", (PyCFunction)Folder_InvalidateFolderDescriptorCache, 1,
PyDoc_STR("(short vRefNum, long dirID) -> None")},
{"IdentifyFolder", (PyCFunction)Folder_IdentifyFolder, 1,
PyDoc_STR("(short vRefNum, long dirID) -> (FolderType foldType)")},
{NULL, NULL, 0}
{"InvalidateFolderDescriptorCache", (PyCFunction)Folder_InvalidateFolderDescriptorCache, 1,
PyDoc_STR("(short vRefNum, long dirID) -> None")},
{"IdentifyFolder", (PyCFunction)Folder_IdentifyFolder, 1,
PyDoc_STR("(short vRefNum, long dirID) -> (FolderType foldType)")},
{NULL, NULL, 0}
};
@ -324,18 +324,18 @@ static PyMethodDef Folder_methods[] = {
void init_Folder(void)
{
PyObject *m;
PyObject *d;
PyObject *m;
PyObject *d;
m = Py_InitModule("_Folder", Folder_methods);
d = PyModule_GetDict(m);
Folder_Error = PyMac_GetOSErrException();
if (Folder_Error == NULL ||
PyDict_SetItemString(d, "Error", Folder_Error) != 0)
return;
m = Py_InitModule("_Folder", Folder_methods);
d = PyModule_GetDict(m);
Folder_Error = PyMac_GetOSErrException();
if (Folder_Error == NULL ||
PyDict_SetItemString(d, "Error", Folder_Error) != 0)
return;
}
/* ======================= End module _Folder ======================= */

View file

@ -4,10 +4,10 @@ The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
@ -32,24 +32,24 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
static PyObject *
gestalt_gestalt(PyObject *self, PyObject *args)
{
OSErr iErr;
OSType selector;
SInt32 response;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetOSType, &selector))
return NULL;
iErr = Gestalt ( selector, &response );
if (iErr != 0)
return PyMac_Error(iErr);
return PyInt_FromLong(response);
OSErr iErr;
OSType selector;
SInt32 response;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetOSType, &selector))
return NULL;
iErr = Gestalt ( selector, &response );
if (iErr != 0)
return PyMac_Error(iErr);
return PyInt_FromLong(response);
}
static struct PyMethodDef gestalt_methods[] = {
{"gestalt", gestalt_gestalt, METH_VARARGS},
{NULL, NULL} /* Sentinel */
{"gestalt", gestalt_gestalt, METH_VARARGS},
{NULL, NULL} /* Sentinel */
};
void
initgestalt(void)
{
Py_InitModule("gestalt", gestalt_methods);
Py_InitModule("gestalt", gestalt_methods);
}

View file

@ -10,9 +10,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -22,151 +22,151 @@ static PyObject *Help_Error;
static PyObject *Help_HMGetHelpMenu(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
MenuRef outHelpMenu;
MenuItemIndex outFirstCustomItemIndex;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMGetHelpMenu(&outHelpMenu,
&outFirstCustomItemIndex);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&H",
MenuObj_New, outHelpMenu,
outFirstCustomItemIndex);
return _res;
PyObject *_res = NULL;
OSStatus _err;
MenuRef outHelpMenu;
MenuItemIndex outFirstCustomItemIndex;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMGetHelpMenu(&outHelpMenu,
&outFirstCustomItemIndex);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&H",
MenuObj_New, outHelpMenu,
outFirstCustomItemIndex);
return _res;
}
static PyObject *Help_HMAreHelpTagsDisplayed(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
Boolean _rv;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = HMAreHelpTagsDisplayed();
_res = Py_BuildValue("b",
_rv);
return _res;
PyObject *_res = NULL;
Boolean _rv;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_rv = HMAreHelpTagsDisplayed();
_res = Py_BuildValue("b",
_rv);
return _res;
}
static PyObject *Help_HMSetHelpTagsDisplayed(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
Boolean inDisplayTags;
if (!PyArg_ParseTuple(_args, "b",
&inDisplayTags))
return NULL;
_err = HMSetHelpTagsDisplayed(inDisplayTags);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
Boolean inDisplayTags;
if (!PyArg_ParseTuple(_args, "b",
&inDisplayTags))
return NULL;
_err = HMSetHelpTagsDisplayed(inDisplayTags);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Help_HMSetTagDelay(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
Duration inDelay;
if (!PyArg_ParseTuple(_args, "l",
&inDelay))
return NULL;
_err = HMSetTagDelay(inDelay);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
Duration inDelay;
if (!PyArg_ParseTuple(_args, "l",
&inDelay))
return NULL;
_err = HMSetTagDelay(inDelay);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Help_HMGetTagDelay(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
Duration outDelay;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMGetTagDelay(&outDelay);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
outDelay);
return _res;
PyObject *_res = NULL;
OSStatus _err;
Duration outDelay;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMGetTagDelay(&outDelay);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
outDelay);
return _res;
}
static PyObject *Help_HMSetMenuHelpFromBalloonRsrc(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
MenuRef inMenu;
SInt16 inHmnuRsrcID;
if (!PyArg_ParseTuple(_args, "O&h",
MenuObj_Convert, &inMenu,
&inHmnuRsrcID))
return NULL;
_err = HMSetMenuHelpFromBalloonRsrc(inMenu,
inHmnuRsrcID);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
MenuRef inMenu;
SInt16 inHmnuRsrcID;
if (!PyArg_ParseTuple(_args, "O&h",
MenuObj_Convert, &inMenu,
&inHmnuRsrcID))
return NULL;
_err = HMSetMenuHelpFromBalloonRsrc(inMenu,
inHmnuRsrcID);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Help_HMSetDialogHelpFromBalloonRsrc(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
DialogPtr inDialog;
SInt16 inHdlgRsrcID;
SInt16 inItemStart;
if (!PyArg_ParseTuple(_args, "O&hh",
DlgObj_Convert, &inDialog,
&inHdlgRsrcID,
&inItemStart))
return NULL;
_err = HMSetDialogHelpFromBalloonRsrc(inDialog,
inHdlgRsrcID,
inItemStart);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
DialogPtr inDialog;
SInt16 inHdlgRsrcID;
SInt16 inItemStart;
if (!PyArg_ParseTuple(_args, "O&hh",
DlgObj_Convert, &inDialog,
&inHdlgRsrcID,
&inItemStart))
return NULL;
_err = HMSetDialogHelpFromBalloonRsrc(inDialog,
inHdlgRsrcID,
inItemStart);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Help_HMHideTag(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMHideTag();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = HMHideTag();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
#endif /* __LP64__ */
static PyMethodDef Help_methods[] = {
#ifndef __LP64__
{"HMGetHelpMenu", (PyCFunction)Help_HMGetHelpMenu, 1,
PyDoc_STR("() -> (MenuRef outHelpMenu, MenuItemIndex outFirstCustomItemIndex)")},
{"HMAreHelpTagsDisplayed", (PyCFunction)Help_HMAreHelpTagsDisplayed, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"HMSetHelpTagsDisplayed", (PyCFunction)Help_HMSetHelpTagsDisplayed, 1,
PyDoc_STR("(Boolean inDisplayTags) -> None")},
{"HMSetTagDelay", (PyCFunction)Help_HMSetTagDelay, 1,
PyDoc_STR("(Duration inDelay) -> None")},
{"HMGetTagDelay", (PyCFunction)Help_HMGetTagDelay, 1,
PyDoc_STR("() -> (Duration outDelay)")},
{"HMSetMenuHelpFromBalloonRsrc", (PyCFunction)Help_HMSetMenuHelpFromBalloonRsrc, 1,
PyDoc_STR("(MenuRef inMenu, SInt16 inHmnuRsrcID) -> None")},
{"HMSetDialogHelpFromBalloonRsrc", (PyCFunction)Help_HMSetDialogHelpFromBalloonRsrc, 1,
PyDoc_STR("(DialogPtr inDialog, SInt16 inHdlgRsrcID, SInt16 inItemStart) -> None")},
{"HMHideTag", (PyCFunction)Help_HMHideTag, 1,
PyDoc_STR("() -> None")},
{"HMGetHelpMenu", (PyCFunction)Help_HMGetHelpMenu, 1,
PyDoc_STR("() -> (MenuRef outHelpMenu, MenuItemIndex outFirstCustomItemIndex)")},
{"HMAreHelpTagsDisplayed", (PyCFunction)Help_HMAreHelpTagsDisplayed, 1,
PyDoc_STR("() -> (Boolean _rv)")},
{"HMSetHelpTagsDisplayed", (PyCFunction)Help_HMSetHelpTagsDisplayed, 1,
PyDoc_STR("(Boolean inDisplayTags) -> None")},
{"HMSetTagDelay", (PyCFunction)Help_HMSetTagDelay, 1,
PyDoc_STR("(Duration inDelay) -> None")},
{"HMGetTagDelay", (PyCFunction)Help_HMGetTagDelay, 1,
PyDoc_STR("() -> (Duration outDelay)")},
{"HMSetMenuHelpFromBalloonRsrc", (PyCFunction)Help_HMSetMenuHelpFromBalloonRsrc, 1,
PyDoc_STR("(MenuRef inMenu, SInt16 inHmnuRsrcID) -> None")},
{"HMSetDialogHelpFromBalloonRsrc", (PyCFunction)Help_HMSetDialogHelpFromBalloonRsrc, 1,
PyDoc_STR("(DialogPtr inDialog, SInt16 inHdlgRsrcID, SInt16 inItemStart) -> None")},
{"HMHideTag", (PyCFunction)Help_HMHideTag, 1,
PyDoc_STR("() -> None")},
#endif /* __LP64__ */
{NULL, NULL, 0}
{NULL, NULL, 0}
};
@ -174,21 +174,21 @@ static PyMethodDef Help_methods[] = {
void init_Help(void)
{
PyObject *m;
PyObject *m;
#ifndef __LP64__
PyObject *d;
PyObject *d;
#endif /* __LP64__ */
m = Py_InitModule("_Help", Help_methods);
m = Py_InitModule("_Help", Help_methods);
#ifndef __LP64__
d = PyModule_GetDict(m);
Help_Error = PyMac_GetOSErrException();
if (Help_Error == NULL ||
PyDict_SetItemString(d, "Error", Help_Error) != 0)
return;
d = PyModule_GetDict(m);
Help_Error = PyMac_GetOSErrException();
if (Help_Error == NULL ||
PyDict_SetItemString(d, "Error", Help_Error) != 0)
return;
#endif /* __LP64__ */
}

View file

@ -23,116 +23,116 @@ PyTypeObject IBNibRef_Type;
#define IBNibRefObj_Check(x) ((x)->ob_type == &IBNibRef_Type || PyObject_TypeCheck((x), &IBNibRef_Type))
typedef struct IBNibRefObject {
PyObject_HEAD
IBNibRef ob_itself;
PyObject_HEAD
IBNibRef ob_itself;
} IBNibRefObject;
PyObject *IBNibRefObj_New(IBNibRef itself)
{
IBNibRefObject *it;
it = PyObject_NEW(IBNibRefObject, &IBNibRef_Type);
if (it == NULL) return NULL;
it->ob_itself = itself;
return (PyObject *)it;
IBNibRefObject *it;
it = PyObject_NEW(IBNibRefObject, &IBNibRef_Type);
if (it == NULL) return NULL;
it->ob_itself = itself;
return (PyObject *)it;
}
int IBNibRefObj_Convert(PyObject *v, IBNibRef *p_itself)
{
if (!IBNibRefObj_Check(v))
{
PyErr_SetString(PyExc_TypeError, "IBNibRef required");
return 0;
}
*p_itself = ((IBNibRefObject *)v)->ob_itself;
return 1;
if (!IBNibRefObj_Check(v))
{
PyErr_SetString(PyExc_TypeError, "IBNibRef required");
return 0;
}
*p_itself = ((IBNibRefObject *)v)->ob_itself;
return 1;
}
static void IBNibRefObj_dealloc(IBNibRefObject *self)
{
DisposeNibReference(self->ob_itself);
self->ob_type->tp_free((PyObject *)self);
DisposeNibReference(self->ob_itself);
self->ob_type->tp_free((PyObject *)self);
}
static PyObject *IBNibRefObj_CreateWindowFromNib(IBNibRefObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
WindowPtr outWindow;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateWindowFromNib(_self->ob_itself,
inName,
&outWindow);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
WinObj_New, outWindow);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
WindowPtr outWindow;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateWindowFromNib(_self->ob_itself,
inName,
&outWindow);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
WinObj_New, outWindow);
return _res;
}
static PyObject *IBNibRefObj_CreateMenuFromNib(IBNibRefObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
MenuHandle outMenuRef;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateMenuFromNib(_self->ob_itself,
inName,
&outMenuRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
MenuObj_New, outMenuRef);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
MenuHandle outMenuRef;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateMenuFromNib(_self->ob_itself,
inName,
&outMenuRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
MenuObj_New, outMenuRef);
return _res;
}
static PyObject *IBNibRefObj_CreateMenuBarFromNib(IBNibRefObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
Handle outMenuBar;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateMenuBarFromNib(_self->ob_itself,
inName,
&outMenuBar);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
ResObj_New, outMenuBar);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
Handle outMenuBar;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = CreateMenuBarFromNib(_self->ob_itself,
inName,
&outMenuBar);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
ResObj_New, outMenuBar);
return _res;
}
static PyObject *IBNibRefObj_SetMenuBarFromNib(IBNibRefObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = SetMenuBarFromNib(_self->ob_itself,
inName);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inName;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inName))
return NULL;
_err = SetMenuBarFromNib(_self->ob_itself,
inName);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyMethodDef IBNibRefObj_methods[] = {
{"CreateWindowFromNib", (PyCFunction)IBNibRefObj_CreateWindowFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (WindowPtr outWindow)")},
{"CreateMenuFromNib", (PyCFunction)IBNibRefObj_CreateMenuFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (MenuHandle outMenuRef)")},
{"CreateMenuBarFromNib", (PyCFunction)IBNibRefObj_CreateMenuBarFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (Handle outMenuBar)")},
{"SetMenuBarFromNib", (PyCFunction)IBNibRefObj_SetMenuBarFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> None")},
{NULL, NULL, 0}
{"CreateWindowFromNib", (PyCFunction)IBNibRefObj_CreateWindowFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (WindowPtr outWindow)")},
{"CreateMenuFromNib", (PyCFunction)IBNibRefObj_CreateMenuFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (MenuHandle outMenuRef)")},
{"CreateMenuBarFromNib", (PyCFunction)IBNibRefObj_CreateMenuBarFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> (Handle outMenuBar)")},
{"SetMenuBarFromNib", (PyCFunction)IBNibRefObj_SetMenuBarFromNib, 1,
PyDoc_STR("(CFStringRef inName) -> None")},
{NULL, NULL, 0}
};
#define IBNibRefObj_getsetlist NULL
@ -149,61 +149,61 @@ static PyMethodDef IBNibRefObj_methods[] = {
static PyObject *IBNibRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
PyObject *_self;
IBNibRef itself;
char *kw[] = {"itself", 0};
PyObject *_self;
IBNibRef itself;
char *kw[] = {"itself", 0};
if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, IBNibRefObj_Convert, &itself)) return NULL;
if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
((IBNibRefObject *)_self)->ob_itself = itself;
return _self;
if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, IBNibRefObj_Convert, &itself)) return NULL;
if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
((IBNibRefObject *)_self)->ob_itself = itself;
return _self;
}
#define IBNibRefObj_tp_free PyObject_Del
PyTypeObject IBNibRef_Type = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"_IBCarbon.IBNibRef", /*tp_name*/
sizeof(IBNibRefObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor) IBNibRefObj_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
(cmpfunc) IBNibRefObj_compare, /*tp_compare*/
(reprfunc) IBNibRefObj_repr, /*tp_repr*/
(PyNumberMethods *)0, /* tp_as_number */
(PySequenceMethods *)0, /* tp_as_sequence */
(PyMappingMethods *)0, /* tp_as_mapping */
(hashfunc) IBNibRefObj_hash, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
PyObject_GenericSetAttr, /*tp_setattro */
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
IBNibRefObj_methods, /* tp_methods */
0, /*tp_members*/
IBNibRefObj_getsetlist, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
IBNibRefObj_tp_init, /* tp_init */
IBNibRefObj_tp_alloc, /* tp_alloc */
IBNibRefObj_tp_new, /* tp_new */
IBNibRefObj_tp_free, /* tp_free */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"_IBCarbon.IBNibRef", /*tp_name*/
sizeof(IBNibRefObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor) IBNibRefObj_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
(cmpfunc) IBNibRefObj_compare, /*tp_compare*/
(reprfunc) IBNibRefObj_repr, /*tp_repr*/
(PyNumberMethods *)0, /* tp_as_number */
(PySequenceMethods *)0, /* tp_as_sequence */
(PyMappingMethods *)0, /* tp_as_mapping */
(hashfunc) IBNibRefObj_hash, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
PyObject_GenericSetAttr, /*tp_setattro */
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
IBNibRefObj_methods, /* tp_methods */
0, /*tp_members*/
IBNibRefObj_getsetlist, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
IBNibRefObj_tp_init, /* tp_init */
IBNibRefObj_tp_alloc, /* tp_alloc */
IBNibRefObj_tp_new, /* tp_new */
IBNibRefObj_tp_free, /* tp_free */
};
/* -------------------- End object type IBNibRef -------------------- */
@ -211,28 +211,28 @@ PyTypeObject IBNibRef_Type = {
static PyObject *IBCarbon_CreateNibReference(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inNibName;
IBNibRef outNibRef;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inNibName))
return NULL;
_err = CreateNibReference(inNibName,
&outNibRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
IBNibRefObj_New, outNibRef);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFStringRef inNibName;
IBNibRef outNibRef;
if (!PyArg_ParseTuple(_args, "O&",
CFStringRefObj_Convert, &inNibName))
return NULL;
_err = CreateNibReference(inNibName,
&outNibRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
IBNibRefObj_New, outNibRef);
return _res;
}
#endif /* __LP64__ */
static PyMethodDef IBCarbon_methods[] = {
#ifndef __LP64__
{"CreateNibReference", (PyCFunction)IBCarbon_CreateNibReference, 1,
PyDoc_STR("(CFStringRef inNibName) -> (IBNibRef outNibRef)")},
{"CreateNibReference", (PyCFunction)IBCarbon_CreateNibReference, 1,
PyDoc_STR("(CFStringRef inNibName) -> (IBNibRef outNibRef)")},
#endif /* __LP64__ */
{NULL, NULL, 0}
{NULL, NULL, 0}
};
@ -240,29 +240,29 @@ static PyMethodDef IBCarbon_methods[] = {
void init_IBCarbon(void)
{
PyObject *m;
PyObject *m;
#ifndef __LP64__
PyObject *d;
PyObject *d;
#endif /* __LP64__ */
m = Py_InitModule("_IBCarbon", IBCarbon_methods);
m = Py_InitModule("_IBCarbon", IBCarbon_methods);
#ifndef __LP64__
d = PyModule_GetDict(m);
IBCarbon_Error = PyMac_GetOSErrException();
if (IBCarbon_Error == NULL ||
PyDict_SetItemString(d, "Error", IBCarbon_Error) != 0)
return;
IBNibRef_Type.ob_type = &PyType_Type;
if (PyType_Ready(&IBNibRef_Type) < 0) return;
Py_INCREF(&IBNibRef_Type);
PyModule_AddObject(m, "IBNibRef", (PyObject *)&IBNibRef_Type);
/* Backward-compatible name */
Py_INCREF(&IBNibRef_Type);
PyModule_AddObject(m, "IBNibRefType", (PyObject *)&IBNibRef_Type);
d = PyModule_GetDict(m);
IBCarbon_Error = PyMac_GetOSErrException();
if (IBCarbon_Error == NULL ||
PyDict_SetItemString(d, "Error", IBCarbon_Error) != 0)
return;
IBNibRef_Type.ob_type = &PyType_Type;
if (PyType_Ready(&IBNibRef_Type) < 0) return;
Py_INCREF(&IBNibRef_Type);
PyModule_AddObject(m, "IBNibRef", (PyObject *)&IBNibRef_Type);
/* Backward-compatible name */
Py_INCREF(&IBNibRef_Type);
PyModule_AddObject(m, "IBNibRefType", (PyObject *)&IBNibRef_Type);
#endif /* __LP64__ */
}

View file

@ -43,8 +43,8 @@ static PyObject *ErrorObject;
/* Declarations for objects of type ic_instance */
typedef struct {
PyObject_HEAD
ICInstance inst;
PyObject_HEAD
ICInstance inst;
} iciobject;
static PyTypeObject Icitype;
@ -54,303 +54,303 @@ static PyTypeObject Icitype;
/* ---------------------------------------------------------------- */
static char ici_ICGetSeed__doc__[] =
static char ici_ICGetSeed__doc__[] =
"()->int; Returns int that changes when configuration does"
;
static PyObject *
ici_ICGetSeed(iciobject *self, PyObject *args)
{
OSStatus err;
long seed;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICGetSeed(self->inst, &seed)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)seed);
OSStatus err;
long seed;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICGetSeed(self->inst, &seed)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)seed);
}
static char ici_ICBegin__doc__[] =
static char ici_ICBegin__doc__[] =
"(perm)->None; Lock config file for read/write"
;
static PyObject *
ici_ICBegin(iciobject *self, PyObject *args)
{
OSStatus err;
int perm;
if (!PyArg_ParseTuple(args, "i", &perm))
return NULL;
if ((err=ICBegin(self->inst, (ICPerm)perm)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
OSStatus err;
int perm;
if (!PyArg_ParseTuple(args, "i", &perm))
return NULL;
if ((err=ICBegin(self->inst, (ICPerm)perm)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char ici_ICFindPrefHandle__doc__[] =
static char ici_ICFindPrefHandle__doc__[] =
"(key, handle)->attrs; Lookup key, store result in handle, return attributes"
;
static PyObject *
ici_ICFindPrefHandle(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 key;
ICAttr attr;
Handle h;
if (!PyArg_ParseTuple(args, "O&O&", PyMac_GetStr255, &key, ResObj_Convert, &h))
return NULL;
if ((err=ICFindPrefHandle(self->inst, key, &attr, h)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)attr);
OSStatus err;
Str255 key;
ICAttr attr;
Handle h;
if (!PyArg_ParseTuple(args, "O&O&", PyMac_GetStr255, &key, ResObj_Convert, &h))
return NULL;
if ((err=ICFindPrefHandle(self->inst, key, &attr, h)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)attr);
}
static char ici_ICSetPref__doc__[] =
static char ici_ICSetPref__doc__[] =
"(key, attr, data)->None; Set preference key to data with attributes"
;
static PyObject *
ici_ICSetPref(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 key;
int attr;
char *data;
int datalen;
if (!PyArg_ParseTuple(args, "O&is#", PyMac_GetStr255, &key, &attr,
&data, &datalen))
return NULL;
if ((err=ICSetPref(self->inst, key, (ICAttr)attr, (Ptr)data,
(long)datalen)) != 0)
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
OSStatus err;
Str255 key;
int attr;
char *data;
int datalen;
if (!PyArg_ParseTuple(args, "O&is#", PyMac_GetStr255, &key, &attr,
&data, &datalen))
return NULL;
if ((err=ICSetPref(self->inst, key, (ICAttr)attr, (Ptr)data,
(long)datalen)) != 0)
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char ici_ICCountPref__doc__[] =
static char ici_ICCountPref__doc__[] =
"()->int; Return number of preferences"
;
static PyObject *
ici_ICCountPref(iciobject *self, PyObject *args)
{
OSStatus err;
long count;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICCountPref(self->inst, &count)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)count);
OSStatus err;
long count;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICCountPref(self->inst, &count)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("i", (int)count);
}
static char ici_ICGetIndPref__doc__[] =
static char ici_ICGetIndPref__doc__[] =
"(num)->key; Return key of preference with given index"
;
static PyObject *
ici_ICGetIndPref(iciobject *self, PyObject *args)
{
OSStatus err;
long num;
Str255 key;
if (!PyArg_ParseTuple(args, "l", &num))
return NULL;
if ((err=ICGetIndPref(self->inst, num, key)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("O&", PyMac_BuildStr255, key);
OSStatus err;
long num;
Str255 key;
if (!PyArg_ParseTuple(args, "l", &num))
return NULL;
if ((err=ICGetIndPref(self->inst, num, key)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("O&", PyMac_BuildStr255, key);
}
static char ici_ICDeletePref__doc__[] =
static char ici_ICDeletePref__doc__[] =
"(key)->None; Delete preference"
;
static PyObject *
ici_ICDeletePref(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 key;
OSStatus err;
Str255 key;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, key))
return NULL;
if ((err=ICDeletePref(self->inst, key)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, key))
return NULL;
if ((err=ICDeletePref(self->inst, key)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char ici_ICEnd__doc__[] =
static char ici_ICEnd__doc__[] =
"()->None; Unlock file after ICBegin call"
;
static PyObject *
ici_ICEnd(iciobject *self, PyObject *args)
{
OSStatus err;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICEnd(self->inst)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
OSStatus err;
if (!PyArg_ParseTuple(args, ""))
return NULL;
if ((err=ICEnd(self->inst)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char ici_ICEditPreferences__doc__[] =
static char ici_ICEditPreferences__doc__[] =
"(key)->None; Ask user to edit preferences, staring with key"
;
static PyObject *
ici_ICEditPreferences(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 key;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, key))
return NULL;
if ((err=ICEditPreferences(self->inst, key)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
OSStatus err;
Str255 key;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, key))
return NULL;
if ((err=ICEditPreferences(self->inst, key)) != 0 )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char ici_ICParseURL__doc__[] =
static char ici_ICParseURL__doc__[] =
"(hint, data, selStart, selEnd, handle)->selStart, selEnd; Find an URL, return in handle"
;
static PyObject *
ici_ICParseURL(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 hint;
char *data;
int datalen;
long selStart, selEnd;
Handle h;
if (!PyArg_ParseTuple(args, "O&s#llO&", PyMac_GetStr255, hint, &data, &datalen,
&selStart, &selEnd, ResObj_Convert, &h))
return NULL;
if ((err=ICParseURL(self->inst, hint, (Ptr)data, (long)datalen,
&selStart, &selEnd, h)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("ii", (int)selStart, (int)selEnd);
OSStatus err;
Str255 hint;
char *data;
int datalen;
long selStart, selEnd;
Handle h;
if (!PyArg_ParseTuple(args, "O&s#llO&", PyMac_GetStr255, hint, &data, &datalen,
&selStart, &selEnd, ResObj_Convert, &h))
return NULL;
if ((err=ICParseURL(self->inst, hint, (Ptr)data, (long)datalen,
&selStart, &selEnd, h)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("ii", (int)selStart, (int)selEnd);
}
static char ici_ICLaunchURL__doc__[] =
static char ici_ICLaunchURL__doc__[] =
"(hint, data, selStart, selEnd)->None; Find an URL and launch the correct app"
;
static PyObject *
ici_ICLaunchURL(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 hint;
char *data;
int datalen;
long selStart, selEnd;
if (!PyArg_ParseTuple(args, "O&s#ll", PyMac_GetStr255, hint, &data, &datalen,
&selStart, &selEnd))
return NULL;
if ((err=ICLaunchURL(self->inst, hint, (Ptr)data, (long)datalen,
&selStart, &selEnd)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("ii", (int)selStart, (int)selEnd);
OSStatus err;
Str255 hint;
char *data;
int datalen;
long selStart, selEnd;
if (!PyArg_ParseTuple(args, "O&s#ll", PyMac_GetStr255, hint, &data, &datalen,
&selStart, &selEnd))
return NULL;
if ((err=ICLaunchURL(self->inst, hint, (Ptr)data, (long)datalen,
&selStart, &selEnd)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("ii", (int)selStart, (int)selEnd);
}
static char ici_ICMapFilename__doc__[] =
static char ici_ICMapFilename__doc__[] =
"(filename)->mapinfo; Get filemap info for given filename"
;
static PyObject *
ici_ICMapFilename(iciobject *self, PyObject *args)
{
OSStatus err;
Str255 filename;
ICMapEntry entry;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, filename))
return NULL;
if ((err=ICMapFilename(self->inst, filename, &entry)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("hO&O&O&lO&O&O&O&O&", entry.version,
PyMac_BuildOSType, entry.fileType,
PyMac_BuildOSType, entry.fileCreator,
PyMac_BuildOSType, entry.postCreator,
entry.flags,
PyMac_BuildStr255, entry.extension,
PyMac_BuildStr255, entry.creatorAppName,
PyMac_BuildStr255, entry.postAppName,
PyMac_BuildStr255, entry.MIMEType,
PyMac_BuildStr255, entry.entryName);
OSStatus err;
Str255 filename;
ICMapEntry entry;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetStr255, filename))
return NULL;
if ((err=ICMapFilename(self->inst, filename, &entry)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("hO&O&O&lO&O&O&O&O&", entry.version,
PyMac_BuildOSType, entry.fileType,
PyMac_BuildOSType, entry.fileCreator,
PyMac_BuildOSType, entry.postCreator,
entry.flags,
PyMac_BuildStr255, entry.extension,
PyMac_BuildStr255, entry.creatorAppName,
PyMac_BuildStr255, entry.postAppName,
PyMac_BuildStr255, entry.MIMEType,
PyMac_BuildStr255, entry.entryName);
}
static char ici_ICMapTypeCreator__doc__[] =
static char ici_ICMapTypeCreator__doc__[] =
"(type, creator, filename)->mapinfo; Get filemap info for given tp/cr/filename"
;
static PyObject *
ici_ICMapTypeCreator(iciobject *self, PyObject *args)
{
OSStatus err;
OSType type, creator;
Str255 filename;
ICMapEntry entry;
if (!PyArg_ParseTuple(args, "O&O&O&",
PyMac_GetOSType, &type,
PyMac_GetOSType, &creator,
PyMac_GetStr255, filename))
return NULL;
if ((err=ICMapTypeCreator(self->inst, type, creator, filename, &entry)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("hO&O&O&lO&O&O&O&O&", entry.version,
PyMac_BuildOSType, entry.fileType,
PyMac_BuildOSType, entry.fileCreator,
PyMac_BuildOSType, entry.postCreator,
entry.flags,
PyMac_BuildStr255, entry.extension,
PyMac_BuildStr255, entry.creatorAppName,
PyMac_BuildStr255, entry.postAppName,
PyMac_BuildStr255, entry.MIMEType,
PyMac_BuildStr255, entry.entryName);
OSStatus err;
OSType type, creator;
Str255 filename;
ICMapEntry entry;
if (!PyArg_ParseTuple(args, "O&O&O&",
PyMac_GetOSType, &type,
PyMac_GetOSType, &creator,
PyMac_GetStr255, filename))
return NULL;
if ((err=ICMapTypeCreator(self->inst, type, creator, filename, &entry)) != 0 )
return PyMac_Error(err);
return Py_BuildValue("hO&O&O&lO&O&O&O&O&", entry.version,
PyMac_BuildOSType, entry.fileType,
PyMac_BuildOSType, entry.fileCreator,
PyMac_BuildOSType, entry.postCreator,
entry.flags,
PyMac_BuildStr255, entry.extension,
PyMac_BuildStr255, entry.creatorAppName,
PyMac_BuildStr255, entry.postAppName,
PyMac_BuildStr255, entry.MIMEType,
PyMac_BuildStr255, entry.entryName);
}
static struct PyMethodDef ici_methods[] = {
{"ICGetSeed", (PyCFunction)ici_ICGetSeed, METH_VARARGS, ici_ICGetSeed__doc__},
{"ICBegin", (PyCFunction)ici_ICBegin, METH_VARARGS, ici_ICBegin__doc__},
{"ICFindPrefHandle", (PyCFunction)ici_ICFindPrefHandle, METH_VARARGS, ici_ICFindPrefHandle__doc__},
{"ICSetPref", (PyCFunction)ici_ICSetPref, METH_VARARGS, ici_ICSetPref__doc__},
{"ICCountPref", (PyCFunction)ici_ICCountPref, METH_VARARGS, ici_ICCountPref__doc__},
{"ICGetIndPref", (PyCFunction)ici_ICGetIndPref, METH_VARARGS, ici_ICGetIndPref__doc__},
{"ICDeletePref", (PyCFunction)ici_ICDeletePref, METH_VARARGS, ici_ICDeletePref__doc__},
{"ICEnd", (PyCFunction)ici_ICEnd, METH_VARARGS, ici_ICEnd__doc__},
{"ICEditPreferences", (PyCFunction)ici_ICEditPreferences, METH_VARARGS, ici_ICEditPreferences__doc__},
{"ICParseURL", (PyCFunction)ici_ICParseURL, METH_VARARGS, ici_ICParseURL__doc__},
{"ICLaunchURL", (PyCFunction)ici_ICLaunchURL, METH_VARARGS, ici_ICLaunchURL__doc__},
{"ICMapFilename", (PyCFunction)ici_ICMapFilename, METH_VARARGS, ici_ICMapFilename__doc__},
{"ICMapTypeCreator", (PyCFunction)ici_ICMapTypeCreator, METH_VARARGS, ici_ICMapTypeCreator__doc__},
{NULL, NULL} /* sentinel */
{"ICGetSeed", (PyCFunction)ici_ICGetSeed, METH_VARARGS, ici_ICGetSeed__doc__},
{"ICBegin", (PyCFunction)ici_ICBegin, METH_VARARGS, ici_ICBegin__doc__},
{"ICFindPrefHandle", (PyCFunction)ici_ICFindPrefHandle, METH_VARARGS, ici_ICFindPrefHandle__doc__},
{"ICSetPref", (PyCFunction)ici_ICSetPref, METH_VARARGS, ici_ICSetPref__doc__},
{"ICCountPref", (PyCFunction)ici_ICCountPref, METH_VARARGS, ici_ICCountPref__doc__},
{"ICGetIndPref", (PyCFunction)ici_ICGetIndPref, METH_VARARGS, ici_ICGetIndPref__doc__},
{"ICDeletePref", (PyCFunction)ici_ICDeletePref, METH_VARARGS, ici_ICDeletePref__doc__},
{"ICEnd", (PyCFunction)ici_ICEnd, METH_VARARGS, ici_ICEnd__doc__},
{"ICEditPreferences", (PyCFunction)ici_ICEditPreferences, METH_VARARGS, ici_ICEditPreferences__doc__},
{"ICParseURL", (PyCFunction)ici_ICParseURL, METH_VARARGS, ici_ICParseURL__doc__},
{"ICLaunchURL", (PyCFunction)ici_ICLaunchURL, METH_VARARGS, ici_ICLaunchURL__doc__},
{"ICMapFilename", (PyCFunction)ici_ICMapFilename, METH_VARARGS, ici_ICMapFilename__doc__},
{"ICMapTypeCreator", (PyCFunction)ici_ICMapTypeCreator, METH_VARARGS, ici_ICMapTypeCreator__doc__},
{NULL, NULL} /* sentinel */
};
/* ---------- */
@ -359,61 +359,61 @@ static struct PyMethodDef ici_methods[] = {
static iciobject *
newiciobject(OSType creator)
{
iciobject *self;
OSStatus err;
self = PyObject_NEW(iciobject, &Icitype);
if (self == NULL)
return NULL;
if ((err=ICStart(&self->inst, creator)) != 0 ) {
(void)PyMac_Error(err);
PyObject_DEL(self);
return NULL;
}
return self;
iciobject *self;
OSStatus err;
self = PyObject_NEW(iciobject, &Icitype);
if (self == NULL)
return NULL;
if ((err=ICStart(&self->inst, creator)) != 0 ) {
(void)PyMac_Error(err);
PyObject_DEL(self);
return NULL;
}
return self;
}
static void
ici_dealloc(iciobject *self)
{
(void)ICStop(self->inst);
PyObject_DEL(self);
(void)ICStop(self->inst);
PyObject_DEL(self);
}
static PyObject *
ici_getattr(iciobject *self, char *name)
{
return Py_FindMethod(ici_methods, (PyObject *)self, name);
return Py_FindMethod(ici_methods, (PyObject *)self, name);
}
static char Icitype__doc__[] =
static char Icitype__doc__[] =
"Internet Config instance"
;
static PyTypeObject Icitype = {
PyObject_HEAD_INIT(&PyType_Type)
0, /*ob_size*/
"icglue.ic_instance", /*tp_name*/
sizeof(iciobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)ici_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
(getattrfunc)ici_getattr, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
(cmpfunc)0, /*tp_compare*/
(reprfunc)0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
PyObject_HEAD_INIT(&PyType_Type)
0, /*ob_size*/
"icglue.ic_instance", /*tp_name*/
sizeof(iciobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)ici_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
(getattrfunc)ici_getattr, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
(cmpfunc)0, /*tp_compare*/
(reprfunc)0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
/* Space for future expansion */
0L,0L,0L,0L,
Icitype__doc__ /* Documentation string */
/* Space for future expansion */
0L,0L,0L,0L,
Icitype__doc__ /* Documentation string */
};
/* End of code for ic_instance objects */
@ -427,52 +427,52 @@ static char ic_ICStart__doc__[] =
static PyObject *
ic_ICStart(PyObject *self, PyObject *args)
{
OSType creator;
OSType creator;
if (!PyArg_ParseTuple(args, "O&", PyMac_GetOSType, &creator))
return NULL;
return (PyObject *)newiciobject(creator);
if (!PyArg_ParseTuple(args, "O&", PyMac_GetOSType, &creator))
return NULL;
return (PyObject *)newiciobject(creator);
}
/* List of methods defined in the module */
static struct PyMethodDef ic_methods[] = {
{"ICStart", (PyCFunction)ic_ICStart, METH_VARARGS, ic_ICStart__doc__},
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
{"ICStart", (PyCFunction)ic_ICStart, METH_VARARGS, ic_ICStart__doc__},
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initicglue) */
static char icglue_module_documentation[] =
static char icglue_module_documentation[] =
"Implements low-level Internet Config interface"
;
void
initicglue(void)
{
PyObject *m, *d;
if (PyErr_WarnPy3k("In 3.x, the icglue module is removed.", 1))
return;
PyObject *m, *d;
/* Create the module and add the functions */
m = Py_InitModule4("icglue", ic_methods,
icglue_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
if (PyErr_WarnPy3k("In 3.x, the icglue module is removed.", 1))
return;
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyMac_GetOSErrException();
if (ErrorObject == NULL ||
PyDict_SetItemString(d, "error", ErrorObject) != 0)
return;
/* Create the module and add the functions */
m = Py_InitModule4("icglue", ic_methods,
icglue_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module icglue");
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyMac_GetOSErrException();
if (ErrorObject == NULL ||
PyDict_SetItemString(d, "error", ErrorObject) != 0)
return;
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module icglue");
}

File diff suppressed because it is too large Load diff

View file

@ -9,9 +9,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -27,21 +27,21 @@ PyObject *PyMac_GetOSErrException(void);
static int
OptCFStringRefObj_Convert(PyObject *v, CFStringRef *spec)
{
if (v == Py_None) {
*spec = NULL;
return 1;
}
return CFStringRefObj_Convert(v, spec);
if (v == Py_None) {
*spec = NULL;
return 1;
}
return CFStringRefObj_Convert(v, spec);
}
PyObject *
OptCFStringRefObj_New(CFStringRef it)
{
if (it == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
return CFStringRefObj_New(it);
if (it == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
return CFStringRefObj_New(it);
}
/*
@ -51,19 +51,19 @@ PyObject *
LSItemInfoRecord_New(LSItemInfoRecord *it)
{
#ifndef __LP64__
return Py_BuildValue("{s:is:O&s:O&s:O&s:O&s:i}",
"flags", it->flags,
"filetype", PyMac_BuildOSType, it->filetype,
"creator", PyMac_BuildOSType, it->creator,
"extension", OptCFStringRefObj_New, it->extension,
"iconFileName", OptCFStringRefObj_New, it->iconFileName,
"kindID", it->kindID);
return Py_BuildValue("{s:is:O&s:O&s:O&s:O&s:i}",
"flags", it->flags,
"filetype", PyMac_BuildOSType, it->filetype,
"creator", PyMac_BuildOSType, it->creator,
"extension", OptCFStringRefObj_New, it->extension,
"iconFileName", OptCFStringRefObj_New, it->iconFileName,
"kindID", it->kindID);
#else
return Py_BuildValue("{s:is:O&s:O&s:O&}",
"flags", it->flags,
"filetype", PyMac_BuildOSType, it->filetype,
"creator", PyMac_BuildOSType, it->creator,
"extension", OptCFStringRefObj_New, it->extension);
return Py_BuildValue("{s:is:O&s:O&s:O&}",
"flags", it->flags,
"filetype", PyMac_BuildOSType, it->filetype,
"creator", PyMac_BuildOSType, it->creator,
"extension", OptCFStringRefObj_New, it->extension);
#endif
}
@ -71,391 +71,391 @@ static PyObject *Launch_Error;
static PyObject *Launch_LSCopyItemInfoForRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemRef;
LSRequestedInfo inWhichInfo;
LSItemInfoRecord outItemInfo;
if (!PyArg_ParseTuple(_args, "O&l",
PyMac_GetFSRef, &inItemRef,
&inWhichInfo))
return NULL;
_err = LSCopyItemInfoForRef(&inItemRef,
inWhichInfo,
&outItemInfo);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
LSItemInfoRecord_New, &outItemInfo);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemRef;
LSRequestedInfo inWhichInfo;
LSItemInfoRecord outItemInfo;
if (!PyArg_ParseTuple(_args, "O&l",
PyMac_GetFSRef, &inItemRef,
&inWhichInfo))
return NULL;
_err = LSCopyItemInfoForRef(&inItemRef,
inWhichInfo,
&outItemInfo);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
LSItemInfoRecord_New, &outItemInfo);
return _res;
}
static PyObject *Launch_LSCopyItemInfoForURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
LSRequestedInfo inWhichInfo;
LSItemInfoRecord outItemInfo;
if (!PyArg_ParseTuple(_args, "O&l",
CFURLRefObj_Convert, &inURL,
&inWhichInfo))
return NULL;
_err = LSCopyItemInfoForURL(inURL,
inWhichInfo,
&outItemInfo);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
LSItemInfoRecord_New, &outItemInfo);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
LSRequestedInfo inWhichInfo;
LSItemInfoRecord outItemInfo;
if (!PyArg_ParseTuple(_args, "O&l",
CFURLRefObj_Convert, &inURL,
&inWhichInfo))
return NULL;
_err = LSCopyItemInfoForURL(inURL,
inWhichInfo,
&outItemInfo);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
LSItemInfoRecord_New, &outItemInfo);
return _res;
}
static PyObject *Launch_LSGetExtensionInfo(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
UniChar *inNameLen__in__;
UniCharCount inNameLen__len__;
int inNameLen__in_len__;
UniCharCount outExtStartIndex;
if (!PyArg_ParseTuple(_args, "u#",
&inNameLen__in__, &inNameLen__in_len__))
return NULL;
inNameLen__len__ = inNameLen__in_len__;
_err = LSGetExtensionInfo(inNameLen__len__, inNameLen__in__,
&outExtStartIndex);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
outExtStartIndex);
return _res;
PyObject *_res = NULL;
OSStatus _err;
UniChar *inNameLen__in__;
UniCharCount inNameLen__len__;
int inNameLen__in_len__;
UniCharCount outExtStartIndex;
if (!PyArg_ParseTuple(_args, "u#",
&inNameLen__in__, &inNameLen__in_len__))
return NULL;
inNameLen__len__ = inNameLen__in_len__;
_err = LSGetExtensionInfo(inNameLen__len__, inNameLen__in__,
&outExtStartIndex);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
outExtStartIndex);
return _res;
}
static PyObject *Launch_LSCopyDisplayNameForRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
CFStringRef outDisplayName;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inRef))
return NULL;
_err = LSCopyDisplayNameForRef(&inRef,
&outDisplayName);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outDisplayName);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
CFStringRef outDisplayName;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inRef))
return NULL;
_err = LSCopyDisplayNameForRef(&inRef,
&outDisplayName);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outDisplayName);
return _res;
}
static PyObject *Launch_LSCopyDisplayNameForURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFStringRef outDisplayName;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSCopyDisplayNameForURL(inURL,
&outDisplayName);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outDisplayName);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFStringRef outDisplayName;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSCopyDisplayNameForURL(inURL,
&outDisplayName);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outDisplayName);
return _res;
}
static PyObject *Launch_LSSetExtensionHiddenForRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
Boolean inHide;
if (!PyArg_ParseTuple(_args, "O&b",
PyMac_GetFSRef, &inRef,
&inHide))
return NULL;
_err = LSSetExtensionHiddenForRef(&inRef,
inHide);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
Boolean inHide;
if (!PyArg_ParseTuple(_args, "O&b",
PyMac_GetFSRef, &inRef,
&inHide))
return NULL;
_err = LSSetExtensionHiddenForRef(&inRef,
inHide);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Launch_LSSetExtensionHiddenForURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
Boolean inHide;
if (!PyArg_ParseTuple(_args, "O&b",
CFURLRefObj_Convert, &inURL,
&inHide))
return NULL;
_err = LSSetExtensionHiddenForURL(inURL,
inHide);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
Boolean inHide;
if (!PyArg_ParseTuple(_args, "O&b",
CFURLRefObj_Convert, &inURL,
&inHide))
return NULL;
_err = LSSetExtensionHiddenForURL(inURL,
inHide);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Launch_LSCopyKindStringForRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inFSRef;
CFStringRef outKindString;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inFSRef))
return NULL;
_err = LSCopyKindStringForRef(&inFSRef,
&outKindString);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outKindString);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inFSRef;
CFStringRef outKindString;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inFSRef))
return NULL;
_err = LSCopyKindStringForRef(&inFSRef,
&outKindString);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outKindString);
return _res;
}
static PyObject *Launch_LSCopyKindStringForURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFStringRef outKindString;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSCopyKindStringForURL(inURL,
&outKindString);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outKindString);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFStringRef outKindString;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSCopyKindStringForURL(inURL,
&outKindString);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFStringRefObj_New, outKindString);
return _res;
}
static PyObject *Launch_LSGetApplicationForItem(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemRef;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&l",
PyMac_GetFSRef, &inItemRef,
&inRoleMask))
return NULL;
_err = LSGetApplicationForItem(&inItemRef,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemRef;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&l",
PyMac_GetFSRef, &inItemRef,
&inRoleMask))
return NULL;
_err = LSGetApplicationForItem(&inItemRef,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
}
static PyObject *Launch_LSGetApplicationForInfo(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
OSType inType;
OSType inCreator;
CFStringRef inExtension;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&O&O&l",
PyMac_GetOSType, &inType,
PyMac_GetOSType, &inCreator,
OptCFStringRefObj_Convert, &inExtension,
&inRoleMask))
return NULL;
_err = LSGetApplicationForInfo(inType,
inCreator,
inExtension,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
PyObject *_res = NULL;
OSStatus _err;
OSType inType;
OSType inCreator;
CFStringRef inExtension;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&O&O&l",
PyMac_GetOSType, &inType,
PyMac_GetOSType, &inCreator,
OptCFStringRefObj_Convert, &inExtension,
&inRoleMask))
return NULL;
_err = LSGetApplicationForInfo(inType,
inCreator,
inExtension,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
}
static PyObject *Launch_LSGetApplicationForURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&l",
CFURLRefObj_Convert, &inURL,
&inRoleMask))
return NULL;
_err = LSGetApplicationForURL(inURL,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
LSRolesMask inRoleMask;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&l",
CFURLRefObj_Convert, &inURL,
&inRoleMask))
return NULL;
_err = LSGetApplicationForURL(inURL,
inRoleMask,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
}
static PyObject *Launch_LSFindApplicationForInfo(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
OSType inCreator;
CFStringRef inBundleID;
CFStringRef inName;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&O&O&",
PyMac_GetOSType, &inCreator,
OptCFStringRefObj_Convert, &inBundleID,
OptCFStringRefObj_Convert, &inName))
return NULL;
_err = LSFindApplicationForInfo(inCreator,
inBundleID,
inName,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
PyObject *_res = NULL;
OSStatus _err;
OSType inCreator;
CFStringRef inBundleID;
CFStringRef inName;
FSRef outAppRef;
CFURLRef outAppURL;
if (!PyArg_ParseTuple(_args, "O&O&O&",
PyMac_GetOSType, &inCreator,
OptCFStringRefObj_Convert, &inBundleID,
OptCFStringRefObj_Convert, &inName))
return NULL;
_err = LSFindApplicationForInfo(inCreator,
inBundleID,
inName,
&outAppRef,
&outAppURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&O&",
PyMac_BuildFSRef, &outAppRef,
CFURLRefObj_New, outAppURL);
return _res;
}
static PyObject *Launch_LSCanRefAcceptItem(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemFSRef;
FSRef inTargetRef;
LSRolesMask inRoleMask;
LSAcceptanceFlags inFlags;
Boolean outAcceptsItem;
if (!PyArg_ParseTuple(_args, "O&O&ll",
PyMac_GetFSRef, &inItemFSRef,
PyMac_GetFSRef, &inTargetRef,
&inRoleMask,
&inFlags))
return NULL;
_err = LSCanRefAcceptItem(&inItemFSRef,
&inTargetRef,
inRoleMask,
inFlags,
&outAcceptsItem);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("b",
outAcceptsItem);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inItemFSRef;
FSRef inTargetRef;
LSRolesMask inRoleMask;
LSAcceptanceFlags inFlags;
Boolean outAcceptsItem;
if (!PyArg_ParseTuple(_args, "O&O&ll",
PyMac_GetFSRef, &inItemFSRef,
PyMac_GetFSRef, &inTargetRef,
&inRoleMask,
&inFlags))
return NULL;
_err = LSCanRefAcceptItem(&inItemFSRef,
&inTargetRef,
inRoleMask,
inFlags,
&outAcceptsItem);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("b",
outAcceptsItem);
return _res;
}
static PyObject *Launch_LSCanURLAcceptURL(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inItemURL;
CFURLRef inTargetURL;
LSRolesMask inRoleMask;
LSAcceptanceFlags inFlags;
Boolean outAcceptsItem;
if (!PyArg_ParseTuple(_args, "O&O&ll",
CFURLRefObj_Convert, &inItemURL,
CFURLRefObj_Convert, &inTargetURL,
&inRoleMask,
&inFlags))
return NULL;
_err = LSCanURLAcceptURL(inItemURL,
inTargetURL,
inRoleMask,
inFlags,
&outAcceptsItem);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("b",
outAcceptsItem);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inItemURL;
CFURLRef inTargetURL;
LSRolesMask inRoleMask;
LSAcceptanceFlags inFlags;
Boolean outAcceptsItem;
if (!PyArg_ParseTuple(_args, "O&O&ll",
CFURLRefObj_Convert, &inItemURL,
CFURLRefObj_Convert, &inTargetURL,
&inRoleMask,
&inFlags))
return NULL;
_err = LSCanURLAcceptURL(inItemURL,
inTargetURL,
inRoleMask,
inFlags,
&outAcceptsItem);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("b",
outAcceptsItem);
return _res;
}
static PyObject *Launch_LSOpenFSRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
FSRef outLaunchedRef;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inRef))
return NULL;
_err = LSOpenFSRef(&inRef,
&outLaunchedRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildFSRef, &outLaunchedRef);
return _res;
PyObject *_res = NULL;
OSStatus _err;
FSRef inRef;
FSRef outLaunchedRef;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetFSRef, &inRef))
return NULL;
_err = LSOpenFSRef(&inRef,
&outLaunchedRef);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
PyMac_BuildFSRef, &outLaunchedRef);
return _res;
}
static PyObject *Launch_LSOpenCFURLRef(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFURLRef outLaunchedURL;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSOpenCFURLRef(inURL,
&outLaunchedURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFURLRefObj_New, outLaunchedURL);
return _res;
PyObject *_res = NULL;
OSStatus _err;
CFURLRef inURL;
CFURLRef outLaunchedURL;
if (!PyArg_ParseTuple(_args, "O&",
CFURLRefObj_Convert, &inURL))
return NULL;
_err = LSOpenCFURLRef(inURL,
&outLaunchedURL);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
CFURLRefObj_New, outLaunchedURL);
return _res;
}
static PyMethodDef Launch_methods[] = {
{"LSCopyItemInfoForRef", (PyCFunction)Launch_LSCopyItemInfoForRef, 1,
PyDoc_STR("(FSRef inItemRef, LSRequestedInfo inWhichInfo) -> (LSItemInfoRecord outItemInfo)")},
{"LSCopyItemInfoForURL", (PyCFunction)Launch_LSCopyItemInfoForURL, 1,
PyDoc_STR("(CFURLRef inURL, LSRequestedInfo inWhichInfo) -> (LSItemInfoRecord outItemInfo)")},
{"LSGetExtensionInfo", (PyCFunction)Launch_LSGetExtensionInfo, 1,
PyDoc_STR("(Buffer inNameLen) -> (UniCharCount outExtStartIndex)")},
{"LSCopyDisplayNameForRef", (PyCFunction)Launch_LSCopyDisplayNameForRef, 1,
PyDoc_STR("(FSRef inRef) -> (CFStringRef outDisplayName)")},
{"LSCopyDisplayNameForURL", (PyCFunction)Launch_LSCopyDisplayNameForURL, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFStringRef outDisplayName)")},
{"LSSetExtensionHiddenForRef", (PyCFunction)Launch_LSSetExtensionHiddenForRef, 1,
PyDoc_STR("(FSRef inRef, Boolean inHide) -> None")},
{"LSSetExtensionHiddenForURL", (PyCFunction)Launch_LSSetExtensionHiddenForURL, 1,
PyDoc_STR("(CFURLRef inURL, Boolean inHide) -> None")},
{"LSCopyKindStringForRef", (PyCFunction)Launch_LSCopyKindStringForRef, 1,
PyDoc_STR("(FSRef inFSRef) -> (CFStringRef outKindString)")},
{"LSCopyKindStringForURL", (PyCFunction)Launch_LSCopyKindStringForURL, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFStringRef outKindString)")},
{"LSGetApplicationForItem", (PyCFunction)Launch_LSGetApplicationForItem, 1,
PyDoc_STR("(FSRef inItemRef, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSGetApplicationForInfo", (PyCFunction)Launch_LSGetApplicationForInfo, 1,
PyDoc_STR("(OSType inType, OSType inCreator, CFStringRef inExtension, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSGetApplicationForURL", (PyCFunction)Launch_LSGetApplicationForURL, 1,
PyDoc_STR("(CFURLRef inURL, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSFindApplicationForInfo", (PyCFunction)Launch_LSFindApplicationForInfo, 1,
PyDoc_STR("(OSType inCreator, CFStringRef inBundleID, CFStringRef inName) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSCanRefAcceptItem", (PyCFunction)Launch_LSCanRefAcceptItem, 1,
PyDoc_STR("(FSRef inItemFSRef, FSRef inTargetRef, LSRolesMask inRoleMask, LSAcceptanceFlags inFlags) -> (Boolean outAcceptsItem)")},
{"LSCanURLAcceptURL", (PyCFunction)Launch_LSCanURLAcceptURL, 1,
PyDoc_STR("(CFURLRef inItemURL, CFURLRef inTargetURL, LSRolesMask inRoleMask, LSAcceptanceFlags inFlags) -> (Boolean outAcceptsItem)")},
{"LSOpenFSRef", (PyCFunction)Launch_LSOpenFSRef, 1,
PyDoc_STR("(FSRef inRef) -> (FSRef outLaunchedRef)")},
{"LSOpenCFURLRef", (PyCFunction)Launch_LSOpenCFURLRef, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFURLRef outLaunchedURL)")},
{NULL, NULL, 0}
{"LSCopyItemInfoForRef", (PyCFunction)Launch_LSCopyItemInfoForRef, 1,
PyDoc_STR("(FSRef inItemRef, LSRequestedInfo inWhichInfo) -> (LSItemInfoRecord outItemInfo)")},
{"LSCopyItemInfoForURL", (PyCFunction)Launch_LSCopyItemInfoForURL, 1,
PyDoc_STR("(CFURLRef inURL, LSRequestedInfo inWhichInfo) -> (LSItemInfoRecord outItemInfo)")},
{"LSGetExtensionInfo", (PyCFunction)Launch_LSGetExtensionInfo, 1,
PyDoc_STR("(Buffer inNameLen) -> (UniCharCount outExtStartIndex)")},
{"LSCopyDisplayNameForRef", (PyCFunction)Launch_LSCopyDisplayNameForRef, 1,
PyDoc_STR("(FSRef inRef) -> (CFStringRef outDisplayName)")},
{"LSCopyDisplayNameForURL", (PyCFunction)Launch_LSCopyDisplayNameForURL, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFStringRef outDisplayName)")},
{"LSSetExtensionHiddenForRef", (PyCFunction)Launch_LSSetExtensionHiddenForRef, 1,
PyDoc_STR("(FSRef inRef, Boolean inHide) -> None")},
{"LSSetExtensionHiddenForURL", (PyCFunction)Launch_LSSetExtensionHiddenForURL, 1,
PyDoc_STR("(CFURLRef inURL, Boolean inHide) -> None")},
{"LSCopyKindStringForRef", (PyCFunction)Launch_LSCopyKindStringForRef, 1,
PyDoc_STR("(FSRef inFSRef) -> (CFStringRef outKindString)")},
{"LSCopyKindStringForURL", (PyCFunction)Launch_LSCopyKindStringForURL, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFStringRef outKindString)")},
{"LSGetApplicationForItem", (PyCFunction)Launch_LSGetApplicationForItem, 1,
PyDoc_STR("(FSRef inItemRef, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSGetApplicationForInfo", (PyCFunction)Launch_LSGetApplicationForInfo, 1,
PyDoc_STR("(OSType inType, OSType inCreator, CFStringRef inExtension, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSGetApplicationForURL", (PyCFunction)Launch_LSGetApplicationForURL, 1,
PyDoc_STR("(CFURLRef inURL, LSRolesMask inRoleMask) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSFindApplicationForInfo", (PyCFunction)Launch_LSFindApplicationForInfo, 1,
PyDoc_STR("(OSType inCreator, CFStringRef inBundleID, CFStringRef inName) -> (FSRef outAppRef, CFURLRef outAppURL)")},
{"LSCanRefAcceptItem", (PyCFunction)Launch_LSCanRefAcceptItem, 1,
PyDoc_STR("(FSRef inItemFSRef, FSRef inTargetRef, LSRolesMask inRoleMask, LSAcceptanceFlags inFlags) -> (Boolean outAcceptsItem)")},
{"LSCanURLAcceptURL", (PyCFunction)Launch_LSCanURLAcceptURL, 1,
PyDoc_STR("(CFURLRef inItemURL, CFURLRef inTargetURL, LSRolesMask inRoleMask, LSAcceptanceFlags inFlags) -> (Boolean outAcceptsItem)")},
{"LSOpenFSRef", (PyCFunction)Launch_LSOpenFSRef, 1,
PyDoc_STR("(FSRef inRef) -> (FSRef outLaunchedRef)")},
{"LSOpenCFURLRef", (PyCFunction)Launch_LSOpenCFURLRef, 1,
PyDoc_STR("(CFURLRef inURL) -> (CFURLRef outLaunchedURL)")},
{NULL, NULL, 0}
};
@ -463,18 +463,18 @@ static PyMethodDef Launch_methods[] = {
void init_Launch(void)
{
PyObject *m;
PyObject *d;
PyObject *m;
PyObject *d;
m = Py_InitModule("_Launch", Launch_methods);
d = PyModule_GetDict(m);
Launch_Error = PyMac_GetOSErrException();
if (Launch_Error == NULL ||
PyDict_SetItemString(d, "Error", Launch_Error) != 0)
return;
m = Py_InitModule("_Launch", Launch_methods);
d = PyModule_GetDict(m);
Launch_Error = PyMac_GetOSErrException();
if (Launch_Error == NULL ||
PyDict_SetItemString(d, "Error", Launch_Error) != 0)
return;
}
/* ======================= End module _Launch ======================= */

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,9 @@
/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
PyErr_SetString(PyExc_NotImplementedError, \
"Not available in this shared library/OS version"); \
return NULL; \
}} while(0)
@ -27,199 +27,199 @@ PyTypeObject Scrap_Type;
#define ScrapObj_Check(x) ((x)->ob_type == &Scrap_Type || PyObject_TypeCheck((x), &Scrap_Type))
typedef struct ScrapObject {
PyObject_HEAD
ScrapRef ob_itself;
PyObject_HEAD
ScrapRef ob_itself;
} ScrapObject;
PyObject *ScrapObj_New(ScrapRef itself)
{
ScrapObject *it;
it = PyObject_NEW(ScrapObject, &Scrap_Type);
if (it == NULL) return NULL;
it->ob_itself = itself;
return (PyObject *)it;
ScrapObject *it;
it = PyObject_NEW(ScrapObject, &Scrap_Type);
if (it == NULL) return NULL;
it->ob_itself = itself;
return (PyObject *)it;
}
int ScrapObj_Convert(PyObject *v, ScrapRef *p_itself)
{
if (!ScrapObj_Check(v))
{
PyErr_SetString(PyExc_TypeError, "Scrap required");
return 0;
}
*p_itself = ((ScrapObject *)v)->ob_itself;
return 1;
if (!ScrapObj_Check(v))
{
PyErr_SetString(PyExc_TypeError, "Scrap required");
return 0;
}
*p_itself = ((ScrapObject *)v)->ob_itself;
return 1;
}
static void ScrapObj_dealloc(ScrapObject *self)
{
/* Cleanup of self->ob_itself goes here */
self->ob_type->tp_free((PyObject *)self);
/* Cleanup of self->ob_itself goes here */
self->ob_type->tp_free((PyObject *)self);
}
static PyObject *ScrapObj_GetScrapFlavorFlags(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
ScrapFlavorFlags flavorFlags;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorFlags(_self->ob_itself,
flavorType,
&flavorFlags);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
flavorFlags);
return _res;
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
ScrapFlavorFlags flavorFlags;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorFlags(_self->ob_itself,
flavorType,
&flavorFlags);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
flavorFlags);
return _res;
}
static PyObject *ScrapObj_GetScrapFlavorSize(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
Size byteCount;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorSize(_self->ob_itself,
flavorType,
&byteCount);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
byteCount);
return _res;
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
Size byteCount;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorSize(_self->ob_itself,
flavorType,
&byteCount);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
byteCount);
return _res;
}
static PyObject *ScrapObj_GetScrapFlavorData(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
Size byteCount;
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
Size byteCount;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorSize(_self->ob_itself,
flavorType,
&byteCount);
if (_err != noErr) return PyMac_Error(_err);
_res = PyString_FromStringAndSize(NULL, (int)byteCount);
if ( _res == NULL ) return NULL;
_err = GetScrapFlavorData(_self->ob_itself,
flavorType,
&byteCount,
PyString_AS_STRING(_res));
if (_err != noErr) {
Py_XDECREF(_res);
return PyMac_Error(_err);
}
return _res;
if (!PyArg_ParseTuple(_args, "O&",
PyMac_GetOSType, &flavorType))
return NULL;
_err = GetScrapFlavorSize(_self->ob_itself,
flavorType,
&byteCount);
if (_err != noErr) return PyMac_Error(_err);
_res = PyString_FromStringAndSize(NULL, (int)byteCount);
if ( _res == NULL ) return NULL;
_err = GetScrapFlavorData(_self->ob_itself,
flavorType,
&byteCount,
PyString_AS_STRING(_res));
if (_err != noErr) {
Py_XDECREF(_res);
return PyMac_Error(_err);
}
return _res;
}
static PyObject *ScrapObj_PutScrapFlavor(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
ScrapFlavorFlags flavorFlags;
char *flavorData__in__;
int flavorData__in_len__;
if (!PyArg_ParseTuple(_args, "O&Ks#",
PyMac_GetOSType, &flavorType,
&flavorFlags,
&flavorData__in__, &flavorData__in_len__))
return NULL;
_err = PutScrapFlavor(_self->ob_itself,
flavorType,
flavorFlags,
(Size)flavorData__in_len__,
flavorData__in__);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
ScrapFlavorType flavorType;
ScrapFlavorFlags flavorFlags;
char *flavorData__in__;
int flavorData__in_len__;
if (!PyArg_ParseTuple(_args, "O&Ks#",
PyMac_GetOSType, &flavorType,
&flavorFlags,
&flavorData__in__, &flavorData__in_len__))
return NULL;
_err = PutScrapFlavor(_self->ob_itself,
flavorType,
flavorFlags,
(Size)flavorData__in_len__,
flavorData__in__);
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *ScrapObj_GetScrapFlavorCount(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
UInt32 infoCount;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetScrapFlavorCount(_self->ob_itself,
&infoCount);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
infoCount);
return _res;
PyObject *_res = NULL;
OSStatus _err;
UInt32 infoCount;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetScrapFlavorCount(_self->ob_itself,
&infoCount);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("l",
infoCount);
return _res;
}
static PyObject *ScrapObj_GetScrapFlavorInfoList(ScrapObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
PyObject *item;
OSStatus _err;
UInt32 infoCount;
ScrapFlavorInfo *infolist = NULL;
int i;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetScrapFlavorCount(_self->ob_itself,
&infoCount);
if (_err != noErr) return PyMac_Error(_err);
if (infoCount == 0) return Py_BuildValue("[]");
if ((infolist = (ScrapFlavorInfo *)malloc(infoCount*sizeof(ScrapFlavorInfo))) == NULL )
return PyErr_NoMemory();
_err = GetScrapFlavorInfoList(_self->ob_itself, &infoCount, infolist);
if (_err != noErr) {
free(infolist);
return NULL;
}
if ((_res = PyList_New(infoCount)) == NULL ) {
free(infolist);
return NULL;
}
for(i=0; i<infoCount; i++) {
item = Py_BuildValue("O&l", PyMac_BuildOSType, infolist[i].flavorType,
infolist[i].flavorFlags);
if ( !item || PyList_SetItem(_res, i, item) < 0 ) {
Py_DECREF(_res);
free(infolist);
return NULL;
}
}
free(infolist);
return _res;
PyObject *_res = NULL;
PyObject *item;
OSStatus _err;
UInt32 infoCount;
ScrapFlavorInfo *infolist = NULL;
int i;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetScrapFlavorCount(_self->ob_itself,
&infoCount);
if (_err != noErr) return PyMac_Error(_err);
if (infoCount == 0) return Py_BuildValue("[]");
if ((infolist = (ScrapFlavorInfo *)malloc(infoCount*sizeof(ScrapFlavorInfo))) == NULL )
return PyErr_NoMemory();
_err = GetScrapFlavorInfoList(_self->ob_itself, &infoCount, infolist);
if (_err != noErr) {
free(infolist);
return NULL;
}
if ((_res = PyList_New(infoCount)) == NULL ) {
free(infolist);
return NULL;
}
for(i=0; i<infoCount; i++) {
item = Py_BuildValue("O&l", PyMac_BuildOSType, infolist[i].flavorType,
infolist[i].flavorFlags);
if ( !item || PyList_SetItem(_res, i, item) < 0 ) {
Py_DECREF(_res);
free(infolist);
return NULL;
}
}
free(infolist);
return _res;
}
static PyMethodDef ScrapObj_methods[] = {
{"GetScrapFlavorFlags", (PyCFunction)ScrapObj_GetScrapFlavorFlags, 1,
PyDoc_STR("(ScrapFlavorType flavorType) -> (ScrapFlavorFlags flavorFlags)")},
{"GetScrapFlavorSize", (PyCFunction)ScrapObj_GetScrapFlavorSize, 1,
PyDoc_STR("(ScrapFlavorType flavorType) -> (Size byteCount)")},
{"GetScrapFlavorData", (PyCFunction)ScrapObj_GetScrapFlavorData, 1,
PyDoc_STR("(ScrapFlavorType flavorType, Buffer destination) -> (Size byteCount)")},
{"PutScrapFlavor", (PyCFunction)ScrapObj_PutScrapFlavor, 1,
PyDoc_STR("(ScrapFlavorType flavorType, ScrapFlavorFlags flavorFlags, Size flavorSize, Buffer flavorData) -> None")},
{"GetScrapFlavorCount", (PyCFunction)ScrapObj_GetScrapFlavorCount, 1,
PyDoc_STR("() -> (UInt32 infoCount)")},
{"GetScrapFlavorInfoList", (PyCFunction)ScrapObj_GetScrapFlavorInfoList, 1,
PyDoc_STR("() -> ([(ScrapFlavorType, ScrapFlavorInfo), ...])")},
{NULL, NULL, 0}
{"GetScrapFlavorFlags", (PyCFunction)ScrapObj_GetScrapFlavorFlags, 1,
PyDoc_STR("(ScrapFlavorType flavorType) -> (ScrapFlavorFlags flavorFlags)")},
{"GetScrapFlavorSize", (PyCFunction)ScrapObj_GetScrapFlavorSize, 1,
PyDoc_STR("(ScrapFlavorType flavorType) -> (Size byteCount)")},
{"GetScrapFlavorData", (PyCFunction)ScrapObj_GetScrapFlavorData, 1,
PyDoc_STR("(ScrapFlavorType flavorType, Buffer destination) -> (Size byteCount)")},
{"PutScrapFlavor", (PyCFunction)ScrapObj_PutScrapFlavor, 1,
PyDoc_STR("(ScrapFlavorType flavorType, ScrapFlavorFlags flavorFlags, Size flavorSize, Buffer flavorData) -> None")},
{"GetScrapFlavorCount", (PyCFunction)ScrapObj_GetScrapFlavorCount, 1,
PyDoc_STR("() -> (UInt32 infoCount)")},
{"GetScrapFlavorInfoList", (PyCFunction)ScrapObj_GetScrapFlavorInfoList, 1,
PyDoc_STR("() -> ([(ScrapFlavorType, ScrapFlavorInfo), ...])")},
{NULL, NULL, 0}
};
PyMethodChain ScrapObj_chain = { ScrapObj_methods, NULL };
static PyObject *ScrapObj_getattr(ScrapObject *self, char *name)
{
return Py_FindMethodInChain(&ScrapObj_chain, (PyObject *)self, name);
return Py_FindMethodInChain(&ScrapObj_chain, (PyObject *)self, name);
}
#define ScrapObj_setattr NULL
@ -231,107 +231,107 @@ static PyObject *ScrapObj_getattr(ScrapObject *self, char *name)
#define ScrapObj_hash NULL
PyTypeObject Scrap_Type = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"_Scrap.Scrap", /*tp_name*/
sizeof(ScrapObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor) ScrapObj_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc) ScrapObj_getattr, /*tp_getattr*/
(setattrfunc) ScrapObj_setattr, /*tp_setattr*/
(cmpfunc) ScrapObj_compare, /*tp_compare*/
(reprfunc) ScrapObj_repr, /*tp_repr*/
(PyNumberMethods *)0, /* tp_as_number */
(PySequenceMethods *)0, /* tp_as_sequence */
(PyMappingMethods *)0, /* tp_as_mapping */
(hashfunc) ScrapObj_hash, /*tp_hash*/
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"_Scrap.Scrap", /*tp_name*/
sizeof(ScrapObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor) ScrapObj_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc) ScrapObj_getattr, /*tp_getattr*/
(setattrfunc) ScrapObj_setattr, /*tp_setattr*/
(cmpfunc) ScrapObj_compare, /*tp_compare*/
(reprfunc) ScrapObj_repr, /*tp_repr*/
(PyNumberMethods *)0, /* tp_as_number */
(PySequenceMethods *)0, /* tp_as_sequence */
(PyMappingMethods *)0, /* tp_as_mapping */
(hashfunc) ScrapObj_hash, /*tp_hash*/
};
/* --------------------- End object type Scrap ---------------------- */
static PyObject *Scrap_LoadScrap(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = LoadScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = LoadScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Scrap_UnloadScrap(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = UnloadScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = UnloadScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Scrap_GetCurrentScrap(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
ScrapRef scrap;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetCurrentScrap(&scrap);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
ScrapObj_New, scrap);
return _res;
PyObject *_res = NULL;
OSStatus _err;
ScrapRef scrap;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = GetCurrentScrap(&scrap);
if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&",
ScrapObj_New, scrap);
return _res;
}
static PyObject *Scrap_ClearCurrentScrap(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = ClearCurrentScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = ClearCurrentScrap();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
static PyObject *Scrap_CallInScrapPromises(PyObject *_self, PyObject *_args)
{
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = CallInScrapPromises();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
PyObject *_res = NULL;
OSStatus _err;
if (!PyArg_ParseTuple(_args, ""))
return NULL;
_err = CallInScrapPromises();
if (_err != noErr) return PyMac_Error(_err);
Py_INCREF(Py_None);
_res = Py_None;
return _res;
}
#endif /* __LP64__ */
static PyMethodDef Scrap_methods[] = {
#ifndef __LP64__
{"LoadScrap", (PyCFunction)Scrap_LoadScrap, 1,
PyDoc_STR("() -> None")},
{"UnloadScrap", (PyCFunction)Scrap_UnloadScrap, 1,
PyDoc_STR("() -> None")},
{"GetCurrentScrap", (PyCFunction)Scrap_GetCurrentScrap, 1,
PyDoc_STR("() -> (ScrapRef scrap)")},
{"ClearCurrentScrap", (PyCFunction)Scrap_ClearCurrentScrap, 1,
PyDoc_STR("() -> None")},
{"CallInScrapPromises", (PyCFunction)Scrap_CallInScrapPromises, 1,
PyDoc_STR("() -> None")},
{"LoadScrap", (PyCFunction)Scrap_LoadScrap, 1,
PyDoc_STR("() -> None")},
{"UnloadScrap", (PyCFunction)Scrap_UnloadScrap, 1,
PyDoc_STR("() -> None")},
{"GetCurrentScrap", (PyCFunction)Scrap_GetCurrentScrap, 1,
PyDoc_STR("() -> (ScrapRef scrap)")},
{"ClearCurrentScrap", (PyCFunction)Scrap_ClearCurrentScrap, 1,
PyDoc_STR("() -> None")},
{"CallInScrapPromises", (PyCFunction)Scrap_CallInScrapPromises, 1,
PyDoc_STR("() -> None")},
#endif /* __LP64__ */
{NULL, NULL, 0}
{NULL, NULL, 0}
};
@ -339,25 +339,25 @@ static PyMethodDef Scrap_methods[] = {
void init_Scrap(void)
{
PyObject *m;
PyObject *m;
#ifndef __LP64__
PyObject *d;
PyObject *d;
#endif /* __LP64__ */
m = Py_InitModule("_Scrap", Scrap_methods);
m = Py_InitModule("_Scrap", Scrap_methods);
#ifndef __LP64__
d = PyModule_GetDict(m);
Scrap_Error = PyMac_GetOSErrException();
if (Scrap_Error == NULL ||
PyDict_SetItemString(d, "Error", Scrap_Error) != 0)
return;
Scrap_Type.ob_type = &PyType_Type;
Py_INCREF(&Scrap_Type);
if (PyDict_SetItemString(d, "ScrapType", (PyObject *)&Scrap_Type) != 0)
Py_FatalError("can't initialize ScrapType");
d = PyModule_GetDict(m);
Scrap_Error = PyMac_GetOSErrException();
if (Scrap_Error == NULL ||
PyDict_SetItemString(d, "Error", Scrap_Error) != 0)
return;
Scrap_Type.ob_type = &PyType_Type;
Py_INCREF(&Scrap_Type);
if (PyDict_SetItemString(d, "ScrapType", (PyObject *)&Scrap_Type) != 0)
Py_FatalError("can't initialize ScrapType");
#endif /* __LP64__ */
}

View file

@ -35,13 +35,13 @@ PERFORMANCE OF THIS SOFTWARE.
#pragma options align=mac68k
struct SampleRateAvailable_arg {
short numrates;
Handle rates;
short numrates;
Handle rates;
};
struct SampleSizeAvailable_arg {
short numsizes;
Handle sizes;
short numsizes;
Handle sizes;
};
#pragma options align=reset
@ -53,28 +53,28 @@ static PyObject *ErrorObject;
static int
PyMac_GetUFixed(PyObject *v, Fixed *f)
{
double d;
unsigned long uns;
if( !PyArg_Parse(v, "d", &d))
return 0;
uns = (unsigned long)(d * 0x10000);
*f = (Fixed)uns;
return 1;
double d;
unsigned long uns;
if( !PyArg_Parse(v, "d", &d))
return 0;
uns = (unsigned long)(d * 0x10000);
*f = (Fixed)uns;
return 1;
}
/* Convert a Point to a Python object */
static PyObject *
PyMac_BuildUFixed(Fixed f)
{
double d;
unsigned long funs;
funs = (unsigned long)f;
d = funs;
d = d / 0x10000;
return Py_BuildValue("d", d);
double d;
unsigned long funs;
funs = (unsigned long)f;
d = funs;
d = d / 0x10000;
return Py_BuildValue("d", d);
}
@ -86,19 +86,19 @@ static char sndih_getChannelAvailable__doc__[] =
static PyObject *
sndih_getChannelAvailable(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short nchannel;
OSErr err;
long inRefNum;
short nchannel;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siChannelAvailable, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", nchannel);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siChannelAvailable, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", nchannel);
}
static char sndih_getNumberChannels__doc__[] =
@ -107,19 +107,19 @@ static char sndih_getNumberChannels__doc__[] =
static PyObject *
sndih_getNumberChannels(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short nchannel;
OSErr err;
long inRefNum;
short nchannel;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siNumberChannels, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", nchannel);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siNumberChannels, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", nchannel);
}
static char sndih_setNumberChannels__doc__[] =
@ -128,20 +128,20 @@ static char sndih_setNumberChannels__doc__[] =
static PyObject *
sndih_setNumberChannels(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short nchannel;
OSErr err;
long inRefNum;
short nchannel;
OSErr err;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &nchannel))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siNumberChannels, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &nchannel))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siNumberChannels, (Ptr)&nchannel)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getContinuous__doc__[] =
@ -150,19 +150,19 @@ static char sndih_getContinuous__doc__[] =
static PyObject *
sndih_getContinuous(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short onoff;
OSErr err;
long inRefNum;
short onoff;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siContinuous, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", onoff);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siContinuous, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", onoff);
}
static char sndih_setContinuous__doc__[] =
@ -171,20 +171,20 @@ static char sndih_setContinuous__doc__[] =
static PyObject *
sndih_setContinuous(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short onoff;
OSErr err;
long inRefNum;
short onoff;
OSErr err;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &onoff))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siContinuous, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &onoff))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siContinuous, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getInputSourceNames__doc__[] =
@ -193,19 +193,19 @@ static char sndih_getInputSourceNames__doc__[] =
static PyObject *
sndih_getInputSourceNames(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
Handle names;
OSErr err;
long inRefNum;
Handle names;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siInputSourceNames, (Ptr)&names)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("O&", ResObj_New, names);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siInputSourceNames, (Ptr)&names)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("O&", ResObj_New, names);
}
static char sndih_getInputSource__doc__[] =
@ -214,19 +214,19 @@ static char sndih_getInputSource__doc__[] =
static PyObject *
sndih_getInputSource(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short source;
OSErr err;
long inRefNum;
short source;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siInputSource, (Ptr)&source)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", source);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siInputSource, (Ptr)&source)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", source);
}
static char sndih_setInputSource__doc__[] =
@ -235,20 +235,20 @@ static char sndih_setInputSource__doc__[] =
static PyObject *
sndih_setInputSource(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short source;
OSErr err;
long inRefNum;
short source;
OSErr err;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &source))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siInputSource, (Ptr)&source)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &source))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siInputSource, (Ptr)&source)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getPlayThruOnOff__doc__[] =
@ -257,19 +257,19 @@ static char sndih_getPlayThruOnOff__doc__[] =
static PyObject *
sndih_getPlayThruOnOff(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short onoff;
OSErr err;
long inRefNum;
short onoff;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siPlayThruOnOff, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", onoff);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siPlayThruOnOff, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", onoff);
}
static char sndih_setPlayThruOnOff__doc__[] =
@ -278,20 +278,20 @@ static char sndih_setPlayThruOnOff__doc__[] =
static PyObject *
sndih_setPlayThruOnOff(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short onoff;
OSErr err;
long inRefNum;
short onoff;
OSErr err;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &onoff))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siPlayThruOnOff, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &onoff))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siPlayThruOnOff, (Ptr)&onoff)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getSampleRate__doc__[] =
@ -300,19 +300,19 @@ static char sndih_getSampleRate__doc__[] =
static PyObject *
sndih_getSampleRate(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
Fixed sample_rate;
OSErr err;
long inRefNum;
Fixed sample_rate;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleRate, (Ptr)&sample_rate)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("O&", PyMac_BuildUFixed, sample_rate);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleRate, (Ptr)&sample_rate)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("O&", PyMac_BuildUFixed, sample_rate);
}
static char sndih_setSampleRate__doc__[] =
@ -321,20 +321,20 @@ static char sndih_setSampleRate__doc__[] =
static PyObject *
sndih_setSampleRate(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
Fixed sample_rate;
OSErr err;
long inRefNum;
Fixed sample_rate;
OSErr err;
if (!PyArg_ParseTuple(args, "lO&", &inRefNum, PyMac_GetUFixed, &sample_rate))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siSampleRate, (Ptr)&sample_rate)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lO&", &inRefNum, PyMac_GetUFixed, &sample_rate))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siSampleRate, (Ptr)&sample_rate)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getSampleSize__doc__[] =
@ -343,19 +343,19 @@ static char sndih_getSampleSize__doc__[] =
static PyObject *
sndih_getSampleSize(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short bits;
OSErr err;
long inRefNum;
short bits;
OSErr err;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleSize, (Ptr)&bits)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", bits);
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleSize, (Ptr)&bits)) != noErr )
return PyMac_Error(err);
return Py_BuildValue("h", bits);
}
static char sndih_setSampleSize__doc__[] =
@ -364,20 +364,20 @@ static char sndih_setSampleSize__doc__[] =
static PyObject *
sndih_setSampleSize(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
short size;
OSErr err;
long inRefNum;
short size;
OSErr err;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &size))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siSampleSize, (Ptr)&size)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
if (!PyArg_ParseTuple(args, "lh", &inRefNum, &size))
return NULL;
if( (err=SPBSetDeviceInfo(inRefNum, siSampleSize, (Ptr)&size)) != noErr )
return PyMac_Error(err);
Py_INCREF(Py_None);
return Py_None;
}
static char sndih_getSampleSizeAvailable__doc__[] =
@ -386,31 +386,31 @@ static char sndih_getSampleSizeAvailable__doc__[] =
static PyObject *
sndih_getSampleSizeAvailable(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
struct SampleSizeAvailable_arg arg;
OSErr err;
PyObject *rsizes;
short *fsizes;
int i;
long inRefNum;
struct SampleSizeAvailable_arg arg;
OSErr err;
PyObject *rsizes;
short *fsizes;
int i;
arg.sizes = NULL;
rsizes = NULL;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleSizeAvailable, (Ptr)&arg)) != noErr ) {
return PyMac_Error(err);
}
fsizes = (short *)*(arg.sizes);
/* Handle contains a list of rates */
if( (rsizes = PyTuple_New(arg.numsizes)) == NULL)
return NULL;
for( i=0; i<arg.numsizes; i++ )
PyTuple_SetItem(rsizes, i, PyInt_FromLong((long)fsizes[i]));
return rsizes;
arg.sizes = NULL;
rsizes = NULL;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleSizeAvailable, (Ptr)&arg)) != noErr ) {
return PyMac_Error(err);
}
fsizes = (short *)*(arg.sizes);
/* Handle contains a list of rates */
if( (rsizes = PyTuple_New(arg.numsizes)) == NULL)
return NULL;
for( i=0; i<arg.numsizes; i++ )
PyTuple_SetItem(rsizes, i, PyInt_FromLong((long)fsizes[i]));
return rsizes;
}
static char sndih_getSampleRateAvailable__doc__[] =
@ -419,94 +419,94 @@ static char sndih_getSampleRateAvailable__doc__[] =
static PyObject *
sndih_getSampleRateAvailable(self, args)
PyObject *self; /* Not used */
PyObject *args;
PyObject *self; /* Not used */
PyObject *args;
{
long inRefNum;
struct SampleRateAvailable_arg arg;
OSErr err;
PyObject *rrates, *obj;
Fixed *frates;
int i;
long inRefNum;
struct SampleRateAvailable_arg arg;
OSErr err;
PyObject *rrates, *obj;
Fixed *frates;
int i;
arg.rates = NULL;
rrates = NULL;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleRateAvailable, (Ptr)&arg)) != noErr ) {
return PyMac_Error(err);
}
frates = (Fixed *)*(arg.rates);
if( arg.numrates == 0 ) {
/* The handle contains upper and lowerbound */
rrates = Py_BuildValue("O&O&", frates[0], frates[1]);
if (rrates == NULL) return NULL;
} else {
/* Handle contains a list of rates */
if( (rrates = PyTuple_New(arg.numrates)) == NULL)
return NULL;
for( i=0; i<arg.numrates; i++ ) {
if( (obj = Py_BuildValue("O&", PyMac_BuildUFixed, frates[i]))==NULL)
goto out;
PyTuple_SetItem(rrates, i, obj);
}
}
return Py_BuildValue("hO", arg.numrates, rrates);
arg.rates = NULL;
rrates = NULL;
if (!PyArg_ParseTuple(args, "l", &inRefNum))
return NULL;
if( (err=SPBGetDeviceInfo(inRefNum, siSampleRateAvailable, (Ptr)&arg)) != noErr ) {
return PyMac_Error(err);
}
frates = (Fixed *)*(arg.rates);
if( arg.numrates == 0 ) {
/* The handle contains upper and lowerbound */
rrates = Py_BuildValue("O&O&", frates[0], frates[1]);
if (rrates == NULL) return NULL;
} else {
/* Handle contains a list of rates */
if( (rrates = PyTuple_New(arg.numrates)) == NULL)
return NULL;
for( i=0; i<arg.numrates; i++ ) {
if( (obj = Py_BuildValue("O&", PyMac_BuildUFixed, frates[i]))==NULL)
goto out;
PyTuple_SetItem(rrates, i, obj);
}
}
return Py_BuildValue("hO", arg.numrates, rrates);
out:
Py_XDECREF(rrates);
return NULL;
Py_XDECREF(rrates);
return NULL;
}
/* List of methods defined in the module */
static struct PyMethodDef sndih_methods[] = {
{"getChannelAvailable", (PyCFunction)sndih_getChannelAvailable, METH_VARARGS, sndih_getChannelAvailable__doc__},
{"getNumberChannels", (PyCFunction)sndih_getNumberChannels, METH_VARARGS, sndih_getNumberChannels__doc__},
{"setNumberChannels", (PyCFunction)sndih_setNumberChannels, METH_VARARGS, sndih_setNumberChannels__doc__},
{"getContinuous", (PyCFunction)sndih_getContinuous, METH_VARARGS, sndih_getContinuous__doc__},
{"setContinuous", (PyCFunction)sndih_setContinuous, METH_VARARGS, sndih_setContinuous__doc__},
{"getInputSourceNames", (PyCFunction)sndih_getInputSourceNames, METH_VARARGS, sndih_getInputSourceNames__doc__},
{"getInputSource", (PyCFunction)sndih_getInputSource, METH_VARARGS, sndih_getInputSource__doc__},
{"setInputSource", (PyCFunction)sndih_setInputSource, METH_VARARGS, sndih_setInputSource__doc__},
{"getPlayThruOnOff", (PyCFunction)sndih_getPlayThruOnOff, METH_VARARGS, sndih_getPlayThruOnOff__doc__},
{"setPlayThruOnOff", (PyCFunction)sndih_setPlayThruOnOff, METH_VARARGS, sndih_setPlayThruOnOff__doc__},
{"getSampleRate", (PyCFunction)sndih_getSampleRate, METH_VARARGS, sndih_getSampleRate__doc__},
{"setSampleRate", (PyCFunction)sndih_setSampleRate, METH_VARARGS, sndih_setSampleRate__doc__},
{"getSampleSize", (PyCFunction)sndih_getSampleSize, METH_VARARGS, sndih_getSampleSize__doc__},
{"setSampleSize", (PyCFunction)sndih_setSampleSize, METH_VARARGS, sndih_setSampleSize__doc__},
{"getSampleSizeAvailable", (PyCFunction)sndih_getSampleSizeAvailable, METH_VARARGS, sndih_getSampleSizeAvailable__doc__},
{"getSampleRateAvailable", (PyCFunction)sndih_getSampleRateAvailable, METH_VARARGS, sndih_getSampleRateAvailable__doc__},
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
{"getChannelAvailable", (PyCFunction)sndih_getChannelAvailable, METH_VARARGS, sndih_getChannelAvailable__doc__},
{"getNumberChannels", (PyCFunction)sndih_getNumberChannels, METH_VARARGS, sndih_getNumberChannels__doc__},
{"setNumberChannels", (PyCFunction)sndih_setNumberChannels, METH_VARARGS, sndih_setNumberChannels__doc__},
{"getContinuous", (PyCFunction)sndih_getContinuous, METH_VARARGS, sndih_getContinuous__doc__},
{"setContinuous", (PyCFunction)sndih_setContinuous, METH_VARARGS, sndih_setContinuous__doc__},
{"getInputSourceNames", (PyCFunction)sndih_getInputSourceNames, METH_VARARGS, sndih_getInputSourceNames__doc__},
{"getInputSource", (PyCFunction)sndih_getInputSource, METH_VARARGS, sndih_getInputSource__doc__},
{"setInputSource", (PyCFunction)sndih_setInputSource, METH_VARARGS, sndih_setInputSource__doc__},
{"getPlayThruOnOff", (PyCFunction)sndih_getPlayThruOnOff, METH_VARARGS, sndih_getPlayThruOnOff__doc__},
{"setPlayThruOnOff", (PyCFunction)sndih_setPlayThruOnOff, METH_VARARGS, sndih_setPlayThruOnOff__doc__},
{"getSampleRate", (PyCFunction)sndih_getSampleRate, METH_VARARGS, sndih_getSampleRate__doc__},
{"setSampleRate", (PyCFunction)sndih_setSampleRate, METH_VARARGS, sndih_setSampleRate__doc__},
{"getSampleSize", (PyCFunction)sndih_getSampleSize, METH_VARARGS, sndih_getSampleSize__doc__},
{"setSampleSize", (PyCFunction)sndih_setSampleSize, METH_VARARGS, sndih_setSampleSize__doc__},
{"getSampleSizeAvailable", (PyCFunction)sndih_getSampleSizeAvailable, METH_VARARGS, sndih_getSampleSizeAvailable__doc__},
{"getSampleRateAvailable", (PyCFunction)sndih_getSampleRateAvailable, METH_VARARGS, sndih_getSampleRateAvailable__doc__},
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initSndihooks) */
static char Sndihooks_module_documentation[] =
static char Sndihooks_module_documentation[] =
""
;
void
init_Sndihooks()
{
PyObject *m, *d;
PyObject *m, *d;
/* Create the module and add the functions */
m = Py_InitModule4("_Sndihooks", sndih_methods,
Sndihooks_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
/* Create the module and add the functions */
m = Py_InitModule4("_Sndihooks", sndih_methods,
Sndihooks_module_documentation,
(PyObject*)NULL,PYTHON_API_VERSION);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyString_FromString("Sndihooks.error");
PyDict_SetItemString(d, "error", ErrorObject);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyString_FromString("Sndihooks.error");
PyDict_SetItemString(d, "error", ErrorObject);
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module Sndihooks");
/* XXXX Add constants here */
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module Sndihooks");
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -37,8 +37,8 @@ extern char** environ;
* In a regular framework the structure is:
*
* Python.framework/Versions/2.7
* /Python
* /Resources/Python.app/Contents/MacOS/Python
* /Python
* /Resources/Python.app/Contents/MacOS/Python
*
* In a virtualenv style structure the expected
* structure is:
@ -48,123 +48,123 @@ extern char** environ;
* /.Python <- the dylib
* /.Resources/Python.app/Contents/MacOS/Python
*
* NOTE: virtualenv's are not an officially supported
* NOTE: virtualenv's are not an officially supported
* feature, support for that structure is provided as
* a convenience.
*/
static char* get_python_path(void)
{
size_t len;
Dl_info info;
char* end;
char* g_path;
size_t len;
Dl_info info;
char* end;
char* g_path;
if (dladdr(Py_Initialize, &info) == 0) {
return NULL;
}
if (dladdr(Py_Initialize, &info) == 0) {
return NULL;
}
len = strlen(info.dli_fname);
len = strlen(info.dli_fname);
g_path = malloc(len+60);
if (g_path == NULL) {
return NULL;
}
g_path = malloc(len+60);
if (g_path == NULL) {
return NULL;
}
strcpy(g_path, info.dli_fname);
end = g_path + len - 1;
while (end != g_path && *end != '/') {
end --;
}
end++;
if (*end == '.') {
end++;
}
strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK);
strcpy(g_path, info.dli_fname);
end = g_path + len - 1;
while (end != g_path && *end != '/') {
end --;
}
end++;
if (*end == '.') {
end++;
}
strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK);
return g_path;
return g_path;
}
#ifdef HAVE_SPAWN_H
static void
setup_spawnattr(posix_spawnattr_t* spawnattr)
{
size_t ocount;
size_t count;
cpu_type_t cpu_types[1];
short flags = 0;
size_t ocount;
size_t count;
cpu_type_t cpu_types[1];
short flags = 0;
#ifdef __LP64__
int ch;
int ch;
#endif
if ((errno = posix_spawnattr_init(spawnattr)) != 0) {
err(2, "posix_spawnattr_int");
/* NOTREACHTED */
}
if ((errno = posix_spawnattr_init(spawnattr)) != 0) {
err(2, "posix_spawnattr_int");
/* NOTREACHTED */
}
count = 1;
count = 1;
/* Run the real python executable using the same architure as this
* executable, this allows users to controle the architecture using
* "arch -ppc python"
*/
/* Run the real python executable using the same architure as this
* executable, this allows users to controle the architecture using
* "arch -ppc python"
*/
#if defined(__ppc64__)
cpu_types[0] = CPU_TYPE_POWERPC64;
cpu_types[0] = CPU_TYPE_POWERPC64;
#elif defined(__x86_64__)
cpu_types[0] = CPU_TYPE_X86_64;
cpu_types[0] = CPU_TYPE_X86_64;
#elif defined(__ppc__)
cpu_types[0] = CPU_TYPE_POWERPC;
cpu_types[0] = CPU_TYPE_POWERPC;
#elif defined(__i386__)
cpu_types[0] = CPU_TYPE_X86;
cpu_types[0] = CPU_TYPE_X86;
#else
# error "Unknown CPU"
# error "Unknown CPU"
#endif
if (posix_spawnattr_setbinpref_np(spawnattr, count,
cpu_types, &ocount) == -1) {
err(1, "posix_spawnattr_setbinpref");
/* NOTREACHTED */
}
if (count != ocount) {
fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n");
exit(1);
/* NOTREACHTED */
}
if (posix_spawnattr_setbinpref_np(spawnattr, count,
cpu_types, &ocount) == -1) {
err(1, "posix_spawnattr_setbinpref");
/* NOTREACHTED */
}
if (count != ocount) {
fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n");
exit(1);
/* NOTREACHTED */
}
/*
* Set flag that causes posix_spawn to behave like execv
*/
flags |= POSIX_SPAWN_SETEXEC;
if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) {
err(1, "posix_spawnattr_setflags");
/* NOTREACHTED */
}
/*
* Set flag that causes posix_spawn to behave like execv
*/
flags |= POSIX_SPAWN_SETEXEC;
if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) {
err(1, "posix_spawnattr_setflags");
/* NOTREACHTED */
}
}
#endif
int
int
main(int argc, char **argv) {
char* exec_path = get_python_path();
char* exec_path = get_python_path();
#ifdef HAVE_SPAWN_H
/* We're weak-linking to posix-spawnv to ensure that
* an executable build on 10.5 can work on 10.4.
*/
if (posix_spawn != NULL) {
posix_spawnattr_t spawnattr = NULL;
/* We're weak-linking to posix-spawnv to ensure that
* an executable build on 10.5 can work on 10.4.
*/
if (posix_spawn != NULL) {
posix_spawnattr_t spawnattr = NULL;
setup_spawnattr(&spawnattr);
posix_spawn(NULL, exec_path, NULL,
&spawnattr, argv, environ);
err(1, "posix_spawn: %s", exec_path);
}
setup_spawnattr(&spawnattr);
posix_spawn(NULL, exec_path, NULL,
&spawnattr, argv, environ);
err(1, "posix_spawn: %s", exec_path);
}
#endif
execve(exec_path, argv, environ);
err(1, "execve: %s", argv[0]);
/* NOTREACHED */
execve(exec_path, argv, environ);
err(1, "execve: %s", argv[0]);
/* NOTREACHED */
}

View file

@ -21,28 +21,28 @@
Assuming the script is a Bourne shell script, the first line of the
script should be
#!/bin/sh -
#!/bin/sh -
The - is important, don't omit it. If you're using esh, the first
line should be
#!/usr/local/bin/esh -f
#!/usr/local/bin/esh -f
and for ksh, the first line should be
#!/usr/local/bin/ksh -p
#!/usr/local/bin/ksh -p
The script should then set the variable IFS to the string
consisting of <space>, <tab>, and <newline>. After this (*not*
before!), the PATH variable should be set to a reasonable value and
exported. Do not expect the PATH to have a reasonable value, so do
not trust the old value of PATH. You should then set the umask of
the program by calling
umask 077 # or 022 if you want the files to be readable
umask 077 # or 022 if you want the files to be readable
If you plan to change directories, you should either unset CDPATH
or set it to a good value. Setting CDPATH to just ``.'' (dot) is a
good idea.
If, for some reason, you want to use csh, the first line should be
#!/bin/csh -fb
#!/bin/csh -fb
You should then set the path variable to something reasonable,
without trusting the inherited path. Here too, you should set the
umask using the command
umask 077 # or 022 if you want the files to be readable
umask 077 # or 022 if you want the files to be readable
*/
#include <unistd.h>
@ -54,14 +54,14 @@
/* CONFIGURATION SECTION */
#ifndef FULL_PATH /* so that this can be specified from the Makefile */
#ifndef FULL_PATH /* so that this can be specified from the Makefile */
/* Uncomment the following line:
#define FULL_PATH "/full/path/of/script"
#define FULL_PATH "/full/path/of/script"
* Then comment out the #error line. */
#error "You must define FULL_PATH somewhere"
#endif
#ifndef UMASK
#define UMASK 077
#define UMASK 077
#endif
/* END OF CONFIGURATION SECTION */
@ -101,76 +101,76 @@ char def_ENV[] = "ENV=:";
void
clean_environ(void)
{
char **p;
extern char **environ;
char **p;
extern char **environ;
for (p = environ; *p; p++) {
if (strncmp(*p, "LD_", 3) == 0)
**p = 'X';
else if (strncmp(*p, "_RLD", 4) == 0)
**p = 'X';
else if (strncmp(*p, "PYTHON", 6) == 0)
**p = 'X';
else if (strncmp(*p, "IFS=", 4) == 0)
*p = def_IFS;
else if (strncmp(*p, "CDPATH=", 7) == 0)
*p = def_CDPATH;
else if (strncmp(*p, "ENV=", 4) == 0)
*p = def_ENV;
}
putenv(def_PATH);
for (p = environ; *p; p++) {
if (strncmp(*p, "LD_", 3) == 0)
**p = 'X';
else if (strncmp(*p, "_RLD", 4) == 0)
**p = 'X';
else if (strncmp(*p, "PYTHON", 6) == 0)
**p = 'X';
else if (strncmp(*p, "IFS=", 4) == 0)
*p = def_IFS;
else if (strncmp(*p, "CDPATH=", 7) == 0)
*p = def_CDPATH;
else if (strncmp(*p, "ENV=", 4) == 0)
*p = def_ENV;
}
putenv(def_PATH);
}
int
main(int argc, char **argv)
{
struct stat statb;
gid_t egid = getegid();
uid_t euid = geteuid();
struct stat statb;
gid_t egid = getegid();
uid_t euid = geteuid();
/*
Sanity check #1.
This check should be made compile-time, but that's not possible.
If you're sure that you specified a full path name for FULL_PATH,
you can omit this check.
*/
if (FULL_PATH[0] != '/') {
fprintf(stderr, "%s: %s is not a full path name\n", argv[0],
FULL_PATH);
fprintf(stderr, "You can only use this wrapper if you\n");
fprintf(stderr, "compile it with an absolute path.\n");
exit(1);
}
/*
Sanity check #1.
This check should be made compile-time, but that's not possible.
If you're sure that you specified a full path name for FULL_PATH,
you can omit this check.
*/
if (FULL_PATH[0] != '/') {
fprintf(stderr, "%s: %s is not a full path name\n", argv[0],
FULL_PATH);
fprintf(stderr, "You can only use this wrapper if you\n");
fprintf(stderr, "compile it with an absolute path.\n");
exit(1);
}
/*
Sanity check #2.
Check that the owner of the script is equal to either the
effective uid or the super user.
*/
if (stat(FULL_PATH, &statb) < 0) {
perror("stat");
exit(1);
}
if (statb.st_uid != 0 && statb.st_uid != euid) {
fprintf(stderr, "%s: %s has the wrong owner\n", argv[0],
FULL_PATH);
fprintf(stderr, "The script should be owned by root,\n");
fprintf(stderr, "and shouldn't be writeable by anyone.\n");
exit(1);
}
/*
Sanity check #2.
Check that the owner of the script is equal to either the
effective uid or the super user.
*/
if (stat(FULL_PATH, &statb) < 0) {
perror("stat");
exit(1);
}
if (statb.st_uid != 0 && statb.st_uid != euid) {
fprintf(stderr, "%s: %s has the wrong owner\n", argv[0],
FULL_PATH);
fprintf(stderr, "The script should be owned by root,\n");
fprintf(stderr, "and shouldn't be writeable by anyone.\n");
exit(1);
}
if (setregid(egid, egid) < 0)
perror("setregid");
if (setreuid(euid, euid) < 0)
perror("setreuid");
if (setregid(egid, egid) < 0)
perror("setregid");
if (setreuid(euid, euid) < 0)
perror("setreuid");
clean_environ();
clean_environ();
umask(UMASK);
umask(UMASK);
while (**argv == '-') /* don't let argv[0] start with '-' */
(*argv)++;
execv(FULL_PATH, argv);
fprintf(stderr, "%s: could not execute the script\n", argv[0]);
exit(1);
while (**argv == '-') /* don't let argv[0] start with '-' */
(*argv)++;
execv(FULL_PATH, argv);
fprintf(stderr, "%s: could not execute the script\n", argv[0]);
exit(1);
}

View file

@ -8,51 +8,51 @@ Converted to C by Dmitry Vasiliev (dima at hlabs.spb.ru).
static Py_ssize_t
internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
PyObject *litem;
Py_ssize_t mid, res;
PyObject *litem;
Py_ssize_t mid, res;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(item, litem, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
hi = mid;
else
lo = mid + 1;
}
return lo;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(item, litem, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
hi = mid;
else
lo = mid + 1;
}
return lo;
}
static PyObject *
bisect_right(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
return PyInt_FromSsize_t(index);
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
return PyInt_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_right_doc,
@ -70,30 +70,30 @@ slice of a to be searched.\n");
static PyObject *
insort_right(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "nO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "nO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_right_doc,
@ -109,51 +109,51 @@ slice of a to be searched.\n");
static Py_ssize_t
internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
PyObject *litem;
Py_ssize_t mid, res;
PyObject *litem;
Py_ssize_t mid, res;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(litem, item, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
lo = mid + 1;
else
hi = mid;
}
return lo;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(litem, item, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
static PyObject *
bisect_left(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
return PyInt_FromSsize_t(index);
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
return PyInt_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_left_doc,
@ -171,30 +171,30 @@ slice of a to be searched.\n");
static PyObject *
insort_left(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "iO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "iO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_left_doc,
@ -211,19 +211,19 @@ PyDoc_STRVAR(bisect_doc, "Alias for bisect_right().\n");
PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n");
static PyMethodDef bisect_methods[] = {
{"bisect_right", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
{"bisect", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_doc},
{"insort_right", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_right_doc},
{"insort", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_doc},
{"bisect_left", (PyCFunction)bisect_left,
METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
{"insort_left", (PyCFunction)insort_left,
METH_VARARGS|METH_KEYWORDS, insort_left_doc},
{NULL, NULL} /* sentinel */
{"bisect_right", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
{"bisect", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_doc},
{"insort_right", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_right_doc},
{"insort", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_doc},
{"bisect_left", (PyCFunction)bisect_left,
METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
{"insort_left", (PyCFunction)insort_left,
METH_VARARGS|METH_KEYWORDS, insort_left_doc},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@ -237,5 +237,5 @@ common approach.\n");
PyMODINIT_FUNC
init_bisect(void)
{
Py_InitModule3("_bisect", bisect_methods, module_doc);
Py_InitModule3("_bisect", bisect_methods, module_doc);
}

View file

@ -143,9 +143,9 @@ typedef int Py_ssize_t;
/* and these are for calling C --> Python */
#if defined(MYDB_USE_GILSTATE)
#define MYDB_BEGIN_BLOCK_THREADS \
PyGILState_STATE __savestate = PyGILState_Ensure();
PyGILState_STATE __savestate = PyGILState_Ensure();
#define MYDB_END_BLOCK_THREADS \
PyGILState_Release(__savestate);
PyGILState_Release(__savestate);
#else /* MYDB_USE_GILSTATE */
/* Pre GILState API - do it the long old way */
static PyInterpreterState* _db_interpreterState = NULL;
@ -221,7 +221,7 @@ static PyObject* DBForeignConflictError; /* DB_FOREIGN_CONFLICT */
static PyObject* DBRepUnavailError; /* DB_REP_UNAVAIL */
#if (DBVER < 43)
#define DB_BUFFER_SMALL ENOMEM
#define DB_BUFFER_SMALL ENOMEM
#endif
#if (DBVER < 48)
@ -554,7 +554,7 @@ unsigned int our_strlcpy(char* dest, const char* src, unsigned int n)
srclen = strlen(src);
if (n <= 0)
return srclen;
return srclen;
copylen = (srclen > n-1) ? n-1 : srclen;
/* populate dest[0] thru dest[copylen-1] */
memcpy(dest, src, copylen);
@ -571,7 +571,7 @@ static char _db_errmsg[1024];
static void _db_errorCallback(const char* prefix, char* msg)
#else
static void _db_errorCallback(const DB_ENV *db_env,
const char* prefix, const char* msg)
const char* prefix, const char* msg)
#endif
{
our_strlcpy(_db_errmsg, msg, sizeof(_db_errmsg));
@ -703,8 +703,8 @@ static int makeDBError(int err)
case DB_BUFFER_SMALL: errObj = DBNoMemoryError; break;
#if (DBVER >= 43)
/* ENOMEM and DB_BUFFER_SMALL were one and the same until 4.3 */
case ENOMEM: errObj = PyExc_MemoryError; break;
/* ENOMEM and DB_BUFFER_SMALL were one and the same until 4.3 */
case ENOMEM: errObj = PyExc_MemoryError; break;
#endif
case EINVAL: errObj = DBInvalidArgError; break;
case EACCES: errObj = DBAccessError; break;
@ -818,7 +818,7 @@ static int _DB_put(DBObject* self, DB_TXN *txn, DBT *key, DBT *data, int flags)
/* Get a key/data pair from a cursor */
static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
PyObject *args, PyObject *kwargs, char *format)
PyObject *args, PyObject *kwargs, char *format)
{
int err;
PyObject* retval = NULL;
@ -829,7 +829,7 @@ static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
static char* kwnames[] = { "flags", "dlen", "doff", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, format, kwnames,
&flags, &dlen, &doff))
&flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -845,7 +845,7 @@ static PyObject* _DBCursor_get(DBCursorObject* self, int extra_flags,
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.getReturnsNone) {
&& self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -889,13 +889,13 @@ static void _addIntToDict(PyObject* dict, char *name, int value)
static void _addTimeTToDict(PyObject* dict, char *name, time_t value)
{
PyObject* v;
/* if the value fits in regular int, use that. */
/* if the value fits in regular int, use that. */
#ifdef PY_LONG_LONG
if (sizeof(time_t) > sizeof(long))
v = PyLong_FromLongLong((PY_LONG_LONG) value);
else
if (sizeof(time_t) > sizeof(long))
v = PyLong_FromLongLong((PY_LONG_LONG) value);
else
#endif
v = NUMBER_FromLong((long) value);
v = NUMBER_FromLong((long) value);
if (!v || PyDict_SetItemString(dict, name, v))
PyErr_Clear();
@ -1044,10 +1044,10 @@ newDBCursorObject(DBC* dbc, DBTxnObject *txn, DBObject* db)
INSERT_IN_DOUBLE_LINKED_LIST(self->mydb->children_cursors,self);
if (txn && ((PyObject *)txn!=Py_None)) {
INSERT_IN_DOUBLE_LINKED_LIST_TXN(txn->children_cursors,self);
self->txn=txn;
INSERT_IN_DOUBLE_LINKED_LIST_TXN(txn->children_cursors,self);
self->txn=txn;
} else {
self->txn=NULL;
self->txn=NULL;
}
self->in_weakreflist = NULL;
@ -1474,16 +1474,16 @@ _db_associateCallback(DB* db, const DBT* priKey, const DBT* priData,
PyBytes_AsStringAndSize(result, &data, &size);
secKey->flags = DB_DBT_APPMALLOC; /* DB will free */
secKey->data = malloc(size); /* TODO, check this */
if (secKey->data) {
memcpy(secKey->data, data, size);
secKey->size = size;
retval = 0;
}
else {
PyErr_SetString(PyExc_MemoryError,
if (secKey->data) {
memcpy(secKey->data, data, size);
secKey->size = size;
retval = 0;
}
else {
PyErr_SetString(PyExc_MemoryError,
"malloc failed in _db_associateCallback");
PyErr_Print();
}
PyErr_Print();
}
}
#if (DBVER >= 46)
else if (PyList_Check(result))
@ -1615,7 +1615,7 @@ DB_associate(DBObject* self, PyObject* args, PyObject* kwargs)
#endif
MYDB_BEGIN_ALLOW_THREADS;
err = self->db->associate(self->db,
txn,
txn,
secondaryDB->db,
_db_associateCallback,
flags);
@ -1727,7 +1727,7 @@ _DB_consume(DBObject* self, PyObject* args, PyObject* kwargs, int consume_flag)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->moduleFlags.getReturnsNone) {
&& self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@ -1981,7 +1981,7 @@ DB_get(DBObject* self, PyObject* args, PyObject* kwargs)
retval = dfltobj;
}
else if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->moduleFlags.getReturnsNone) {
&& self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@ -2050,7 +2050,7 @@ DB_pget(DBObject* self, PyObject* args, PyObject* kwargs)
retval = dfltobj;
}
else if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->moduleFlags.getReturnsNone) {
&& self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@ -2185,7 +2185,7 @@ DB_get_both(DBObject* self, PyObject* args, PyObject* kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->moduleFlags.getReturnsNone) {
&& self->moduleFlags.getReturnsNone) {
err = 0;
Py_INCREF(Py_None);
retval = Py_None;
@ -2341,17 +2341,17 @@ DB_open(DBObject* self, PyObject* args, PyObject* kwargs)
"filename", "dbtype", "flags", "mode", "txn", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "z|ziiiO:open", kwnames,
&filename, &dbname, &type, &flags, &mode,
&filename, &dbname, &type, &flags, &mode,
&txnobj))
{
PyErr_Clear();
type = DB_UNKNOWN; flags = 0; mode = 0660;
filename = NULL; dbname = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iiiO:open",
PyErr_Clear();
type = DB_UNKNOWN; flags = 0; mode = 0660;
filename = NULL; dbname = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,"z|iiiO:open",
kwnames_basic,
&filename, &type, &flags, &mode,
&filename, &type, &flags, &mode,
&txnobj))
return NULL;
return NULL;
}
if (!checkTxnObj(txnobj, &txn)) return NULL;
@ -2607,20 +2607,20 @@ DB_get_bt_minkey(DBObject* self)
static int
_default_cmp(const DBT *leftKey,
const DBT *rightKey)
const DBT *rightKey)
{
int res;
int lsize = leftKey->size, rsize = rightKey->size;
res = memcmp(leftKey->data, rightKey->data,
lsize < rsize ? lsize : rsize);
lsize < rsize ? lsize : rsize);
if (res == 0) {
if (lsize < rsize) {
res = -1;
res = -1;
}
else if (lsize > rsize) {
res = 1;
res = 1;
}
}
return res;
@ -2628,8 +2628,8 @@ _default_cmp(const DBT *leftKey,
static int
_db_compareCallback(DB* db,
const DBT *leftKey,
const DBT *rightKey)
const DBT *leftKey,
const DBT *rightKey)
{
int res = 0;
PyObject *args;
@ -2637,40 +2637,40 @@ _db_compareCallback(DB* db,
DBObject *self = (DBObject *)db->app_private;
if (self == NULL || self->btCompareCallback == NULL) {
MYDB_BEGIN_BLOCK_THREADS;
PyErr_SetString(PyExc_TypeError,
(self == 0
? "DB_bt_compare db is NULL."
: "DB_bt_compare callback is NULL."));
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
MYDB_END_BLOCK_THREADS;
MYDB_BEGIN_BLOCK_THREADS;
PyErr_SetString(PyExc_TypeError,
(self == 0
? "DB_bt_compare db is NULL."
: "DB_bt_compare callback is NULL."));
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
MYDB_END_BLOCK_THREADS;
} else {
MYDB_BEGIN_BLOCK_THREADS;
MYDB_BEGIN_BLOCK_THREADS;
args = BuildValue_SS(leftKey->data, leftKey->size, rightKey->data, rightKey->size);
if (args != NULL) {
result = PyEval_CallObject(self->btCompareCallback, args);
}
if (args == NULL || result == NULL) {
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
} else if (NUMBER_Check(result)) {
res = NUMBER_AsLong(result);
} else {
PyErr_SetString(PyExc_TypeError,
"DB_bt_compare callback MUST return an int.");
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
}
args = BuildValue_SS(leftKey->data, leftKey->size, rightKey->data, rightKey->size);
if (args != NULL) {
result = PyEval_CallObject(self->btCompareCallback, args);
}
if (args == NULL || result == NULL) {
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
} else if (NUMBER_Check(result)) {
res = NUMBER_AsLong(result);
} else {
PyErr_SetString(PyExc_TypeError,
"DB_bt_compare callback MUST return an int.");
/* we're in a callback within the DB code, we can't raise */
PyErr_Print();
res = _default_cmp(leftKey, rightKey);
}
Py_XDECREF(args);
Py_XDECREF(result);
Py_XDECREF(args);
Py_XDECREF(result);
MYDB_END_BLOCK_THREADS;
MYDB_END_BLOCK_THREADS;
}
return res;
}
@ -2684,8 +2684,8 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
CHECK_DB_NOT_CLOSED(self);
if (!PyCallable_Check(comparator)) {
makeTypeError("Callable", comparator);
return NULL;
makeTypeError("Callable", comparator);
return NULL;
}
/*
@ -2699,15 +2699,15 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
if (result == NULL)
return NULL;
if (!NUMBER_Check(result)) {
Py_DECREF(result);
PyErr_SetString(PyExc_TypeError,
"callback MUST return an int");
return NULL;
Py_DECREF(result);
PyErr_SetString(PyExc_TypeError,
"callback MUST return an int");
return NULL;
} else if (NUMBER_AsLong(result) != 0) {
Py_DECREF(result);
PyErr_SetString(PyExc_TypeError,
"callback failed to return 0 on two empty strings");
return NULL;
Py_DECREF(result);
PyErr_SetString(PyExc_TypeError,
"callback failed to return 0 on two empty strings");
return NULL;
}
Py_DECREF(result);
@ -2715,8 +2715,8 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
* simplify the code. This would have no real use, as one cannot
* change the function once the db is opened anyway */
if (self->btCompareCallback != NULL) {
PyErr_SetString(PyExc_RuntimeError, "set_bt_compare() cannot be called more than once");
return NULL;
PyErr_SetString(PyExc_RuntimeError, "set_bt_compare() cannot be called more than once");
return NULL;
}
Py_INCREF(comparator);
@ -2731,9 +2731,9 @@ DB_set_bt_compare(DBObject* self, PyObject* comparator)
err = self->db->set_bt_compare(self->db, _db_compareCallback);
if (err) {
/* restore the old state in case of error */
Py_DECREF(comparator);
self->btCompareCallback = NULL;
/* restore the old state in case of error */
Py_DECREF(comparator);
self->btCompareCallback = NULL;
}
RETURN_IF_ERR();
@ -3315,8 +3315,8 @@ DB_verify(DBObject* self, PyObject* args, PyObject* kwargs)
CHECK_DB_NOT_CLOSED(self);
if (outFileName)
outFile = fopen(outFileName, "w");
/* XXX(nnorwitz): it should probably be an exception if outFile
can't be opened. */
/* XXX(nnorwitz): it should probably be an exception if outFile
can't be opened. */
{ /* DB.verify acts as a DB handle destructor (like close) */
PyObject *error;
@ -3369,8 +3369,8 @@ DB_set_encrypt(DBObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "passwd", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i:set_encrypt", kwnames,
&passwd, &flags)) {
return NULL;
&passwd, &flags)) {
return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@ -3990,12 +3990,12 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
CLEAR_DBT(key);
CLEAR_DBT(data);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii:get", &kwnames[2],
&flags, &dlen, &doff))
&flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii:get",
&kwnames[1],
&keyobj, &flags, &dlen, &doff))
&keyobj, &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOi|ii:get",
@ -4003,8 +4003,8 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
&flags, &dlen, &doff))
{
return NULL;
}
}
}
}
}
CHECK_CURSOR_NOT_CLOSED(self);
@ -4023,7 +4023,7 @@ DBC_get(DBCursorObject* self, PyObject* args, PyObject *kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.getReturnsNone) {
&& self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4066,12 +4066,12 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
CLEAR_DBT(key);
CLEAR_DBT(data);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|ii:pget", &kwnames[2],
&flags, &dlen, &doff))
&flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii:pget",
kwnames_keyOnly,
&keyobj, &flags, &dlen, &doff))
&keyobj, &flags, &dlen, &doff))
{
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOi|ii:pget",
@ -4079,8 +4079,8 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
&flags, &dlen, &doff))
{
return NULL;
}
}
}
}
}
CHECK_CURSOR_NOT_CLOSED(self);
@ -4101,7 +4101,7 @@ DBC_pget(DBCursorObject* self, PyObject* args, PyObject *kwargs)
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.getReturnsNone) {
&& self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4212,7 +4212,7 @@ DBC_put(DBCursorObject* self, PyObject* args, PyObject* kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iii:put", kwnames,
&keyobj, &dataobj, &flags, &dlen, &doff))
&keyobj, &dataobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -4246,7 +4246,7 @@ DBC_set(DBCursorObject* self, PyObject* args, PyObject *kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iii:set", kwnames,
&keyobj, &flags, &dlen, &doff))
&keyobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -4264,7 +4264,7 @@ DBC_set(DBCursorObject* self, PyObject* args, PyObject *kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4309,7 +4309,7 @@ DBC_set_range(DBCursorObject* self, PyObject* args, PyObject* kwargs)
int doff = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iii:set_range", kwnames,
&keyobj, &flags, &dlen, &doff))
&keyobj, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -4326,7 +4326,7 @@ DBC_set_range(DBCursorObject* self, PyObject* args, PyObject* kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET_RANGE);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4480,7 +4480,7 @@ DBC_set_recno(DBCursorObject* self, PyObject* args, PyObject *kwargs)
static char* kwnames[] = { "recno","flags", "dlen", "doff", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|iii:set_recno", kwnames,
&irecno, &flags, &dlen, &doff))
&irecno, &flags, &dlen, &doff))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -4509,7 +4509,7 @@ DBC_set_recno(DBCursorObject* self, PyObject* args, PyObject *kwargs)
err = _DBC_get(self->dbc, &key, &data, flags|DB_SET_RECNO);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
&& self->mydb->moduleFlags.cursorSetReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4579,7 +4579,7 @@ DBC_join_item(DBCursorObject* self, PyObject* args)
err = _DBC_get(self->dbc, &key, &data, flags | DB_JOIN_ITEM);
MYDB_END_ALLOW_THREADS;
if ((err == DB_NOTFOUND || err == DB_KEYEMPTY)
&& self->mydb->moduleFlags.getReturnsNone) {
&& self->mydb->moduleFlags.getReturnsNone) {
Py_INCREF(Py_None);
retval = Py_None;
}
@ -4602,7 +4602,7 @@ DBC_set_priority(DBCursorObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "priority", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i:set_priority", kwnames,
&priority))
&priority))
return NULL;
CHECK_CURSOR_NOT_CLOSED(self);
@ -4921,8 +4921,8 @@ DBEnv_dbremove(DBEnvObject* self, PyObject* args, PyObject* kwargs)
NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|zOi:dbremove", kwnames,
&file, &database, &txnobj, &flags)) {
return NULL;
&file, &database, &txnobj, &flags)) {
return NULL;
}
if (!checkTxnObj(txnobj, &txn)) {
return NULL;
@ -4949,8 +4949,8 @@ DBEnv_dbrename(DBEnvObject* self, PyObject* args, PyObject* kwargs)
"flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "szs|Oi:dbrename", kwnames,
&file, &database, &newname, &txnobj, &flags)) {
return NULL;
&file, &database, &newname, &txnobj, &flags)) {
return NULL;
}
if (!checkTxnObj(txnobj, &txn)) {
return NULL;
@ -4975,8 +4975,8 @@ DBEnv_set_encrypt(DBEnvObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "passwd", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i:set_encrypt", kwnames,
&passwd, &flags)) {
return NULL;
&passwd, &flags)) {
return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@ -5037,8 +5037,8 @@ DBEnv_set_timeout(DBEnvObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "timeout", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:set_timeout", kwnames,
&timeout, &flags)) {
return NULL;
&timeout, &flags)) {
return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@ -6935,8 +6935,8 @@ DBEnv_set_event_notify(DBEnvObject* self, PyObject* notifyFunc)
CHECK_ENV_NOT_CLOSED(self);
if (!PyCallable_Check(notifyFunc)) {
makeTypeError("Callable", notifyFunc);
return NULL;
makeTypeError("Callable", notifyFunc);
return NULL;
}
Py_XDECREF(self->event_notifyCallback);
@ -6954,8 +6954,8 @@ DBEnv_set_event_notify(DBEnvObject* self, PyObject* notifyFunc)
MYDB_END_ALLOW_THREADS;
if (err) {
Py_DECREF(notifyFunc);
self->event_notifyCallback = NULL;
Py_DECREF(notifyFunc);
self->event_notifyCallback = NULL;
}
RETURN_IF_ERR();
@ -7276,7 +7276,7 @@ DBEnv_rep_start(DBEnvObject* self, PyObject* args, PyObject* kwargs)
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"i|O:rep_start", kwnames, &flags, &cdata_py))
{
return NULL;
return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
@ -7598,7 +7598,7 @@ DBEnv_repmgr_start(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"ii:repmgr_start", kwnames, &nthreads, &flags))
{
return NULL;
return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@ -7621,7 +7621,7 @@ DBEnv_repmgr_set_local_site(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"si|i:repmgr_set_local_site", kwnames, &host, &port, &flags))
{
return NULL;
return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@ -7645,7 +7645,7 @@ DBEnv_repmgr_add_remote_site(DBEnvObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"si|i:repmgr_add_remote_site", kwnames, &host, &port, &flags))
{
return NULL;
return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@ -7663,7 +7663,7 @@ DBEnv_repmgr_set_ack_policy(DBEnvObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "i:repmgr_set_ack_policy", &ack_policy))
{
return NULL;
return NULL;
}
CHECK_ENV_NOT_CLOSED(self);
MYDB_BEGIN_ALLOW_THREADS;
@ -7838,7 +7838,7 @@ static void _promote_transaction_dbs_and_sequences(DBTxnObject *txn)
/* The db is already linked to its environment,
** so nothing to do.
*/
db->txn=NULL;
db->txn=NULL;
}
}
@ -8034,8 +8034,8 @@ DBTxn_set_timeout(DBTxnObject* self, PyObject* args, PyObject* kwargs)
static char* kwnames[] = { "timeout", "flags", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:set_timeout", kwnames,
&timeout, &flags)) {
return NULL;
&timeout, &flags)) {
return NULL;
}
MYDB_BEGIN_ALLOW_THREADS;
@ -8963,20 +8963,20 @@ statichere PyTypeObject DB_Type = {
&DB_sequence,/*tp_as_sequence*/
&DB_mapping,/*tp_as_mapping*/
0, /*tp_hash*/
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(DBObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@ -9092,20 +9092,20 @@ statichere PyTypeObject DBEnv_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(DBEnvObject, in_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
@ -9135,20 +9135,20 @@ statichere PyTypeObject DBTxn_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(DBTxnObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@ -9178,20 +9178,20 @@ statichere PyTypeObject DBLock_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(DBLockObject, in_weakreflist), /* tp_weaklistoffset */
};
@ -9217,20 +9217,20 @@ statichere PyTypeObject DBSequence_Type = {
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_as_buffer */
#if (PY_VERSION_HEX < 0x03000000)
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
#else
Py_TPFLAGS_DEFAULT, /* tp_flags */
#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(DBSequenceObject, in_weakreflist), /* tp_weaklistoffset */
0, /*tp_iter*/
0, /*tp_iternext*/
@ -9404,7 +9404,7 @@ PyMODINIT_FUNC PyInit__bsddb(void) /* Note the two underscores */
#if (PY_VERSION_HEX < 0x03000000)
return;
#else
return NULL;
return NULL;
#endif
}
@ -9878,7 +9878,7 @@ PyMODINIT_FUNC PyInit__bsddb(void) /* Note the two underscores */
* using one base class. */
PyDict_SetItemString(d, "KeyError", PyExc_KeyError);
PyRun_String("class DBNotFoundError(DBError, KeyError): pass\n"
"class DBKeyEmptyError(DBError, KeyError): pass",
"class DBKeyEmptyError(DBError, KeyError): pass",
Py_file_input, d, d);
DBNotFoundError = PyDict_GetItemString(d, "DBNotFoundError");
DBKeyEmptyError = PyDict_GetItemString(d, "DBKeyEmptyError");

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -27,152 +27,152 @@
EXPORT(void)testfunc_array(int values[4])
{
printf("testfunc_array %d %d %d %d\n",
values[0],
values[1],
values[2],
values[3]);
printf("testfunc_array %d %d %d %d\n",
values[0],
values[1],
values[2],
values[3]);
}
EXPORT(long double)testfunc_Ddd(double a, double b)
{
long double result = (long double)(a * b);
printf("testfunc_Ddd(%p, %p)\n", &a, &b);
printf("testfunc_Ddd(%g, %g)\n", a, b);
return result;
long double result = (long double)(a * b);
printf("testfunc_Ddd(%p, %p)\n", &a, &b);
printf("testfunc_Ddd(%g, %g)\n", a, b);
return result;
}
EXPORT(long double)testfunc_DDD(long double a, long double b)
{
long double result = a * b;
printf("testfunc_DDD(%p, %p)\n", &a, &b);
printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
return result;
long double result = a * b;
printf("testfunc_DDD(%p, %p)\n", &a, &b);
printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
return result;
}
EXPORT(int)testfunc_iii(int a, int b)
{
int result = a * b;
printf("testfunc_iii(%p, %p)\n", &a, &b);
return result;
int result = a * b;
printf("testfunc_iii(%p, %p)\n", &a, &b);
return result;
}
EXPORT(int)myprintf(char *fmt, ...)
{
int result;
va_list argptr;
va_start(argptr, fmt);
result = vprintf(fmt, argptr);
va_end(argptr);
return result;
int result;
va_list argptr;
va_start(argptr, fmt);
result = vprintf(fmt, argptr);
va_end(argptr);
return result;
}
EXPORT(char *)my_strtok(char *token, const char *delim)
{
return strtok(token, delim);
return strtok(token, delim);
}
EXPORT(char *)my_strchr(const char *s, int c)
{
return strchr(s, c);
return strchr(s, c);
}
EXPORT(double) my_sqrt(double a)
{
return sqrt(a);
return sqrt(a);
}
EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*))
{
qsort(base, num, width, compare);
qsort(base, num, width, compare);
}
EXPORT(int *) _testfunc_ai8(int a[8])
{
return a;
return a;
}
EXPORT(void) _testfunc_v(int a, int b, int *presult)
{
*presult = a + b;
*presult = a + b;
}
EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (int)(b + h + i + l + f + d);
return (int)(b + h + i + l + f + d);
}
EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (float)(b + h + i + l + f + d);
return (float)(b + h + i + l + f + d);
}
EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (double)(b + h + i + l + f + d);
return (double)(b + h + i + l + f + d);
}
EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d)
{
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (long double)(b + h + i + l + f + d);
return (long double)(b + h + i + l + f + d);
}
EXPORT(char *) _testfunc_p_p(void *s)
{
return (char *)s;
return (char *)s;
}
EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv)
{
return argv[(*argcp)-1];
return argv[(*argcp)-1];
}
EXPORT(void *) get_strchr(void)
{
return (void *)strchr;
return (void *)strchr;
}
EXPORT(char *) my_strdup(char *src)
{
char *dst = (char *)malloc(strlen(src)+1);
if (!dst)
return NULL;
strcpy(dst, src);
return dst;
char *dst = (char *)malloc(strlen(src)+1);
if (!dst)
return NULL;
strcpy(dst, src);
return dst;
}
EXPORT(void)my_free(void *ptr)
{
free(ptr);
free(ptr);
}
#ifdef HAVE_WCHAR_H
EXPORT(wchar_t *) my_wcsdup(wchar_t *src)
{
size_t len = wcslen(src);
wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (ptr == NULL)
return NULL;
memcpy(ptr, src, (len+1) * sizeof(wchar_t));
return ptr;
size_t len = wcslen(src);
wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (ptr == NULL)
return NULL;
memcpy(ptr, src, (len+1) * sizeof(wchar_t));
return ptr;
}
EXPORT(size_t) my_wcslen(wchar_t *src)
{
return wcslen(src);
return wcslen(src);
}
#endif
@ -183,158 +183,158 @@ EXPORT(size_t) my_wcslen(wchar_t *src)
#endif
typedef struct {
int (*c)(int, int);
int (__stdcall *s)(int, int);
int (*c)(int, int);
int (__stdcall *s)(int, int);
} FUNCS;
EXPORT(int) _testfunc_callfuncp(FUNCS *fp)
{
fp->c(1, 2);
fp->s(3, 4);
return 0;
fp->c(1, 2);
fp->s(3, 4);
return 0;
}
EXPORT(int) _testfunc_deref_pointer(int *pi)
{
return *pi;
return *pi;
}
#ifdef MS_WIN32
EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk)
{
piunk->lpVtbl->AddRef(piunk);
return piunk->lpVtbl->Release(piunk);
piunk->lpVtbl->AddRef(piunk);
return piunk->lpVtbl->Release(piunk);
}
#endif
EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *))
{
int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return (*func)(table);
return (*func)(table);
}
#ifdef HAVE_LONG_LONG
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f,
double d, PY_LONG_LONG q)
double d, PY_LONG_LONG q)
{
return (PY_LONG_LONG)(b + h + i + l + f + d + q);
return (PY_LONG_LONG)(b + h + i + l + f + d + q);
}
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
return (PY_LONG_LONG)(b + h + i + l + f + d);
return (PY_LONG_LONG)(b + h + i + l + f + d);
}
EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int))
{
int sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
int sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
}
EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value,
PY_LONG_LONG (*func)(PY_LONG_LONG))
PY_LONG_LONG (*func)(PY_LONG_LONG))
{
PY_LONG_LONG sum = 0;
PY_LONG_LONG sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
}
#endif
typedef struct {
char *name;
char *value;
char *name;
char *value;
} SPAM;
typedef struct {
char *name;
int num_spams;
SPAM *spams;
char *name;
int num_spams;
SPAM *spams;
} EGG;
SPAM my_spams[2] = {
{ "name1", "value1" },
{ "name2", "value2" },
{ "name1", "value1" },
{ "name2", "value2" },
};
EGG my_eggs[1] = {
{ "first egg", 1, my_spams }
{ "first egg", 1, my_spams }
};
EXPORT(int) getSPAMANDEGGS(EGG **eggs)
{
*eggs = my_eggs;
return 1;
*eggs = my_eggs;
return 1;
}
typedef struct tagpoint {
int x;
int y;
int x;
int y;
} point;
EXPORT(int) _testfunc_byval(point in, point *pout)
{
if (pout) {
pout->x = in.x;
pout->y = in.y;
}
return in.x + in.y;
if (pout) {
pout->x = in.x;
pout->y = in.y;
}
return in.x + in.y;
}
EXPORT (int) an_integer = 42;
EXPORT(int) get_an_integer(void)
{
return an_integer;
return an_integer;
}
EXPORT(double)
integrate(double a, double b, double (*f)(double), long nstep)
{
double x, sum=0.0, dx=(b-a)/(double)nstep;
for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
sum += f(x);
return sum/(double)nstep;
double x, sum=0.0, dx=(b-a)/(double)nstep;
for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
sum += f(x);
return sum/(double)nstep;
}
typedef struct {
void (*initialize)(void *(*)(int), void(*)(void *));
void (*initialize)(void *(*)(int), void(*)(void *));
} xxx_library;
static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *))
{
void *ptr;
printf("_xxx_init got %p %p\n", Xalloc, Xfree);
printf("calling\n");
ptr = Xalloc(32);
Xfree(ptr);
printf("calls done, ptr was %p\n", ptr);
void *ptr;
printf("_xxx_init got %p %p\n", Xalloc, Xfree);
printf("calling\n");
ptr = Xalloc(32);
Xfree(ptr);
printf("calls done, ptr was %p\n", ptr);
}
xxx_library _xxx_lib = {
_xxx_init
_xxx_init
};
EXPORT(xxx_library) *library_get(void)
{
return &_xxx_lib;
return &_xxx_lib;
}
#ifdef MS_WIN32
/* See Don Box (german), pp 79ff. */
EXPORT(void) GetString(BSTR *pbstr)
{
*pbstr = SysAllocString(L"Goodbye!");
*pbstr = SysAllocString(L"Goodbye!");
}
#endif
@ -343,12 +343,12 @@ EXPORT(void) GetString(BSTR *pbstr)
*/
PyObject *py_func_si(PyObject *self, PyObject *args)
{
char *name;
int i;
if (!PyArg_ParseTuple(args, "si", &name, &i))
return NULL;
Py_INCREF(Py_None);
return Py_None;
char *name;
int i;
if (!PyArg_ParseTuple(args, "si", &name, &i))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
EXPORT(void) _py_func_si(char *s, int i)
@ -357,8 +357,8 @@ EXPORT(void) _py_func_si(char *s, int i)
PyObject *py_func(PyObject *self, PyObject *args)
{
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
}
EXPORT(void) _py_func(void)
@ -369,64 +369,64 @@ EXPORT(PY_LONG_LONG) last_tf_arg_s;
EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u;
struct BITS {
int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
};
DL_EXPORT(void) set_bitfields(struct BITS *bits, char name, int value)
{
switch (name) {
case 'A': bits->A = value; break;
case 'B': bits->B = value; break;
case 'C': bits->C = value; break;
case 'D': bits->D = value; break;
case 'E': bits->E = value; break;
case 'F': bits->F = value; break;
case 'G': bits->G = value; break;
case 'H': bits->H = value; break;
case 'I': bits->I = value; break;
switch (name) {
case 'A': bits->A = value; break;
case 'B': bits->B = value; break;
case 'C': bits->C = value; break;
case 'D': bits->D = value; break;
case 'E': bits->E = value; break;
case 'F': bits->F = value; break;
case 'G': bits->G = value; break;
case 'H': bits->H = value; break;
case 'I': bits->I = value; break;
case 'M': bits->M = value; break;
case 'N': bits->N = value; break;
case 'O': bits->O = value; break;
case 'P': bits->P = value; break;
case 'Q': bits->Q = value; break;
case 'R': bits->R = value; break;
case 'S': bits->S = value; break;
}
case 'M': bits->M = value; break;
case 'N': bits->N = value; break;
case 'O': bits->O = value; break;
case 'P': bits->P = value; break;
case 'Q': bits->Q = value; break;
case 'R': bits->R = value; break;
case 'S': bits->S = value; break;
}
}
DL_EXPORT(int) unpack_bitfields(struct BITS *bits, char name)
{
switch (name) {
case 'A': return bits->A;
case 'B': return bits->B;
case 'C': return bits->C;
case 'D': return bits->D;
case 'E': return bits->E;
case 'F': return bits->F;
case 'G': return bits->G;
case 'H': return bits->H;
case 'I': return bits->I;
switch (name) {
case 'A': return bits->A;
case 'B': return bits->B;
case 'C': return bits->C;
case 'D': return bits->D;
case 'E': return bits->E;
case 'F': return bits->F;
case 'G': return bits->G;
case 'H': return bits->H;
case 'I': return bits->I;
case 'M': return bits->M;
case 'N': return bits->N;
case 'O': return bits->O;
case 'P': return bits->P;
case 'Q': return bits->Q;
case 'R': return bits->R;
case 'S': return bits->S;
}
return 0;
case 'M': return bits->M;
case 'N': return bits->N;
case 'O': return bits->O;
case 'P': return bits->P;
case 'Q': return bits->Q;
case 'R': return bits->R;
case 'S': return bits->S;
}
return 0;
}
static PyMethodDef module_methods[] = {
/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
{"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
{"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
*/
{"func_si", py_func_si, METH_VARARGS},
{"func", py_func, METH_NOARGS},
{ NULL, NULL, 0, NULL},
{"func_si", py_func_si, METH_VARARGS},
{"func", py_func, METH_NOARGS},
{ NULL, NULL, 0, NULL},
};
#define S last_tf_arg_s = (PY_LONG_LONG)c
@ -496,80 +496,80 @@ EXPORT(void) __stdcall s_tv_i(int c) { S; return; }
#endif
/********/
#ifndef MS_WIN32
typedef struct {
long x;
long y;
long x;
long y;
} POINT;
typedef struct {
long left;
long top;
long right;
long bottom;
long left;
long top;
long right;
long bottom;
} RECT;
#endif
EXPORT(int) PointInRect(RECT *prc, POINT pt)
{
if (pt.x < prc->left)
return 0;
if (pt.x > prc->right)
return 0;
if (pt.y < prc->top)
return 0;
if (pt.y > prc->bottom)
return 0;
return 1;
if (pt.x < prc->left)
return 0;
if (pt.x > prc->right)
return 0;
if (pt.y < prc->top)
return 0;
if (pt.y > prc->bottom)
return 0;
return 1;
}
typedef struct {
short x;
short y;
short x;
short y;
} S2H;
EXPORT(S2H) ret_2h_func(S2H inp)
{
inp.x *= 2;
inp.y *= 3;
return inp;
inp.x *= 2;
inp.y *= 3;
return inp;
}
typedef struct {
int a, b, c, d, e, f, g, h;
int a, b, c, d, e, f, g, h;
} S8I;
EXPORT(S8I) ret_8i_func(S8I inp)
{
inp.a *= 2;
inp.b *= 3;
inp.c *= 4;
inp.d *= 5;
inp.e *= 6;
inp.f *= 7;
inp.g *= 8;
inp.h *= 9;
return inp;
inp.a *= 2;
inp.b *= 3;
inp.c *= 4;
inp.d *= 5;
inp.e *= 6;
inp.f *= 7;
inp.g *= 8;
inp.h *= 9;
return inp;
}
EXPORT(int) GetRectangle(int flag, RECT *prect)
{
if (flag == 0)
return 0;
prect->left = (int)flag;
prect->top = (int)flag + 1;
prect->right = (int)flag + 2;
prect->bottom = (int)flag + 3;
return 1;
if (flag == 0)
return 0;
prect->left = (int)flag;
prect->top = (int)flag + 1;
prect->right = (int)flag + 2;
prect->bottom = (int)flag + 3;
return 1;
}
EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj)
{
*pi += a;
*pj += b;
*pi += a;
*pj += b;
}
#ifdef MS_WIN32
@ -584,13 +584,13 @@ EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); }
EXPORT (HRESULT) KeepObject(IUnknown *punk)
{
static IUnknown *pobj;
if (punk)
punk->lpVtbl->AddRef(punk);
if (pobj)
pobj->lpVtbl->Release(pobj);
pobj = punk;
return S_OK;
static IUnknown *pobj;
if (punk)
punk->lpVtbl->AddRef(punk);
if (pobj)
pobj->lpVtbl->Release(pobj);
pobj = punk;
return S_OK;
}
#endif
@ -598,5 +598,5 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk)
DL_EXPORT(void)
init_ctypes_test(void)
{
Py_InitModule("_ctypes_test", module_methods);
Py_InitModule("_ctypes_test", module_methods);
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@ typedef Py_ssize_t (*charbufferproc)(PyObject *, Py_ssize_t, char **);
#if (PY_VERSION_HEX < 0x02060000)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
PyObject_HEAD_INIT(type) size,
#define PyImport_ImportModuleNoBlock PyImport_ImportModule
#define PyLong_FromSsize_t PyInt_FromLong
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
@ -62,16 +62,16 @@ Making CDataObject a variable size object would be a better solution, but more
difficult in the presence of PyCFuncPtrObject. Maybe later.
*/
union value {
char c[16];
short s;
int i;
long l;
float f;
double d;
char c[16];
short s;
int i;
long l;
float f;
double d;
#ifdef HAVE_LONG_LONG
PY_LONG_LONG ll;
PY_LONG_LONG ll;
#endif
long double D;
long double D;
};
/*
@ -81,67 +81,67 @@ union value {
*/
struct tagCDataObject {
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
union value b_value;
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
union value b_value;
};
typedef struct {
PyObject_VAR_HEAD
ffi_closure *pcl; /* the C callable */
ffi_cif cif;
int flags;
PyObject *converters;
PyObject *callable;
PyObject *restype;
SETFUNC setfunc;
ffi_type *ffi_restype;
ffi_type *atypes[1];
PyObject_VAR_HEAD
ffi_closure *pcl; /* the C callable */
ffi_cif cif;
int flags;
PyObject *converters;
PyObject *callable;
PyObject *restype;
SETFUNC setfunc;
ffi_type *ffi_restype;
ffi_type *atypes[1];
} CThunkObject;
extern PyTypeObject PyCThunk_Type;
#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
typedef struct {
/* First part identical to tagCDataObject */
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
/* end of tagCDataObject, additional fields follow */
/* First part identical to tagCDataObject */
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
/* end of tagCDataObject, additional fields follow */
CThunkObject *thunk;
PyObject *callable;
CThunkObject *thunk;
PyObject *callable;
/* These two fields will override the ones in the type's stgdict if
they are set */
PyObject *converters;
PyObject *argtypes;
PyObject *restype;
PyObject *checker;
PyObject *errcheck;
/* These two fields will override the ones in the type's stgdict if
they are set */
PyObject *converters;
PyObject *argtypes;
PyObject *restype;
PyObject *checker;
PyObject *errcheck;
#ifdef MS_WIN32
int index;
GUID *iid;
int index;
GUID *iid;
#endif
PyObject *paramflags;
PyObject *paramflags;
} PyCFuncPtrObject;
extern PyTypeObject PyCStgDict_Type;
#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct);
extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength);
@ -150,12 +150,12 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig
extern PyTypeObject PyCData_Type;
#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
extern PyTypeObject PyCSimpleType_Type;
#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
extern PyTypeObject PyCField_Type;
extern struct fielddesc *_ctypes_get_fielddesc(char *fmt);
@ -163,9 +163,9 @@ extern struct fielddesc *_ctypes_get_fielddesc(char *fmt);
extern PyObject *
PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
int pack, int is_big_endian);
Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
int pack, int is_big_endian);
extern PyObject *PyCData_AtAddress(PyObject *type, void *buf);
extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length);
@ -178,13 +178,13 @@ extern PyTypeObject PyCFuncPtr_Type;
extern PyTypeObject PyCFuncPtrType_Type;
extern PyTypeObject PyCStructType_Type;
#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
extern PyObject *
PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
@ -192,35 +192,35 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
extern PyMethodDef _ctypes_module_methods[];
extern CThunkObject *_ctypes_alloc_callback(PyObject *callable,
PyObject *converters,
PyObject *restype,
int flags);
PyObject *converters,
PyObject *restype,
int flags);
/* a table entry describing a predefined ctypes type */
struct fielddesc {
char code;
SETFUNC setfunc;
GETFUNC getfunc;
ffi_type *pffi_type; /* always statically allocated */
SETFUNC setfunc_swapped;
GETFUNC getfunc_swapped;
char code;
SETFUNC setfunc;
GETFUNC getfunc;
ffi_type *pffi_type; /* always statically allocated */
SETFUNC setfunc_swapped;
GETFUNC getfunc_swapped;
};
typedef struct {
PyObject_HEAD
Py_ssize_t offset;
Py_ssize_t size;
Py_ssize_t index; /* Index into CDataObject's
object array */
PyObject *proto; /* a type or NULL */
GETFUNC getfunc; /* getter function if proto is NULL */
SETFUNC setfunc; /* setter function if proto is NULL */
int anonymous;
PyObject_HEAD
Py_ssize_t offset;
Py_ssize_t size;
Py_ssize_t index; /* Index into CDataObject's
object array */
PyObject *proto; /* a type or NULL */
GETFUNC getfunc; /* getter function if proto is NULL */
SETFUNC setfunc; /* setter function if proto is NULL */
int anonymous;
} CFieldObject;
/* A subclass of PyDictObject, used as the instance dictionary of ctypes
metatypes */
typedef struct {
PyDictObject dict; /* first part identical to PyDictObject */
PyDictObject dict; /* first part identical to PyDictObject */
/* The size and align fields are unneeded, they are in ffi_type as well. As
an experiment shows, it's trivial to get rid of them, the only thing to
remember is that in PyCArrayType_new the ffi_type fields must be filled in -
@ -229,28 +229,28 @@ typedef struct {
too much risk to change that now, and there are other fields which doen't
belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?)
*/
Py_ssize_t size; /* number of bytes */
Py_ssize_t align; /* alignment requirements */
Py_ssize_t length; /* number of fields */
ffi_type ffi_type_pointer;
PyObject *proto; /* Only for Pointer/ArrayObject */
SETFUNC setfunc; /* Only for simple objects */
GETFUNC getfunc; /* Only for simple objects */
PARAMFUNC paramfunc;
Py_ssize_t size; /* number of bytes */
Py_ssize_t align; /* alignment requirements */
Py_ssize_t length; /* number of fields */
ffi_type ffi_type_pointer;
PyObject *proto; /* Only for Pointer/ArrayObject */
SETFUNC setfunc; /* Only for simple objects */
GETFUNC getfunc; /* Only for simple objects */
PARAMFUNC paramfunc;
/* Following fields only used by PyCFuncPtrType_Type instances */
PyObject *argtypes; /* tuple of CDataObjects */
PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
PyObject *restype; /* CDataObject or NULL */
PyObject *checker;
int flags; /* calling convention and such */
/* Following fields only used by PyCFuncPtrType_Type instances */
PyObject *argtypes; /* tuple of CDataObjects */
PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
PyObject *restype; /* CDataObject or NULL */
PyObject *checker;
int flags; /* calling convention and such */
/* pep3118 fields, pointers neeed PyMem_Free */
char *format;
int ndim;
Py_ssize_t *shape;
/* Py_ssize_t *strides; */ /* unused in ctypes */
/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
/* pep3118 fields, pointers neeed PyMem_Free */
char *format;
int ndim;
Py_ssize_t *shape;
/* Py_ssize_t *strides; */ /* unused in ctypes */
/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
} StgDictObject;
@ -305,16 +305,16 @@ extern int PyCStgDict_clone(StgDictObject *src, StgDictObject *dst);
typedef int(* PPROC)(void);
PyObject *_ctypes_callproc(PPROC pProc,
PyObject *arguments,
PyObject *arguments,
#ifdef MS_WIN32
IUnknown *pIUnk,
GUID *iid,
IUnknown *pIUnk,
GUID *iid,
#endif
int flags,
PyObject *argtypes,
PyObject *restype,
PyObject *checker);
int flags,
PyObject *argtypes,
PyObject *restype,
PyObject *checker);
#define FUNCFLAG_STDCALL 0x0
#define FUNCFLAG_CDECL 0x1
@ -329,45 +329,45 @@ PyObject *_ctypes_callproc(PPROC pProc,
#define DICTFLAG_FINAL 0x1000
struct tagPyCArgObject {
PyObject_HEAD
ffi_type *pffi_type;
char tag;
union {
char c;
char b;
short h;
int i;
long l;
PyObject_HEAD
ffi_type *pffi_type;
char tag;
union {
char c;
char b;
short h;
int i;
long l;
#ifdef HAVE_LONG_LONG
PY_LONG_LONG q;
PY_LONG_LONG q;
#endif
long double D;
double d;
float f;
void *p;
} value;
PyObject *obj;
Py_ssize_t size; /* for the 'V' tag */
long double D;
double d;
float f;
void *p;
} value;
PyObject *obj;
Py_ssize_t size; /* for the 'V' tag */
};
extern PyTypeObject PyCArg_Type;
#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
extern PyCArgObject *PyCArgObject_new(void);
extern PyObject *
PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
Py_ssize_t index, Py_ssize_t size, char *ptr);
Py_ssize_t index, Py_ssize_t size, char *ptr);
extern int
PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
Py_ssize_t index, Py_ssize_t size, char *ptr);
Py_ssize_t index, Py_ssize_t size, char *ptr);
extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...);
struct basespec {
CDataObject *base;
Py_ssize_t index;
char *adr;
CDataObject *base;
Py_ssize_t index;
char *adr;
};
extern char basespec_string[];
@ -383,14 +383,14 @@ extern char *_ctypes_conversion_errors;
/* Python 2.4 macros, which are not available in Python 2.3 */
#ifndef Py_CLEAR
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(tmp); \
} \
} while (0)
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(tmp); \
} \
} while (0)
#endif
#ifndef Py_VISIT
@ -399,14 +399,14 @@ extern char *_ctypes_conversion_errors;
* "visit" and "arg". This is intended to keep tp_traverse functions
* looking as much alike as possible.
*/
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((op), arg); \
if (vret) \
return vret; \
} \
} while (0)
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((op), arg); \
if (vret) \
return vret; \
} \
} while (0)
#endif
/* Python's PyUnicode_*WideChar functions are broken ... */
@ -453,14 +453,14 @@ extern PyObject *ComError;
#define CTYPES_CAPSULE_INSTANTIATE_DESTRUCTOR(name) \
static void capsule_destructor_ ## name(PyObject *ptr) \
{ \
void *p = PyCapsule_GetPointer(ptr, name); \
if (p) { \
PyMem_Free(p); \
} \
void *p = PyCapsule_GetPointer(ptr, name); \
if (p) { \
PyMem_Free(p); \
} \
} \
#define CAPSULE_NEW(pointer, name) \
(PyCapsule_New(pointer, name, capsule_destructor_ ## name))
(PyCapsule_New(pointer, name, capsule_destructor_ ## name))
#define CAPSULE_DEREFERENCE(capsule, name) \
(PyCapsule_GetPointer(capsule, name))
@ -471,7 +471,7 @@ static void capsule_destructor_ ## name(PyObject *ptr) \
#define CTYPES_CAPSULE_INSTANTIATE_DESTRUCTOR(name)
#define CAPSULE_NEW(pointer, name) \
(PyCObject_FromVoidPtr(pointer, PyMem_Free))
(PyCObject_FromVoidPtr(pointer, PyMem_Free))
#define CAPSULE_DEREFERENCE(capsule, name) \
(PyCObject_AsVoidPtr(capsule))

View file

@ -81,167 +81,167 @@ static const char *error(int setget, const char *str, ...);
/* Set and get the error string for use by dlerror */
static const char *error(int setget, const char *str, ...)
{
static char errstr[ERR_STR_LEN];
static int err_filled = 0;
const char *retval;
va_list arg;
if (setget == 0)
{
va_start(arg, str);
strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
va_end(arg);
err_filled = 1;
retval = NULL;
}
else
{
if (!err_filled)
retval = NULL;
else
retval = errstr;
err_filled = 0;
}
return retval;
static char errstr[ERR_STR_LEN];
static int err_filled = 0;
const char *retval;
va_list arg;
if (setget == 0)
{
va_start(arg, str);
strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
va_end(arg);
err_filled = 1;
retval = NULL;
}
else
{
if (!err_filled)
retval = NULL;
else
retval = errstr;
err_filled = 0;
}
return retval;
}
/* darwin_dlopen */
static void *darwin_dlopen(const char *path, int mode)
{
void *module = 0;
NSObjectFileImage ofi = 0;
NSObjectFileImageReturnCode ofirc;
void *module = 0;
NSObjectFileImage ofi = 0;
NSObjectFileImageReturnCode ofirc;
/* If we got no path, the app wants the global namespace, use -1 as the marker
in this case */
if (!path)
return (void *)-1;
/* If we got no path, the app wants the global namespace, use -1 as the marker
in this case */
if (!path)
return (void *)-1;
/* Create the object file image, works for things linked with the -bundle arg to ld */
ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
switch (ofirc)
{
case NSObjectFileImageSuccess:
/* It was okay, so use NSLinkModule to link in the image */
module = NSLinkModule(ofi, path,
NSLINKMODULE_OPTION_RETURN_ON_ERROR
| (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
| (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
NSDestroyObjectFileImage(ofi);
break;
case NSObjectFileImageInappropriateFile:
/* It may have been a dynamic library rather than a bundle, try to load it */
module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
break;
default:
/* God knows what we got */
error(0, "Can not open \"%s\"", path);
return 0;
}
if (!module)
error(0, "Can not open \"%s\"", path);
return module;
/* Create the object file image, works for things linked with the -bundle arg to ld */
ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
switch (ofirc)
{
case NSObjectFileImageSuccess:
/* It was okay, so use NSLinkModule to link in the image */
module = NSLinkModule(ofi, path,
NSLINKMODULE_OPTION_RETURN_ON_ERROR
| (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
| (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
NSDestroyObjectFileImage(ofi);
break;
case NSObjectFileImageInappropriateFile:
/* It may have been a dynamic library rather than a bundle, try to load it */
module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
break;
default:
/* God knows what we got */
error(0, "Can not open \"%s\"", path);
return 0;
}
if (!module)
error(0, "Can not open \"%s\"", path);
return module;
}
/* dlsymIntern is used by dlsym to find the symbol */
static void *dlsymIntern(void *handle, const char *symbol)
{
NSSymbol nssym = 0;
/* If the handle is -1, if is the app global context */
if (handle == (void *)-1)
{
/* Global context, use NSLookupAndBindSymbol */
if (NSIsSymbolNameDefined(symbol))
{
nssym = NSLookupAndBindSymbol(symbol);
}
NSSymbol nssym = 0;
/* If the handle is -1, if is the app global context */
if (handle == (void *)-1)
{
/* Global context, use NSLookupAndBindSymbol */
if (NSIsSymbolNameDefined(symbol))
{
nssym = NSLookupAndBindSymbol(symbol);
}
}
/* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
for libraries, and NSLookupSymbolInModule for bundles */
else
{
/* Check for both possible magic numbers depending on x86/ppc byte order */
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
{
nssym = NSLookupSymbolInImage((struct mach_header *)handle,
symbol,
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
}
}
/* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
for libraries, and NSLookupSymbolInModule for bundles */
else
{
/* Check for both possible magic numbers depending on x86/ppc byte order */
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
{
nssym = NSLookupSymbolInImage((struct mach_header *)handle,
symbol,
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
}
}
else
{
nssym = NSLookupSymbolInModule(handle, symbol);
}
}
if (!nssym)
{
error(0, "Symbol \"%s\" Not found", symbol);
return NULL;
}
return NSAddressOfSymbol(nssym);
}
else
{
nssym = NSLookupSymbolInModule(handle, symbol);
}
}
if (!nssym)
{
error(0, "Symbol \"%s\" Not found", symbol);
return NULL;
}
return NSAddressOfSymbol(nssym);
}
static const char *darwin_dlerror(void)
{
return error(1, (char *)NULL);
return error(1, (char *)NULL);
}
static int darwin_dlclose(void *handle)
{
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
error(0, "Can't remove dynamic libraries on darwin");
return 0;
}
if (!NSUnLinkModule(handle, 0))
{
error(0, "unable to unlink module %s", NSNameOfModule(handle));
return 1;
}
return 0;
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
error(0, "Can't remove dynamic libraries on darwin");
return 0;
}
if (!NSUnLinkModule(handle, 0))
{
error(0, "unable to unlink module %s", NSNameOfModule(handle));
return 1;
}
return 0;
}
/* dlsym, prepend the underscore and call dlsymIntern */
static void *darwin_dlsym(void *handle, const char *symbol)
{
static char undersym[257]; /* Saves calls to malloc(3) */
int sym_len = strlen(symbol);
void *value = NULL;
char *malloc_sym = NULL;
static char undersym[257]; /* Saves calls to malloc(3) */
int sym_len = strlen(symbol);
void *value = NULL;
char *malloc_sym = NULL;
if (sym_len < 256)
{
snprintf(undersym, 256, "_%s", symbol);
value = dlsymIntern(handle, undersym);
}
else
{
malloc_sym = malloc(sym_len + 2);
if (malloc_sym)
{
sprintf(malloc_sym, "_%s", symbol);
value = dlsymIntern(handle, malloc_sym);
free(malloc_sym);
}
else
{
error(0, "Unable to allocate memory");
}
}
return value;
if (sym_len < 256)
{
snprintf(undersym, 256, "_%s", symbol);
value = dlsymIntern(handle, undersym);
}
else
{
malloc_sym = malloc(sym_len + 2);
if (malloc_sym)
{
sprintf(malloc_sym, "_%s", symbol);
value = dlsymIntern(handle, malloc_sym);
free(malloc_sym);
}
else
{
error(0, "Unable to allocate memory");
}
}
return value;
}
static int darwin_dladdr(const void *handle, Dl_info *info) {
return 0;
return 0;
}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
@ -252,21 +252,21 @@ static void __attribute__ ((constructor)) ctypes_dlfcn_init(void);
static
#endif
void ctypes_dlfcn_init(void) {
if (dlopen != NULL) {
ctypes_dlsym = dlsym;
ctypes_dlopen = dlopen;
ctypes_dlerror = dlerror;
ctypes_dlclose = dlclose;
ctypes_dladdr = dladdr;
} else {
if (dlopen != NULL) {
ctypes_dlsym = dlsym;
ctypes_dlopen = dlopen;
ctypes_dlerror = dlerror;
ctypes_dlclose = dlclose;
ctypes_dladdr = dladdr;
} else {
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
ctypes_dlsym = darwin_dlsym;
ctypes_dlopen = darwin_dlopen;
ctypes_dlerror = darwin_dlerror;
ctypes_dlclose = darwin_dlclose;
ctypes_dladdr = darwin_dladdr;
ctypes_dlsym = darwin_dlsym;
ctypes_dlopen = darwin_dlopen;
ctypes_dlerror = darwin_dlerror;
ctypes_dlclose = darwin_dlclose;
ctypes_dladdr = darwin_dladdr;
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
}
}
}
#endif /* CTYPES_DARWIN_DLFCN */

View file

@ -27,8 +27,8 @@
/******************************************************************/
typedef union _tagITEM {
ffi_closure closure;
union _tagITEM *next;
ffi_closure closure;
union _tagITEM *next;
} ITEM;
static ITEM *free_list;
@ -36,58 +36,58 @@ static int _pagesize;
static void more_core(void)
{
ITEM *item;
int count, i;
ITEM *item;
int count, i;
/* determine the pagesize */
#ifdef MS_WIN32
if (!_pagesize) {
SYSTEM_INFO systeminfo;
GetSystemInfo(&systeminfo);
_pagesize = systeminfo.dwPageSize;
}
if (!_pagesize) {
SYSTEM_INFO systeminfo;
GetSystemInfo(&systeminfo);
_pagesize = systeminfo.dwPageSize;
}
#else
if (!_pagesize) {
if (!_pagesize) {
#ifdef _SC_PAGESIZE
_pagesize = sysconf(_SC_PAGESIZE);
_pagesize = sysconf(_SC_PAGESIZE);
#else
_pagesize = getpagesize();
_pagesize = getpagesize();
#endif
}
}
#endif
/* calculate the number of nodes to allocate */
count = BLOCKSIZE / sizeof(ITEM);
/* calculate the number of nodes to allocate */
count = BLOCKSIZE / sizeof(ITEM);
/* allocate a memory block */
/* allocate a memory block */
#ifdef MS_WIN32
item = (ITEM *)VirtualAlloc(NULL,
count * sizeof(ITEM),
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (item == NULL)
return;
item = (ITEM *)VirtualAlloc(NULL,
count * sizeof(ITEM),
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (item == NULL)
return;
#else
item = (ITEM *)mmap(NULL,
count * sizeof(ITEM),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (item == (void *)MAP_FAILED)
return;
item = (ITEM *)mmap(NULL,
count * sizeof(ITEM),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (item == (void *)MAP_FAILED)
return;
#endif
#ifdef MALLOC_CLOSURE_DEBUG
printf("block at %p allocated (%d bytes), %d ITEMs\n",
item, count * sizeof(ITEM), count);
printf("block at %p allocated (%d bytes), %d ITEMs\n",
item, count * sizeof(ITEM), count);
#endif
/* put them into the free list */
for (i = 0; i < count; ++i) {
item->next = free_list;
free_list = item;
++item;
}
/* put them into the free list */
for (i = 0; i < count; ++i) {
item->next = free_list;
free_list = item;
++item;
}
}
/******************************************************************/
@ -95,20 +95,20 @@ static void more_core(void)
/* put the item back into the free list */
void _ctypes_free_closure(void *p)
{
ITEM *item = (ITEM *)p;
item->next = free_list;
free_list = item;
ITEM *item = (ITEM *)p;
item->next = free_list;
free_list = item;
}
/* return one item from the free list, allocating more if needed */
void *_ctypes_alloc_closure(void)
{
ITEM *item;
if (!free_list)
more_core();
if (!free_list)
return NULL;
item = free_list;
free_list = item->next;
return item;
ITEM *item;
if (!free_list)
more_core();
if (!free_list)
return NULL;
item = free_list;
free_list = item->next;
return item;
}

View file

@ -23,145 +23,145 @@
static int
PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds)
{
if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->format = NULL;
self->ndim = 0;
self->shape = NULL;
return 0;
if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->format = NULL;
self->ndim = 0;
self->shape = NULL;
return 0;
}
static int
PyCStgDict_clear(StgDictObject *self)
{
Py_CLEAR(self->proto);
Py_CLEAR(self->argtypes);
Py_CLEAR(self->converters);
Py_CLEAR(self->restype);
Py_CLEAR(self->checker);
return 0;
Py_CLEAR(self->proto);
Py_CLEAR(self->argtypes);
Py_CLEAR(self->converters);
Py_CLEAR(self->restype);
Py_CLEAR(self->checker);
return 0;
}
static void
PyCStgDict_dealloc(StgDictObject *self)
{
PyCStgDict_clear(self);
PyMem_Free(self->format);
PyMem_Free(self->shape);
PyMem_Free(self->ffi_type_pointer.elements);
PyDict_Type.tp_dealloc((PyObject *)self);
PyCStgDict_clear(self);
PyMem_Free(self->format);
PyMem_Free(self->shape);
PyMem_Free(self->ffi_type_pointer.elements);
PyDict_Type.tp_dealloc((PyObject *)self);
}
int
PyCStgDict_clone(StgDictObject *dst, StgDictObject *src)
{
char *d, *s;
Py_ssize_t size;
char *d, *s;
Py_ssize_t size;
PyCStgDict_clear(dst);
PyMem_Free(dst->ffi_type_pointer.elements);
PyMem_Free(dst->format);
dst->format = NULL;
PyMem_Free(dst->shape);
dst->shape = NULL;
dst->ffi_type_pointer.elements = NULL;
PyCStgDict_clear(dst);
PyMem_Free(dst->ffi_type_pointer.elements);
PyMem_Free(dst->format);
dst->format = NULL;
PyMem_Free(dst->shape);
dst->shape = NULL;
dst->ffi_type_pointer.elements = NULL;
d = (char *)dst;
s = (char *)src;
memcpy(d + sizeof(PyDictObject),
s + sizeof(PyDictObject),
sizeof(StgDictObject) - sizeof(PyDictObject));
d = (char *)dst;
s = (char *)src;
memcpy(d + sizeof(PyDictObject),
s + sizeof(PyDictObject),
sizeof(StgDictObject) - sizeof(PyDictObject));
Py_XINCREF(dst->proto);
Py_XINCREF(dst->argtypes);
Py_XINCREF(dst->converters);
Py_XINCREF(dst->restype);
Py_XINCREF(dst->checker);
Py_XINCREF(dst->proto);
Py_XINCREF(dst->argtypes);
Py_XINCREF(dst->converters);
Py_XINCREF(dst->restype);
Py_XINCREF(dst->checker);
if (src->format) {
dst->format = PyMem_Malloc(strlen(src->format) + 1);
if (dst->format == NULL)
return -1;
strcpy(dst->format, src->format);
}
if (src->shape) {
dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
if (dst->shape == NULL)
return -1;
memcpy(dst->shape, src->shape,
sizeof(Py_ssize_t) * src->ndim);
}
if (src->format) {
dst->format = PyMem_Malloc(strlen(src->format) + 1);
if (dst->format == NULL)
return -1;
strcpy(dst->format, src->format);
}
if (src->shape) {
dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
if (dst->shape == NULL)
return -1;
memcpy(dst->shape, src->shape,
sizeof(Py_ssize_t) * src->ndim);
}
if (src->ffi_type_pointer.elements == NULL)
return 0;
size = sizeof(ffi_type *) * (src->length + 1);
dst->ffi_type_pointer.elements = PyMem_Malloc(size);
if (dst->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(dst->ffi_type_pointer.elements,
src->ffi_type_pointer.elements,
size);
return 0;
if (src->ffi_type_pointer.elements == NULL)
return 0;
size = sizeof(ffi_type *) * (src->length + 1);
dst->ffi_type_pointer.elements = PyMem_Malloc(size);
if (dst->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(dst->ffi_type_pointer.elements,
src->ffi_type_pointer.elements,
size);
return 0;
}
PyTypeObject PyCStgDict_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"StgDict",
sizeof(StgDictObject),
0,
(destructor)PyCStgDict_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 */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* 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 */
(initproc)PyCStgDict_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"StgDict",
sizeof(StgDictObject),
0,
(destructor)PyCStgDict_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 */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* 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 */
(initproc)PyCStgDict_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
};
/* May return NULL, but does not set an exception! */
StgDictObject *
PyType_stgdict(PyObject *obj)
{
PyTypeObject *type;
PyTypeObject *type;
if (!PyType_Check(obj))
return NULL;
type = (PyTypeObject *)obj;
if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
return NULL;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
if (!PyType_Check(obj))
return NULL;
type = (PyTypeObject *)obj;
if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
return NULL;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
}
/* May return NULL, but does not set an exception! */
@ -172,12 +172,12 @@ PyType_stgdict(PyObject *obj)
StgDictObject *
PyObject_stgdict(PyObject *self)
{
PyTypeObject *type = self->ob_type;
if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
return NULL;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
PyTypeObject *type = self->ob_type;
if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS))
return NULL;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
}
/* descr is the descriptor for a field marked as anonymous. Get all the
@ -186,78 +186,78 @@ PyObject_stgdict(PyObject *self)
*/
static int
MakeFields(PyObject *type, CFieldObject *descr,
Py_ssize_t index, Py_ssize_t offset)
Py_ssize_t index, Py_ssize_t offset)
{
Py_ssize_t i;
PyObject *fields;
PyObject *fieldlist;
Py_ssize_t i;
PyObject *fields;
PyObject *fieldlist;
fields = PyObject_GetAttrString(descr->proto, "_fields_");
if (fields == NULL)
return -1;
fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
Py_DECREF(fields);
if (fieldlist == NULL)
return -1;
fields = PyObject_GetAttrString(descr->proto, "_fields_");
if (fields == NULL)
return -1;
fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
Py_DECREF(fields);
if (fieldlist == NULL)
return -1;
for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
PyObject *fname, *ftype, *bits;
CFieldObject *fdescr;
CFieldObject *new_descr;
/* Convert to PyArg_UnpackTuple... */
if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
Py_DECREF(fieldlist);
return -1;
}
fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
if (fdescr == NULL) {
Py_DECREF(fieldlist);
return -1;
}
if (Py_TYPE(fdescr) != &PyCField_Type) {
PyErr_SetString(PyExc_TypeError, "unexpected type");
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
if (fdescr->anonymous) {
int rc = MakeFields(type, fdescr,
index + fdescr->index,
offset + fdescr->offset);
Py_DECREF(fdescr);
if (rc == -1) {
Py_DECREF(fieldlist);
return -1;
}
continue;
}
new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
if (new_descr == NULL) {
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
assert(Py_TYPE(new_descr) == &PyCField_Type);
new_descr->size = fdescr->size;
new_descr->offset = fdescr->offset + offset;
new_descr->index = fdescr->index + index;
new_descr->proto = fdescr->proto;
Py_XINCREF(new_descr->proto);
new_descr->getfunc = fdescr->getfunc;
new_descr->setfunc = fdescr->setfunc;
for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
PyObject *fname, *ftype, *bits;
CFieldObject *fdescr;
CFieldObject *new_descr;
/* Convert to PyArg_UnpackTuple... */
if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
Py_DECREF(fieldlist);
return -1;
}
fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
if (fdescr == NULL) {
Py_DECREF(fieldlist);
return -1;
}
if (Py_TYPE(fdescr) != &PyCField_Type) {
PyErr_SetString(PyExc_TypeError, "unexpected type");
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
if (fdescr->anonymous) {
int rc = MakeFields(type, fdescr,
index + fdescr->index,
offset + fdescr->offset);
Py_DECREF(fdescr);
if (rc == -1) {
Py_DECREF(fieldlist);
return -1;
}
continue;
}
new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
if (new_descr == NULL) {
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
assert(Py_TYPE(new_descr) == &PyCField_Type);
new_descr->size = fdescr->size;
new_descr->offset = fdescr->offset + offset;
new_descr->index = fdescr->index + index;
new_descr->proto = fdescr->proto;
Py_XINCREF(new_descr->proto);
new_descr->getfunc = fdescr->getfunc;
new_descr->setfunc = fdescr->setfunc;
Py_DECREF(fdescr);
if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
Py_DECREF(fieldlist);
Py_DECREF(new_descr);
return -1;
}
Py_DECREF(new_descr);
}
Py_DECREF(fieldlist);
return 0;
Py_DECREF(fdescr);
if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
Py_DECREF(fieldlist);
Py_DECREF(new_descr);
return -1;
}
Py_DECREF(new_descr);
}
Py_DECREF(fieldlist);
return 0;
}
/* Iterate over the names in the type's _anonymous_ attribute, if present,
@ -265,43 +265,43 @@ MakeFields(PyObject *type, CFieldObject *descr,
static int
MakeAnonFields(PyObject *type)
{
PyObject *anon;
PyObject *anon_names;
Py_ssize_t i;
PyObject *anon;
PyObject *anon_names;
Py_ssize_t i;
anon = PyObject_GetAttrString(type, "_anonymous_");
if (anon == NULL) {
PyErr_Clear();
return 0;
}
anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
Py_DECREF(anon);
if (anon_names == NULL)
return -1;
anon = PyObject_GetAttrString(type, "_anonymous_");
if (anon == NULL) {
PyErr_Clear();
return 0;
}
anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
Py_DECREF(anon);
if (anon_names == NULL)
return -1;
for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
if (descr == NULL) {
Py_DECREF(anon_names);
return -1;
}
assert(Py_TYPE(descr) == &PyCField_Type);
descr->anonymous = 1;
for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
if (descr == NULL) {
Py_DECREF(anon_names);
return -1;
}
assert(Py_TYPE(descr) == &PyCField_Type);
descr->anonymous = 1;
/* descr is in the field descriptor. */
if (-1 == MakeFields(type, (CFieldObject *)descr,
((CFieldObject *)descr)->index,
((CFieldObject *)descr)->offset)) {
Py_DECREF(descr);
Py_DECREF(anon_names);
return -1;
}
Py_DECREF(descr);
}
/* descr is in the field descriptor. */
if (-1 == MakeFields(type, (CFieldObject *)descr,
((CFieldObject *)descr)->index,
((CFieldObject *)descr)->offset)) {
Py_DECREF(descr);
Py_DECREF(anon_names);
return -1;
}
Py_DECREF(descr);
}
Py_DECREF(anon_names);
return 0;
Py_DECREF(anon_names);
return 0;
}
/*
@ -311,265 +311,265 @@ MakeAnonFields(PyObject *type)
int
PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
{
StgDictObject *stgdict, *basedict;
Py_ssize_t len, offset, size, align, i;
Py_ssize_t union_size, total_align;
Py_ssize_t field_size = 0;
int bitofs;
PyObject *isPacked;
int pack = 0;
Py_ssize_t ffi_ofs;
int big_endian;
StgDictObject *stgdict, *basedict;
Py_ssize_t len, offset, size, align, i;
Py_ssize_t union_size, total_align;
Py_ssize_t field_size = 0;
int bitofs;
PyObject *isPacked;
int pack = 0;
Py_ssize_t ffi_ofs;
int big_endian;
/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
be a way to use the old, broken sematics: _fields_ are not extended
but replaced in subclasses.
XXX Remove this in ctypes 1.0!
*/
int use_broken_old_ctypes_semantics;
/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
be a way to use the old, broken sematics: _fields_ are not extended
but replaced in subclasses.
if (fields == NULL)
return 0;
XXX Remove this in ctypes 1.0!
*/
int use_broken_old_ctypes_semantics;
if (fields == NULL)
return 0;
#ifdef WORDS_BIGENDIAN
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
#else
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
#endif
use_broken_old_ctypes_semantics = \
PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
use_broken_old_ctypes_semantics = \
PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
isPacked = PyObject_GetAttrString(type, "_pack_");
if (isPacked) {
pack = PyInt_AsLong(isPacked);
if (pack < 0 || PyErr_Occurred()) {
Py_XDECREF(isPacked);
PyErr_SetString(PyExc_ValueError,
"_pack_ must be a non-negative integer");
return -1;
}
Py_DECREF(isPacked);
} else
PyErr_Clear();
isPacked = PyObject_GetAttrString(type, "_pack_");
if (isPacked) {
pack = PyInt_AsLong(isPacked);
if (pack < 0 || PyErr_Occurred()) {
Py_XDECREF(isPacked);
PyErr_SetString(PyExc_ValueError,
"_pack_ must be a non-negative integer");
return -1;
}
Py_DECREF(isPacked);
} else
PyErr_Clear();
len = PySequence_Length(fields);
if (len == -1) {
PyErr_SetString(PyExc_TypeError,
"'_fields_' must be a sequence of pairs");
return -1;
}
len = PySequence_Length(fields);
if (len == -1) {
PyErr_SetString(PyExc_TypeError,
"'_fields_' must be a sequence of pairs");
return -1;
}
stgdict = PyType_stgdict(type);
if (!stgdict)
return -1;
/* If this structure/union is already marked final we cannot assign
_fields_ anymore. */
stgdict = PyType_stgdict(type);
if (!stgdict)
return -1;
/* If this structure/union is already marked final we cannot assign
_fields_ anymore. */
if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
PyErr_SetString(PyExc_AttributeError,
"_fields_ is final");
return -1;
}
if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
PyErr_SetString(PyExc_AttributeError,
"_fields_ is final");
return -1;
}
if (stgdict->format) {
PyMem_Free(stgdict->format);
stgdict->format = NULL;
}
if (stgdict->format) {
PyMem_Free(stgdict->format);
stgdict->format = NULL;
}
if (stgdict->ffi_type_pointer.elements)
PyMem_Free(stgdict->ffi_type_pointer.elements);
if (stgdict->ffi_type_pointer.elements)
PyMem_Free(stgdict->ffi_type_pointer.elements);
basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
if (basedict && !use_broken_old_ctypes_semantics) {
size = offset = basedict->size;
align = basedict->align;
union_size = 0;
total_align = align ? align : 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (basedict->length + len + 1));
memcpy(stgdict->ffi_type_pointer.elements,
basedict->ffi_type_pointer.elements,
sizeof(ffi_type *) * (basedict->length));
ffi_ofs = basedict->length;
} else {
offset = 0;
size = 0;
align = 0;
union_size = 0;
total_align = 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (len + 1));
ffi_ofs = 0;
}
basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
if (basedict && !use_broken_old_ctypes_semantics) {
size = offset = basedict->size;
align = basedict->align;
union_size = 0;
total_align = align ? align : 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (basedict->length + len + 1));
memcpy(stgdict->ffi_type_pointer.elements,
basedict->ffi_type_pointer.elements,
sizeof(ffi_type *) * (basedict->length));
ffi_ofs = basedict->length;
} else {
offset = 0;
size = 0;
align = 0;
union_size = 0;
total_align = 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (len + 1));
ffi_ofs = 0;
}
assert(stgdict->format == NULL);
if (isStruct && !isPacked) {
stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
} else {
/* PEP3118 doesn't support union, or packed structures (well,
only standard packing, but we dont support the pep for
that). Use 'B' for bytes. */
stgdict->format = _ctypes_alloc_format_string(NULL, "B");
}
assert(stgdict->format == NULL);
if (isStruct && !isPacked) {
stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
} else {
/* PEP3118 doesn't support union, or packed structures (well,
only standard packing, but we dont support the pep for
that). Use 'B' for bytes. */
stgdict->format = _ctypes_alloc_format_string(NULL, "B");
}
#define realdict ((PyObject *)&stgdict->dict)
for (i = 0; i < len; ++i) {
PyObject *name = NULL, *desc = NULL;
PyObject *pair = PySequence_GetItem(fields, i);
PyObject *prop;
StgDictObject *dict;
int bitsize = 0;
for (i = 0; i < len; ++i) {
PyObject *name = NULL, *desc = NULL;
PyObject *pair = PySequence_GetItem(fields, i);
PyObject *prop;
StgDictObject *dict;
int bitsize = 0;
if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
PyErr_SetString(PyExc_AttributeError,
"'_fields_' must be a sequence of pairs");
Py_XDECREF(pair);
return -1;
}
dict = PyType_stgdict(desc);
if (dict == NULL) {
Py_DECREF(pair);
PyErr_Format(PyExc_TypeError,
if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
PyErr_SetString(PyExc_AttributeError,
"'_fields_' must be a sequence of pairs");
Py_XDECREF(pair);
return -1;
}
dict = PyType_stgdict(desc);
if (dict == NULL) {
Py_DECREF(pair);
PyErr_Format(PyExc_TypeError,
#if (PY_VERSION_HEX < 0x02050000)
"second item in _fields_ tuple (index %d) must be a C type",
"second item in _fields_ tuple (index %d) must be a C type",
#else
"second item in _fields_ tuple (index %zd) must be a C type",
"second item in _fields_ tuple (index %zd) must be a C type",
#endif
i);
return -1;
}
stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
stgdict->flags |= TYPEFLAG_HASPOINTER;
dict->flags |= DICTFLAG_FINAL; /* mark field type final */
if (PyTuple_Size(pair) == 3) { /* bits specified */
switch(dict->ffi_type_pointer.type) {
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
break;
i);
return -1;
}
stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
stgdict->flags |= TYPEFLAG_HASPOINTER;
dict->flags |= DICTFLAG_FINAL; /* mark field type final */
if (PyTuple_Size(pair) == 3) { /* bits specified */
switch(dict->ffi_type_pointer.type) {
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
break;
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
#ifdef CTYPES_UNICODE
&& dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
&& dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
#endif
)
break;
/* else fall through */
default:
PyErr_Format(PyExc_TypeError,
"bit fields not allowed for type %s",
((PyTypeObject *)desc)->tp_name);
Py_DECREF(pair);
return -1;
}
if (bitsize <= 0 || bitsize > dict->size * 8) {
PyErr_SetString(PyExc_ValueError,
"number of bits invalid for bit field");
Py_DECREF(pair);
return -1;
}
} else
bitsize = 0;
if (isStruct && !isPacked) {
char *fieldfmt = dict->format ? dict->format : "B";
char *fieldname = PyString_AsString(name);
char *ptr;
Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
char *buf = alloca(len + 2 + 1);
)
break;
/* else fall through */
default:
PyErr_Format(PyExc_TypeError,
"bit fields not allowed for type %s",
((PyTypeObject *)desc)->tp_name);
Py_DECREF(pair);
return -1;
}
if (bitsize <= 0 || bitsize > dict->size * 8) {
PyErr_SetString(PyExc_ValueError,
"number of bits invalid for bit field");
Py_DECREF(pair);
return -1;
}
} else
bitsize = 0;
if (isStruct && !isPacked) {
char *fieldfmt = dict->format ? dict->format : "B";
char *fieldname = PyString_AsString(name);
char *ptr;
Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
char *buf = alloca(len + 2 + 1);
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
PyMem_Free(ptr);
ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
PyMem_Free(ptr);
if (stgdict->format == NULL) {
Py_DECREF(pair);
return -1;
}
}
if (isStruct) {
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
} else /* union */ {
size = 0;
offset = 0;
align = 0;
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
union_size = max(size, union_size);
}
total_align = max(align, total_align);
if (stgdict->format == NULL) {
Py_DECREF(pair);
return -1;
}
}
if (isStruct) {
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
} else /* union */ {
size = 0;
offset = 0;
align = 0;
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
union_size = max(size, union_size);
}
total_align = max(align, total_align);
if (!prop) {
Py_DECREF(pair);
return -1;
}
if (-1 == PyObject_SetAttr(type, name, prop)) {
Py_DECREF(prop);
Py_DECREF(pair);
return -1;
}
Py_DECREF(pair);
Py_DECREF(prop);
}
if (!prop) {
Py_DECREF(pair);
return -1;
}
if (-1 == PyObject_SetAttr(type, name, prop)) {
Py_DECREF(prop);
Py_DECREF(pair);
return -1;
}
Py_DECREF(pair);
Py_DECREF(prop);
}
#undef realdict
if (isStruct && !isPacked) {
char *ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
PyMem_Free(ptr);
if (stgdict->format == NULL)
return -1;
}
if (isStruct && !isPacked) {
char *ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
PyMem_Free(ptr);
if (stgdict->format == NULL)
return -1;
}
if (!isStruct)
size = union_size;
if (!isStruct)
size = union_size;
/* Adjust the size according to the alignment requirements */
size = ((size + total_align - 1) / total_align) * total_align;
/* Adjust the size according to the alignment requirements */
size = ((size + total_align - 1) / total_align) * total_align;
stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
Py_ssize_t,
unsigned short);
stgdict->ffi_type_pointer.size = size;
stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
Py_ssize_t,
unsigned short);
stgdict->ffi_type_pointer.size = size;
stgdict->size = size;
stgdict->align = total_align;
stgdict->length = len; /* ADD ffi_ofs? */
stgdict->size = size;
stgdict->align = total_align;
stgdict->length = len; /* ADD ffi_ofs? */
/* We did check that this flag was NOT set above, it must not
have been set until now. */
if (stgdict->flags & DICTFLAG_FINAL) {
PyErr_SetString(PyExc_AttributeError,
"Structure or union cannot contain itself");
return -1;
}
stgdict->flags |= DICTFLAG_FINAL;
/* We did check that this flag was NOT set above, it must not
have been set until now. */
if (stgdict->flags & DICTFLAG_FINAL) {
PyErr_SetString(PyExc_AttributeError,
"Structure or union cannot contain itself");
return -1;
}
stgdict->flags |= DICTFLAG_FINAL;
return MakeAnonFields(type);
return MakeAnonFields(type);
}

View file

@ -22,7 +22,7 @@ static PyObject *PyCursesError;
/* Utility Functions */
/*
* Check the return code from a curses function and return None
* Check the return code from a curses function and return None
* or raise an exception as appropriate.
*/
@ -30,15 +30,15 @@ static PyObject *
PyCursesCheckERR(int code, char *fname)
{
if (code != ERR) {
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
} else {
if (fname == NULL) {
PyErr_SetString(PyCursesError, catchall_ERR);
} else {
PyErr_Format(PyCursesError, "%s() returned ERR", fname);
}
return NULL;
if (fname == NULL) {
PyErr_SetString(PyCursesError, catchall_ERR);
} else {
PyErr_Format(PyCursesError, "%s() returned ERR", fname);
}
return NULL;
}
}
@ -51,12 +51,12 @@ PyCursesCheckERR(int code, char *fname)
typedef struct {
PyObject_HEAD
PANEL *pan;
PyCursesWindowObject *wo; /* for reference counts */
PyCursesWindowObject *wo; /* for reference counts */
} PyCursesPanelObject;
PyTypeObject PyCursesPanel_Type;
#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
/* Some helper functions. The problem is that there's always a window
associated with a panel. To ensure that Python's GC doesn't pull
@ -88,10 +88,10 @@ static int
insert_lop(PyCursesPanelObject *po)
{
list_of_panels *new;
if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) {
PyErr_NoMemory();
return -1;
PyErr_NoMemory();
return -1;
}
new->po = po;
new->next = lop;
@ -107,17 +107,17 @@ remove_lop(PyCursesPanelObject *po)
temp = lop;
if (temp->po == po) {
lop = temp->next;
free(temp);
return;
lop = temp->next;
free(temp);
return;
}
while (temp->next == NULL || temp->next->po != po) {
if (temp->next == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"remove_lop: can't find Panel Object");
return;
}
temp = temp->next;
if (temp->next == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"remove_lop: can't find Panel Object");
return;
}
temp = temp->next;
}
n = temp->next->next;
free(temp->next);
@ -131,7 +131,7 @@ find_po(PANEL *pan)
{
list_of_panels *temp;
for (temp = lop; temp->po->pan != pan; temp = temp->next)
if (temp->next == NULL) return NULL; /* not found!? */
if (temp->next == NULL) return NULL; /* not found!? */
return temp->po;
}
@ -179,9 +179,9 @@ PyCursesPanel_New(PANEL *pan, PyCursesWindowObject *wo)
if (po == NULL) return NULL;
po->pan = pan;
if (insert_lop(po) < 0) {
po->wo = NULL;
Py_DECREF(po);
return NULL;
po->wo = NULL;
Py_DECREF(po);
return NULL;
}
po->wo = wo;
Py_INCREF(wo);
@ -193,8 +193,8 @@ PyCursesPanel_Dealloc(PyCursesPanelObject *po)
{
(void)del_panel(po->pan);
if (po->wo != NULL) {
Py_DECREF(po->wo);
remove_lop(po);
Py_DECREF(po->wo);
remove_lop(po);
}
PyObject_DEL(po);
}
@ -206,19 +206,19 @@ PyCursesPanel_above(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
pan = panel_above(self->pan);
if (pan == NULL) { /* valid output, it means the calling panel
is on top of the stack */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means the calling panel
is on top of the stack */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -231,19 +231,19 @@ PyCursesPanel_below(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
pan = panel_below(self->pan);
if (pan == NULL) { /* valid output, it means the calling panel
is on the bottom of the stack */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means the calling panel
is on the bottom of the stack */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -262,26 +262,26 @@ PyCursesPanel_replace_panel(PyCursesPanelObject *self, PyObject *args)
PyCursesPanelObject *po;
PyCursesWindowObject *temp;
int rtn;
if (PyTuple_Size(args) != 1) {
PyErr_SetString(PyExc_TypeError, "replace requires one argument");
return NULL;
PyErr_SetString(PyExc_TypeError, "replace requires one argument");
return NULL;
}
if (!PyArg_ParseTuple(args, "O!;window object",
&PyCursesWindow_Type, &temp))
return NULL;
&PyCursesWindow_Type, &temp))
return NULL;
po = find_po(self->pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"replace_panel: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"replace_panel: can't find Panel Object");
return NULL;
}
rtn = replace_panel(self->pan, temp->win);
if (rtn == ERR) {
PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
return NULL;
PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
return NULL;
}
Py_DECREF(po->wo);
po->wo = temp;
@ -302,11 +302,11 @@ static PyObject *
PyCursesPanel_userptr(PyCursesPanelObject *self)
{
PyObject *obj;
PyCursesInitialised;
PyCursesInitialised;
obj = (PyObject *) panel_userptr(self->pan);
if (obj == NULL) {
PyErr_SetString(PyCursesError, "no userptr set");
return NULL;
PyErr_SetString(PyCursesError, "no userptr set");
return NULL;
}
Py_INCREF(obj);
@ -329,7 +329,7 @@ static PyMethodDef PyCursesPanel_Methods[] = {
{"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS},
{"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS},
{"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
static PyObject *
@ -342,20 +342,20 @@ PyCursesPanel_GetAttr(PyCursesPanelObject *self, char *name)
PyTypeObject PyCursesPanel_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_curses_panel.curses panel", /*tp_name*/
sizeof(PyCursesPanelObject), /*tp_basicsize*/
0, /*tp_itemsize*/
"_curses_panel.curses panel", /*tp_name*/
sizeof(PyCursesPanelObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_print*/
(getattrfunc)PyCursesPanel_GetAttr, /*tp_getattr*/
(setattrfunc)0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
};
/* Wrapper for panel_above(NULL). This function returns the bottom
@ -372,16 +372,16 @@ PyCurses_bottom_panel(PyObject *self)
pan = panel_above(NULL);
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -397,8 +397,8 @@ PyCurses_new_panel(PyObject *self, PyObject *args)
return NULL;
pan = new_panel(win->win);
if (pan == NULL) {
PyErr_SetString(PyCursesError, catchall_NULL);
return NULL;
PyErr_SetString(PyCursesError, catchall_NULL);
return NULL;
}
return (PyObject *)PyCursesPanel_New(pan, win);
}
@ -413,28 +413,28 @@ PyCurses_top_panel(PyObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
PyCursesInitialised;
pan = panel_below(NULL);
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
}
static PyObject *PyCurses_update_panels(PyObject *self)
{
{
PyCursesInitialised;
update_panels();
Py_INCREF(Py_None);
@ -449,7 +449,7 @@ static PyMethodDef PyCurses_methods[] = {
{"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS},
{"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS},
{"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
/* Initialization function for the module */
@ -467,7 +467,7 @@ init_curses_panel(void)
/* Create the module and add the functions */
m = Py_InitModule("_curses_panel", PyCurses_methods);
if (m == NULL)
return;
return;
d = PyModule_GetDict(m);
/* For exception _curses_panel.error */

View file

@ -2,7 +2,7 @@
#include "Python.h"
#include "structmember.h"
/* _functools module written and maintained
/* _functools module written and maintained
by Hye-Shik Chang <perky@FreeBSD.org>
with adaptations by Raymond Hettinger <python@rcn.com>
Copyright (c) 2004, 2005, 2006 Python Software Foundation.
@ -14,64 +14,64 @@
static PyObject *
functools_reduce(PyObject *self, PyObject *args)
{
PyObject *seq, *func, *result = NULL, *it;
PyObject *seq, *func, *result = NULL, *it;
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
it = PyObject_GetIter(seq);
if (it == NULL) {
PyErr_SetString(PyExc_TypeError,
"reduce() arg 2 must support iteration");
Py_XDECREF(result);
return NULL;
}
it = PyObject_GetIter(seq);
if (it == NULL) {
PyErr_SetString(PyExc_TypeError,
"reduce() arg 2 must support iteration");
Py_XDECREF(result);
return NULL;
}
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
for (;;) {
PyObject *op2;
for (;;) {
PyObject *op2;
if (args->ob_refcnt > 1) {
Py_DECREF(args);
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
}
if (args->ob_refcnt > 1) {
Py_DECREF(args);
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
}
op2 = PyIter_Next(it);
if (op2 == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
op2 = PyIter_Next(it);
if (op2 == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
if (result == NULL)
result = op2;
else {
PyTuple_SetItem(args, 0, result);
PyTuple_SetItem(args, 1, op2);
if ((result = PyEval_CallObject(func, args)) == NULL)
goto Fail;
}
}
if (result == NULL)
result = op2;
else {
PyTuple_SetItem(args, 0, result);
PyTuple_SetItem(args, 1, op2);
if ((result = PyEval_CallObject(func, args)) == NULL)
goto Fail;
}
}
Py_DECREF(args);
Py_DECREF(args);
if (result == NULL)
PyErr_SetString(PyExc_TypeError,
"reduce() of empty sequence with no initial value");
if (result == NULL)
PyErr_SetString(PyExc_TypeError,
"reduce() of empty sequence with no initial value");
Py_DECREF(it);
return result;
Py_DECREF(it);
return result;
Fail:
Py_XDECREF(args);
Py_XDECREF(result);
Py_DECREF(it);
return NULL;
Py_XDECREF(args);
Py_XDECREF(result);
Py_DECREF(it);
return NULL;
}
PyDoc_STRVAR(reduce_doc,
@ -90,12 +90,12 @@ sequence is empty.");
/* partial object **********************************************************/
typedef struct {
PyObject_HEAD
PyObject *fn;
PyObject *args;
PyObject *kw;
PyObject *dict;
PyObject *weakreflist; /* List of weak references */
PyObject_HEAD
PyObject *fn;
PyObject *args;
PyObject *kw;
PyObject *dict;
PyObject *weakreflist; /* List of weak references */
} partialobject;
static PyTypeObject partial_type;
@ -103,175 +103,175 @@ static PyTypeObject partial_type;
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *func;
partialobject *pto;
PyObject *func;
partialobject *pto;
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError,
"type 'partial' takes at least one argument");
return NULL;
}
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError,
"type 'partial' takes at least one argument");
return NULL;
}
func = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
func = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
/* create partialobject structure */
pto = (partialobject *)type->tp_alloc(type, 0);
if (pto == NULL)
return NULL;
/* create partialobject structure */
pto = (partialobject *)type->tp_alloc(type, 0);
if (pto == NULL)
return NULL;
pto->fn = func;
Py_INCREF(func);
pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
if (pto->args == NULL) {
pto->kw = NULL;
Py_DECREF(pto);
return NULL;
}
if (kw != NULL) {
pto->kw = PyDict_Copy(kw);
if (pto->kw == NULL) {
Py_DECREF(pto);
return NULL;
}
} else {
pto->kw = Py_None;
Py_INCREF(Py_None);
}
pto->fn = func;
Py_INCREF(func);
pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
if (pto->args == NULL) {
pto->kw = NULL;
Py_DECREF(pto);
return NULL;
}
if (kw != NULL) {
pto->kw = PyDict_Copy(kw);
if (pto->kw == NULL) {
Py_DECREF(pto);
return NULL;
}
} else {
pto->kw = Py_None;
Py_INCREF(Py_None);
}
pto->weakreflist = NULL;
pto->dict = NULL;
pto->weakreflist = NULL;
pto->dict = NULL;
return (PyObject *)pto;
return (PyObject *)pto;
}
static void
partial_dealloc(partialobject *pto)
{
PyObject_GC_UnTrack(pto);
if (pto->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) pto);
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
Py_TYPE(pto)->tp_free(pto);
PyObject_GC_UnTrack(pto);
if (pto->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) pto);
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
Py_TYPE(pto)->tp_free(pto);
}
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
PyObject *ret;
PyObject *argappl = NULL, *kwappl = NULL;
PyObject *ret;
PyObject *argappl = NULL, *kwappl = NULL;
assert (PyCallable_Check(pto->fn));
assert (PyTuple_Check(pto->args));
assert (pto->kw == Py_None || PyDict_Check(pto->kw));
assert (PyCallable_Check(pto->fn));
assert (PyTuple_Check(pto->args));
assert (pto->kw == Py_None || PyDict_Check(pto->kw));
if (PyTuple_GET_SIZE(pto->args) == 0) {
argappl = args;
Py_INCREF(args);
} else if (PyTuple_GET_SIZE(args) == 0) {
argappl = pto->args;
Py_INCREF(pto->args);
} else {
argappl = PySequence_Concat(pto->args, args);
if (argappl == NULL)
return NULL;
}
if (PyTuple_GET_SIZE(pto->args) == 0) {
argappl = args;
Py_INCREF(args);
} else if (PyTuple_GET_SIZE(args) == 0) {
argappl = pto->args;
Py_INCREF(pto->args);
} else {
argappl = PySequence_Concat(pto->args, args);
if (argappl == NULL)
return NULL;
}
if (pto->kw == Py_None) {
kwappl = kw;
Py_XINCREF(kw);
} else {
kwappl = PyDict_Copy(pto->kw);
if (kwappl == NULL) {
Py_DECREF(argappl);
return NULL;
}
if (kw != NULL) {
if (PyDict_Merge(kwappl, kw, 1) != 0) {
Py_DECREF(argappl);
Py_DECREF(kwappl);
return NULL;
}
}
}
if (pto->kw == Py_None) {
kwappl = kw;
Py_XINCREF(kw);
} else {
kwappl = PyDict_Copy(pto->kw);
if (kwappl == NULL) {
Py_DECREF(argappl);
return NULL;
}
if (kw != NULL) {
if (PyDict_Merge(kwappl, kw, 1) != 0) {
Py_DECREF(argappl);
Py_DECREF(kwappl);
return NULL;
}
}
}
ret = PyObject_Call(pto->fn, argappl, kwappl);
Py_DECREF(argappl);
Py_XDECREF(kwappl);
return ret;
ret = PyObject_Call(pto->fn, argappl, kwappl);
Py_DECREF(argappl);
Py_XDECREF(kwappl);
return ret;
}
static int
partial_traverse(partialobject *pto, visitproc visit, void *arg)
{
Py_VISIT(pto->fn);
Py_VISIT(pto->args);
Py_VISIT(pto->kw);
Py_VISIT(pto->dict);
return 0;
Py_VISIT(pto->fn);
Py_VISIT(pto->args);
Py_VISIT(pto->kw);
Py_VISIT(pto->dict);
return 0;
}
PyDoc_STRVAR(partial_doc,
"partial(func, *args, **keywords) - new function with partial application\n\
of the given arguments and keywords.\n");
of the given arguments and keywords.\n");
#define OFF(x) offsetof(partialobject, x)
static PyMemberDef partial_memberlist[] = {
{"func", T_OBJECT, OFF(fn), READONLY,
"function object to use in future partial calls"},
{"args", T_OBJECT, OFF(args), READONLY,
"tuple of arguments to future partial calls"},
{"keywords", T_OBJECT, OFF(kw), READONLY,
"dictionary of keyword arguments to future partial calls"},
{NULL} /* Sentinel */
{"func", T_OBJECT, OFF(fn), READONLY,
"function object to use in future partial calls"},
{"args", T_OBJECT, OFF(args), READONLY,
"tuple of arguments to future partial calls"},
{"keywords", T_OBJECT, OFF(kw), READONLY,
"dictionary of keyword arguments to future partial calls"},
{NULL} /* Sentinel */
};
static PyObject *
partial_get_dict(partialobject *pto)
{
if (pto->dict == NULL) {
pto->dict = PyDict_New();
if (pto->dict == NULL)
return NULL;
}
Py_INCREF(pto->dict);
return pto->dict;
if (pto->dict == NULL) {
pto->dict = PyDict_New();
if (pto->dict == NULL)
return NULL;
}
Py_INCREF(pto->dict);
return pto->dict;
}
static int
partial_set_dict(partialobject *pto, PyObject *value)
{
PyObject *tmp;
PyObject *tmp;
/* It is illegal to del p.__dict__ */
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"a partial object's dictionary may not be deleted");
return -1;
}
/* Can only set __dict__ to a dictionary */
if (!PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"setting partial object's dictionary to a non-dict");
return -1;
}
tmp = pto->dict;
Py_INCREF(value);
pto->dict = value;
Py_XDECREF(tmp);
return 0;
/* It is illegal to del p.__dict__ */
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"a partial object's dictionary may not be deleted");
return -1;
}
/* Can only set __dict__ to a dictionary */
if (!PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"setting partial object's dictionary to a non-dict");
return -1;
}
tmp = pto->dict;
Py_INCREF(value);
pto->dict = value;
Py_XDECREF(tmp);
return 0;
}
static PyGetSetDef partial_getsetlist[] = {
{"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
{NULL} /* Sentinel */
{"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
{NULL} /* Sentinel */
};
/* Pickle strategy:
@ -284,85 +284,85 @@ static PyGetSetDef partial_getsetlist[] = {
PyObject *
partial_reduce(partialobject *pto, PyObject *unused)
{
return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
pto->args, pto->kw,
pto->dict ? pto->dict : Py_None);
return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
pto->args, pto->kw,
pto->dict ? pto->dict : Py_None);
}
PyObject *
partial_setstate(partialobject *pto, PyObject *args)
{
PyObject *fn, *fnargs, *kw, *dict;
if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
&fn, &fnargs, &kw, &dict))
return NULL;
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
pto->fn = fn;
pto->args = fnargs;
pto->kw = kw;
if (dict != Py_None) {
pto->dict = dict;
Py_INCREF(dict);
} else {
pto->dict = NULL;
}
Py_INCREF(fn);
Py_INCREF(fnargs);
Py_INCREF(kw);
Py_RETURN_NONE;
PyObject *fn, *fnargs, *kw, *dict;
if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
&fn, &fnargs, &kw, &dict))
return NULL;
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
pto->fn = fn;
pto->args = fnargs;
pto->kw = kw;
if (dict != Py_None) {
pto->dict = dict;
Py_INCREF(dict);
} else {
pto->dict = NULL;
}
Py_INCREF(fn);
Py_INCREF(fnargs);
Py_INCREF(kw);
Py_RETURN_NONE;
}
static PyMethodDef partial_methods[] = {
{"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
{"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
{NULL, NULL} /* sentinel */
{"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
{"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject partial_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"functools.partial", /* tp_name */
sizeof(partialobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)partial_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 */
(ternaryfunc)partial_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
partial_doc, /* tp_doc */
(traverseproc)partial_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
partial_methods, /* tp_methods */
partial_memberlist, /* tp_members */
partial_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(partialobject, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
partial_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"functools.partial", /* tp_name */
sizeof(partialobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)partial_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 */
(ternaryfunc)partial_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
partial_doc, /* tp_doc */
(traverseproc)partial_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
partial_methods, /* tp_methods */
partial_memberlist, /* tp_members */
partial_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(partialobject, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
partial_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
@ -372,31 +372,31 @@ PyDoc_STRVAR(module_doc,
"Tools that operate on functions.");
static PyMethodDef module_methods[] = {
{"reduce", functools_reduce, METH_VARARGS, reduce_doc},
{NULL, NULL} /* sentinel */
{"reduce", functools_reduce, METH_VARARGS, reduce_doc},
{NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
init_functools(void)
{
int i;
PyObject *m;
char *name;
PyTypeObject *typelist[] = {
&partial_type,
NULL
};
int i;
PyObject *m;
char *name;
PyTypeObject *typelist[] = {
&partial_type,
NULL
};
m = Py_InitModule3("_functools", module_methods, module_doc);
if (m == NULL)
return;
m = Py_InitModule3("_functools", module_methods, module_doc);
if (m == NULL)
return;
for (i=0 ; typelist[i] != NULL ; i++) {
if (PyType_Ready(typelist[i]) < 0)
return;
name = strchr(typelist[i]->tp_name, '.');
assert (name != NULL);
Py_INCREF(typelist[i]);
PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
}
for (i=0 ; typelist[i] != NULL ; i++) {
if (PyType_Ready(typelist[i]) < 0)
return;
name = strchr(typelist[i]->tp_name, '.');
assert (name != NULL);
Py_INCREF(typelist[i]);
PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
}
}

View file

@ -197,21 +197,21 @@ EVP_hexdigest(EVPobject *self, PyObject *unused)
/* (not a problem because we hold the GIL by default) */
retval = PyString_FromStringAndSize(NULL, digest_size * 2);
if (!retval)
return NULL;
return NULL;
hex_digest = PyString_AsString(retval);
if (!hex_digest) {
Py_DECREF(retval);
return NULL;
Py_DECREF(retval);
return NULL;
}
/* Make hex version of the digest */
for(i=j=0; i<digest_size; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
c = (c>9) ? c+'a'-10 : c + '0';
c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
c = (c>9) ? c+'a'-10 : c + '0';
c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@ -253,11 +253,11 @@ EVP_update(EVPobject *self, PyObject *args)
}
static PyMethodDef EVP_methods[] = {
{"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
{"digest", (PyCFunction)EVP_digest, METH_NOARGS, EVP_digest__doc__},
{"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
{"digest", (PyCFunction)EVP_digest, METH_NOARGS, EVP_digest__doc__},
{"hexdigest", (PyCFunction)EVP_hexdigest, METH_NOARGS, EVP_hexdigest__doc__},
{"copy", (PyCFunction)EVP_copy, METH_NOARGS, EVP_copy__doc__},
{NULL, NULL} /* sentinel */
{"copy", (PyCFunction)EVP_copy, METH_NOARGS, EVP_copy__doc__},
{NULL, NULL} /* sentinel */
};
static PyObject *
@ -326,14 +326,14 @@ EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
if (!PyArg_Parse(name_obj, "s", &nameStr)) {
PyErr_SetString(PyExc_TypeError, "name must be a string");
PyBuffer_Release(&view);
PyBuffer_Release(&view);
return -1;
}
digest = EVP_get_digestbyname(nameStr);
if (!digest) {
PyErr_SetString(PyExc_ValueError, "unknown hash function");
PyBuffer_Release(&view);
PyBuffer_Release(&view);
return -1;
}
EVP_DigestInit(&self->ctx, digest);
@ -376,11 +376,11 @@ digest_size -- number of bytes in this hashes output\n");
static PyTypeObject EVPtype = {
PyVarObject_HEAD_INIT(NULL, 0)
"_hashlib.HASH", /*tp_name*/
sizeof(EVPobject), /*tp_basicsize*/
0, /*tp_itemsize*/
sizeof(EVPobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)EVP_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(destructor)EVP_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
@ -397,13 +397,13 @@ static PyTypeObject EVPtype = {
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
hashtype_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
EVP_methods, /* tp_methods */
EVP_members, /* tp_members */
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
EVP_methods, /* tp_methods */
EVP_members, /* tp_members */
EVP_getseters, /* tp_getset */
#if 1
0, /* tp_base */
@ -484,7 +484,7 @@ EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
digest = EVP_get_digestbyname(name);
ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf,
view.len);
view.len);
PyBuffer_Release(&view);
return ret_obj;
@ -508,12 +508,12 @@ EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
return NULL; \
} \
\
ret_obj = EVPnew( \
CONST_ ## NAME ## _name_obj, \
NULL, \
CONST_new_ ## NAME ## _ctx_p, \
(unsigned char*)view.buf, view.len); \
PyBuffer_Release(&view); \
ret_obj = EVPnew( \
CONST_ ## NAME ## _name_obj, \
NULL, \
CONST_new_ ## NAME ## _ctx_p, \
(unsigned char*)view.buf, view.len); \
PyBuffer_Release(&view); \
return ret_obj; \
}
@ -554,7 +554,7 @@ static struct PyMethodDef EVP_functions[] = {
CONSTRUCTOR_METH_DEF(sha384),
CONSTRUCTOR_METH_DEF(sha512),
#endif
{NULL, NULL} /* Sentinel */
{NULL, NULL} /* Sentinel */
};

View file

@ -1,4 +1,4 @@
/* Drop in replacement for heapq.py
/* Drop in replacement for heapq.py
C implementation derived directly from heapq.py in Py2.3
which was written by Kevin O'Connor, augmented by Tim Peters,
@ -16,128 +16,128 @@ annotated by Fran
static int
cmp_lt(PyObject *x, PyObject *y)
{
int cmp;
static PyObject *lt = NULL;
int cmp;
static PyObject *lt = NULL;
if (lt == NULL) {
lt = PyString_FromString("__lt__");
if (lt == NULL)
return -1;
}
if (PyObject_HasAttr(x, lt))
return PyObject_RichCompareBool(x, y, Py_LT);
cmp = PyObject_RichCompareBool(y, x, Py_LE);
if (cmp != -1)
cmp = 1 - cmp;
return cmp;
if (lt == NULL) {
lt = PyString_FromString("__lt__");
if (lt == NULL)
return -1;
}
if (PyObject_HasAttr(x, lt))
return PyObject_RichCompareBool(x, y, Py_LT);
cmp = PyObject_RichCompareBool(y, x, Py_LE);
if (cmp != -1)
cmp = 1 - cmp;
return cmp;
}
static int
_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(newitem, parent);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(newitem, parent);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
}
static int
_siftup(PyListObject *heap, Py_ssize_t pos)
{
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, childpos),
PyList_GET_ITEM(heap, rightpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, childpos),
PyList_GET_ITEM(heap, rightpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdown(heap, startpos, pos);
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdown(heap, startpos, pos);
}
static PyObject *
heappush(PyObject *self, PyObject *args)
{
PyObject *heap, *item;
PyObject *heap, *item;
if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_Append(heap, item) == -1)
return NULL;
if (PyList_Append(heap, item) == -1)
return NULL;
if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(heappush_doc,
@ -146,35 +146,35 @@ PyDoc_STRVAR(heappush_doc,
static PyObject *
heappop(PyObject *self, PyObject *heap)
{
PyObject *lastelt, *returnitem;
Py_ssize_t n;
PyObject *lastelt, *returnitem;
Py_ssize_t n;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
/* # raises appropriate IndexError if heap is empty */
n = PyList_GET_SIZE(heap);
if (n == 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
/* # raises appropriate IndexError if heap is empty */
n = PyList_GET_SIZE(heap);
if (n == 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
lastelt = PyList_GET_ITEM(heap, n-1) ;
Py_INCREF(lastelt);
PyList_SetSlice(heap, n-1, n, NULL);
n--;
lastelt = PyList_GET_ITEM(heap, n-1) ;
Py_INCREF(lastelt);
PyList_SetSlice(heap, n-1, n, NULL);
n--;
if (!n)
return lastelt;
returnitem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, lastelt);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
if (!n)
return lastelt;
returnitem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, lastelt);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heappop_doc,
@ -183,29 +183,29 @@ PyDoc_STRVAR(heappop_doc,
static PyObject *
heapreplace(PyObject *self, PyObject *args)
{
PyObject *heap, *item, *returnitem;
PyObject *heap, *item, *returnitem;
if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heapreplace_doc,
@ -215,44 +215,44 @@ This is more efficient than heappop() followed by heappush(), and can be\n\
more appropriate when using a fixed-size heap. Note that the value\n\
returned may be larger than item! That constrains reasonable uses of\n\
this routine unless written as part of a conditional replacement:\n\n\
if item > heap[0]:\n\
item = heapreplace(heap, item)\n");
if item > heap[0]:\n\
item = heapreplace(heap, item)\n");
static PyObject *
heappushpop(PyObject *self, PyObject *args)
{
PyObject *heap, *item, *returnitem;
int cmp;
PyObject *heap, *item, *returnitem;
int cmp;
if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
Py_INCREF(item);
return item;
}
if (PyList_GET_SIZE(heap) < 1) {
Py_INCREF(item);
return item;
}
cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
if (cmp == -1)
return NULL;
if (cmp == 0) {
Py_INCREF(item);
return item;
}
cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
if (cmp == -1)
return NULL;
if (cmp == 0) {
Py_INCREF(item);
return item;
}
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heappushpop_doc,
@ -263,26 +263,26 @@ heappush() followed by a separate call to heappop().");
static PyObject *
heapify(PyObject *self, PyObject *heap)
{
Py_ssize_t i, n;
Py_ssize_t i, n;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
n = PyList_GET_SIZE(heap);
/* Transform bottom-up. The largest index there's any point to
looking at is the largest with a child index in-range, so must
have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
(2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
and that's again n//2-1.
*/
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
n = PyList_GET_SIZE(heap);
/* Transform bottom-up. The largest index there's any point to
looking at is the largest with a child index in-range, so must
have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
(2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
and that's again n//2-1.
*/
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(heapify_doc,
@ -291,79 +291,79 @@ PyDoc_STRVAR(heapify_doc,
static PyObject *
nlargest(PyObject *self, PyObject *args)
{
PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
return NULL;
if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
if (PyList_GET_SIZE(heap) == 0)
goto sortit;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
if (PyList_GET_SIZE(heap) == 0)
goto sortit;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
goto fail;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(sol, elem);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftup((PyListObject *)heap, 0) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
}
sol = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(sol, elem);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftup((PyListObject *)heap, 0) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
}
sortit:
if (PyList_Sort(heap) == -1)
goto fail;
if (PyList_Reverse(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
if (PyList_Sort(heap) == -1)
goto fail;
if (PyList_Reverse(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
fail:
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
}
PyDoc_STRVAR(nlargest_doc,
@ -374,166 +374,166 @@ Equivalent to: sorted(iterable, reverse=True)[:n]\n");
static int
_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(parent, newitem);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(parent, newitem);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
}
static int
_siftupmax(PyListObject *heap, Py_ssize_t pos)
{
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, rightpos),
PyList_GET_ITEM(heap, childpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, rightpos),
PyList_GET_ITEM(heap, childpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdownmax(heap, startpos, pos);
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdownmax(heap, startpos, pos);
}
static PyObject *
nsmallest(PyObject *self, PyObject *args)
{
PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
return NULL;
if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
n = PyList_GET_SIZE(heap);
if (n == 0)
goto sortit;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
n = PyList_GET_SIZE(heap);
if (n == 0)
goto sortit;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftupmax((PyListObject *)heap, i) == -1)
goto fail;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftupmax((PyListObject *)heap, i) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(elem, los);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
los = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(elem, los);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftupmax((PyListObject *)heap, 0) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftupmax((PyListObject *)heap, 0) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
}
sortit:
if (PyList_Sort(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
if (PyList_Sort(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
fail:
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
}
PyDoc_STRVAR(nsmallest_doc,
@ -542,21 +542,21 @@ PyDoc_STRVAR(nsmallest_doc,
Equivalent to: sorted(iterable)[:n]\n");
static PyMethodDef heapq_methods[] = {
{"heappush", (PyCFunction)heappush,
METH_VARARGS, heappush_doc},
{"heappushpop", (PyCFunction)heappushpop,
METH_VARARGS, heappushpop_doc},
{"heappop", (PyCFunction)heappop,
METH_O, heappop_doc},
{"heapreplace", (PyCFunction)heapreplace,
METH_VARARGS, heapreplace_doc},
{"heapify", (PyCFunction)heapify,
METH_O, heapify_doc},
{"nlargest", (PyCFunction)nlargest,
METH_VARARGS, nlargest_doc},
{"nsmallest", (PyCFunction)nsmallest,
METH_VARARGS, nsmallest_doc},
{NULL, NULL} /* sentinel */
{"heappush", (PyCFunction)heappush,
METH_VARARGS, heappush_doc},
{"heappushpop", (PyCFunction)heappushpop,
METH_VARARGS, heappushpop_doc},
{"heappop", (PyCFunction)heappop,
METH_O, heappop_doc},
{"heapreplace", (PyCFunction)heapreplace,
METH_VARARGS, heapreplace_doc},
{"heapify", (PyCFunction)heapify,
METH_O, heapify_doc},
{"nlargest", (PyCFunction)nlargest,
METH_VARARGS, nlargest_doc},
{"nsmallest", (PyCFunction)nsmallest,
METH_VARARGS, nsmallest_doc},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@ -687,11 +687,11 @@ From all times, sorting has always been a Great Art! :-)\n");
PyMODINIT_FUNC
init_heapq(void)
{
PyObject *m;
PyObject *m;
m = Py_InitModule3("_heapq", heapq_methods, module_doc);
if (m == NULL)
return;
PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
m = Py_InitModule3("_heapq", heapq_methods, module_doc);
if (m == NULL)
return;
PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
}

View file

@ -21,10 +21,10 @@
typedef __int64 hs_time;
#define GETTIMEOFDAY(P_HS_TIME) \
{ LARGE_INTEGER _temp; \
QueryPerformanceCounter(&_temp); \
*(P_HS_TIME) = _temp.QuadPart; }
{ LARGE_INTEGER _temp; \
QueryPerformanceCounter(&_temp); \
*(P_HS_TIME) = _temp.QuadPart; }
#else
#ifndef HAVE_GETTIMEOFDAY
@ -284,7 +284,7 @@ unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
do {
/* read byte */
if ((c = fgetc(self->logfp)) == EOF)
if ((c = fgetc(self->logfp)) == EOF)
return ERR_EOF;
accum |= ((c & 0x7F) >> discard) << bits;
bits += (7 - discard);
@ -308,19 +308,19 @@ unpack_string(LogReaderObject *self, PyObject **pvalue)
int err;
int ch;
char *buf;
if ((err = unpack_packed_int(self, &len, 0)))
return err;
buf = (char *)malloc(len);
if (!buf) {
PyErr_NoMemory();
return ERR_EXCEPTION;
PyErr_NoMemory();
return ERR_EXCEPTION;
}
for (i=0; i < len; i++) {
ch = fgetc(self->logfp);
buf[i] = ch;
buf[i] = ch;
if (ch == EOF) {
free(buf);
return ERR_EOF;
@ -459,16 +459,16 @@ logreader_tp_iternext(LogReaderObject *self)
err = ERR_EOF;
else {
self->linetimings = c ? 1 : 0;
goto restart;
}
goto restart;
}
break;
case WHAT_FRAME_TIMES:
if ((c = fgetc(self->logfp)) == EOF)
err = ERR_EOF;
else {
self->frametimings = c ? 1 : 0;
goto restart;
}
goto restart;
}
break;
default:
err = ERR_BAD_RECTYPE;
@ -876,7 +876,7 @@ tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
case PyTrace_LINE: /* we only get these events if we asked for them */
if (self->linetimings)
return pack_lineno_tdelta(self, frame->f_lineno,
get_tdelta(self));
get_tdelta(self));
else
return pack_lineno(self, frame->f_lineno);
@ -1221,39 +1221,39 @@ PyDoc_STRVAR(profiler_object__doc__,
static PyTypeObject ProfilerType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_hotshot.ProfilerType", /* tp_name */
(int) sizeof(ProfilerObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)profiler_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 */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
profiler_object__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
profiler_methods, /* tp_methods */
profiler_members, /* tp_members */
profiler_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
"_hotshot.ProfilerType", /* tp_name */
(int) sizeof(ProfilerObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)profiler_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 */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
profiler_object__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
profiler_methods, /* tp_methods */
profiler_members, /* tp_members */
profiler_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
};
@ -1277,16 +1277,16 @@ PyDoc_STRVAR(logreader__doc__,
Create a log-reader for the timing information file.");
static PySequenceMethods logreader_as_sequence = {
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
(ssizeargfunc)logreader_sq_item, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
0, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
(ssizeargfunc)logreader_sq_item, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
0, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
};
static PyObject *
@ -1305,39 +1305,39 @@ static PyGetSetDef logreader_getsets[] = {
static PyTypeObject LogReaderType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_hotshot.LogReaderType", /* tp_name */
(int) sizeof(LogReaderObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)logreader_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
&logreader_as_sequence, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
logreader__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)logreader_tp_iternext,/* tp_iternext */
logreader_methods, /* tp_methods */
logreader_members, /* tp_members */
logreader_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
"_hotshot.LogReaderType", /* tp_name */
(int) sizeof(LogReaderObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)logreader_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
&logreader_as_sequence, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
logreader__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)logreader_tp_iternext,/* tp_iternext */
logreader_methods, /* tp_methods */
logreader_members, /* tp_members */
logreader_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
};
static PyObject *
@ -1463,8 +1463,8 @@ write_header(ProfilerObject *self)
temp = PySys_GetObject("path");
if (temp == NULL || !PyList_Check(temp)) {
PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
return -1;
PyErr_SetString(PyExc_RuntimeError, "sys.path must be a list");
return -1;
}
len = PyList_GET_SIZE(temp);
for (i = 0; i < len; ++i) {
@ -1562,7 +1562,7 @@ hotshot_coverage(PyObject *unused, PyObject *args)
return result;
}
PyDoc_VAR(resolution__doc__) =
PyDoc_VAR(resolution__doc__) =
#ifdef MS_WINDOWS
PyDoc_STR(
"resolution() -> (performance-counter-ticks, update-frequency)\n"

View file

@ -58,8 +58,8 @@ copy_grouping(char* s)
PyObject *result, *val = NULL;
if (s[0] == '\0')
/* empty string: no grouping at all */
return PyList_New(0);
/* empty string: no grouping at all */
return PyList_New(0);
for (i = 0; s[i] != '\0' && s[i] != CHAR_MAX; i++)
; /* nothing */
@ -172,23 +172,23 @@ PyLocale_setlocale(PyObject* self, PyObject* args)
#endif
if (locale) {
/* set locale */
result = setlocale(category, locale);
if (!result) {
/* operation failed, no setting was changed */
PyErr_SetString(Error, "unsupported locale setting");
return NULL;
}
result_object = PyString_FromString(result);
if (!result_object)
return NULL;
/* record changes to LC_CTYPE */
if (category == LC_CTYPE || category == LC_ALL)
fixup_ulcase();
/* set locale */
result = setlocale(category, locale);
if (!result) {
/* operation failed, no setting was changed */
PyErr_SetString(Error, "unsupported locale setting");
return NULL;
}
result_object = PyString_FromString(result);
if (!result_object)
return NULL;
/* record changes to LC_CTYPE */
if (category == LC_CTYPE || category == LC_ALL)
fixup_ulcase();
/* things that got wrong up to here are ignored */
PyErr_Clear();
} else {
/* get locale */
/* get locale */
result = setlocale(category, NULL);
if (!result) {
PyErr_SetString(Error, "locale query failed");
@ -276,7 +276,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
{
#if !defined(HAVE_WCSCOLL) || !defined(Py_USING_UNICODE)
char *s1,*s2;
if (!PyArg_ParseTuple(args, "ss:strcoll", &s1, &s2))
return NULL;
return PyInt_FromLong(strcoll(s1, s2));
@ -284,7 +284,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
PyObject *os1, *os2, *result = NULL;
wchar_t *ws1 = NULL, *ws2 = NULL;
int rel1 = 0, rel2 = 0, len1, len2;
if (!PyArg_UnpackTuple(args, "strcoll", 2, 2, &os1, &os2))
return NULL;
/* If both arguments are byte strings, use strcoll. */
@ -297,9 +297,9 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
}
/* Convert the non-unicode argument to unicode. */
if (!PyUnicode_Check(os1)) {
os1 = PyUnicode_FromObject(os1);
if (!os1)
return NULL;
os1 = PyUnicode_FromObject(os1);
if (!os1)
return NULL;
rel1 = 1;
}
if (!PyUnicode_Check(os2)) {
@ -309,7 +309,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
Py_DECREF(os1);
}
return NULL;
}
}
rel2 = 1;
}
/* Convert the unicode strings to wchar[]. */
@ -419,9 +419,9 @@ PyLocale_getdefaultlocale(PyObject* self)
#ifdef HAVE_LANGINFO_H
#define LANGINFO(X) {#X, X}
static struct langinfo_constant{
char* name;
int value;
} langinfo_constants[] =
char* name;
int value;
} langinfo_constants[] =
{
/* These constants should exist on any langinfo implementation */
LANGINFO(DAY_1),
@ -534,7 +534,7 @@ PyLocale_nl_langinfo(PyObject* self, PyObject* args)
{
int item, i;
if (!PyArg_ParseTuple(args, "i:nl_langinfo", &item))
return NULL;
return NULL;
/* Check whether this is a supported constant. GNU libc sometimes
returns numeric values in the char* return value, which would
crash PyString_FromString. */
@ -559,10 +559,10 @@ PyDoc_STRVAR(gettext__doc__,
static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
char *in;
if (!PyArg_ParseTuple(args, "s", &in))
return 0;
return PyString_FromString(gettext(in));
char *in;
if (!PyArg_ParseTuple(args, "s", &in))
return 0;
return PyString_FromString(gettext(in));
}
PyDoc_STRVAR(dgettext__doc__,
@ -572,10 +572,10 @@ PyDoc_STRVAR(dgettext__doc__,
static PyObject*
PyIntl_dgettext(PyObject* self, PyObject *args)
{
char *domain, *in;
if (!PyArg_ParseTuple(args, "zs", &domain, &in))
return 0;
return PyString_FromString(dgettext(domain, in));
char *domain, *in;
if (!PyArg_ParseTuple(args, "zs", &domain, &in))
return 0;
return PyString_FromString(dgettext(domain, in));
}
PyDoc_STRVAR(dcgettext__doc__,
@ -585,11 +585,11 @@ PyDoc_STRVAR(dcgettext__doc__,
static PyObject*
PyIntl_dcgettext(PyObject *self, PyObject *args)
{
char *domain, *msgid;
int category;
if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
return 0;
return PyString_FromString(dcgettext(domain,msgid,category));
char *domain, *msgid;
int category;
if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
return 0;
return PyString_FromString(dcgettext(domain,msgid,category));
}
PyDoc_STRVAR(textdomain__doc__,
@ -599,15 +599,15 @@ PyDoc_STRVAR(textdomain__doc__,
static PyObject*
PyIntl_textdomain(PyObject* self, PyObject* args)
{
char *domain;
if (!PyArg_ParseTuple(args, "z", &domain))
return 0;
domain = textdomain(domain);
if (!domain) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return PyString_FromString(domain);
char *domain;
if (!PyArg_ParseTuple(args, "z", &domain))
return 0;
domain = textdomain(domain);
if (!domain) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return PyString_FromString(domain);
}
PyDoc_STRVAR(bindtextdomain__doc__,
@ -617,19 +617,19 @@ PyDoc_STRVAR(bindtextdomain__doc__,
static PyObject*
PyIntl_bindtextdomain(PyObject* self,PyObject*args)
{
char *domain, *dirname;
if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
return 0;
if (!strlen(domain)) {
PyErr_SetString(Error, "domain must be a non-empty string");
return 0;
}
dirname = bindtextdomain(domain, dirname);
if (!dirname) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return PyString_FromString(dirname);
char *domain, *dirname;
if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
return 0;
if (!strlen(domain)) {
PyErr_SetString(Error, "domain must be a non-empty string");
return 0;
}
dirname = bindtextdomain(domain, dirname);
if (!dirname) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return PyString_FromString(dirname);
}
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
@ -640,28 +640,28 @@ PyDoc_STRVAR(bind_textdomain_codeset__doc__,
static PyObject*
PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args)
{
char *domain,*codeset;
if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
return NULL;
codeset = bind_textdomain_codeset(domain, codeset);
if (codeset)
return PyString_FromString(codeset);
Py_RETURN_NONE;
char *domain,*codeset;
if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
return NULL;
codeset = bind_textdomain_codeset(domain, codeset);
if (codeset)
return PyString_FromString(codeset);
Py_RETURN_NONE;
}
#endif
#endif
static struct PyMethodDef PyLocale_Methods[] = {
{"setlocale", (PyCFunction) PyLocale_setlocale,
{"setlocale", (PyCFunction) PyLocale_setlocale,
METH_VARARGS, setlocale__doc__},
{"localeconv", (PyCFunction) PyLocale_localeconv,
{"localeconv", (PyCFunction) PyLocale_localeconv,
METH_NOARGS, localeconv__doc__},
{"strcoll", (PyCFunction) PyLocale_strcoll,
{"strcoll", (PyCFunction) PyLocale_strcoll,
METH_VARARGS, strcoll__doc__},
{"strxfrm", (PyCFunction) PyLocale_strxfrm,
{"strxfrm", (PyCFunction) PyLocale_strxfrm,
METH_VARARGS, strxfrm__doc__},
#if defined(MS_WINDOWS)
#if defined(MS_WINDOWS)
{"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
#endif
#ifdef HAVE_LANGINFO_H
@ -683,7 +683,7 @@ static struct PyMethodDef PyLocale_Methods[] = {
{"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
#endif
#endif
{NULL, NULL}
};
@ -697,7 +697,7 @@ init_locale(void)
m = Py_InitModule("_locale", PyLocale_Methods);
if (m == NULL)
return;
return;
d = PyModule_GetDict(m);
@ -744,13 +744,13 @@ init_locale(void)
#ifdef HAVE_LANGINFO_H
for (i = 0; langinfo_constants[i].name; i++) {
PyModule_AddIntConstant(m, langinfo_constants[i].name,
langinfo_constants[i].value);
PyModule_AddIntConstant(m, langinfo_constants[i].name,
langinfo_constants[i].value);
}
#endif
}
/*
/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil

File diff suppressed because it is too large Load diff

View file

@ -14,7 +14,7 @@
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
@ -27,11 +27,11 @@ static const double zero = 0.0;
/* acosh(x)
* Method :
* Based on
* acosh(x) = log [ x + sqrt(x*x-1) ]
* acosh(x) = log [ x + sqrt(x*x-1) ]
* we have
* acosh(x) := log(x)+ln2, if x is large; else
* acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
* acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
* acosh(x) := log(x)+ln2, if x is large; else
* acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
* acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
*
* Special cases:
* acosh(x) is NaN with signal if x<1.
@ -41,82 +41,82 @@ static const double zero = 0.0;
double
_Py_acosh(double x)
{
if (Py_IS_NAN(x)) {
return x+x;
}
if (x < 1.) { /* x < 1; return a signaling NaN */
errno = EDOM;
if (Py_IS_NAN(x)) {
return x+x;
}
if (x < 1.) { /* x < 1; return a signaling NaN */
errno = EDOM;
#ifdef Py_NAN
return Py_NAN;
return Py_NAN;
#else
return (x-x)/(x-x);
return (x-x)/(x-x);
#endif
}
else if (x >= two_pow_p28) { /* x > 2**28 */
if (Py_IS_INFINITY(x)) {
return x+x;
} else {
return log(x)+ln2; /* acosh(huge)=log(2x) */
}
}
else if (x == 1.) {
return 0.0; /* acosh(1) = 0 */
}
else if (x > 2.) { /* 2 < x < 2**28 */
double t = x*x;
return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
}
else { /* 1 < x <= 2 */
double t = x - 1.0;
return m_log1p(t + sqrt(2.0*t + t*t));
}
}
else if (x >= two_pow_p28) { /* x > 2**28 */
if (Py_IS_INFINITY(x)) {
return x+x;
} else {
return log(x)+ln2; /* acosh(huge)=log(2x) */
}
}
else if (x == 1.) {
return 0.0; /* acosh(1) = 0 */
}
else if (x > 2.) { /* 2 < x < 2**28 */
double t = x*x;
return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
}
else { /* 1 < x <= 2 */
double t = x - 1.0;
return m_log1p(t + sqrt(2.0*t + t*t));
}
}
/* asinh(x)
* Method :
* Based on
* asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
* we have
* asinh(x) := x if 1+x*x=1,
* := sign(x)*(log(x)+ln2)) for large |x|, else
* := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
* := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
* Based on
* asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
* we have
* asinh(x) := x if 1+x*x=1,
* := sign(x)*(log(x)+ln2)) for large |x|, else
* := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
* := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
*/
double
_Py_asinh(double x)
{
double w;
double absx = fabs(x);
{
double w;
double absx = fabs(x);
if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
return x+x;
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x; /* return x inexact except 0 */
}
if (absx > two_pow_p28) { /* |x| > 2**28 */
w = log(absx)+ln2;
}
else if (absx > 2.0) { /* 2 < |x| < 2**28 */
w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
}
else { /* 2**-28 <= |x| < 2= */
double t = x*x;
w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
}
return copysign(w, x);
if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
return x+x;
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x; /* return x inexact except 0 */
}
if (absx > two_pow_p28) { /* |x| > 2**28 */
w = log(absx)+ln2;
}
else if (absx > 2.0) { /* 2 < |x| < 2**28 */
w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
}
else { /* 2**-28 <= |x| < 2= */
double t = x*x;
w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
}
return copysign(w, x);
}
/* atanh(x)
* Method :
* 1.Reduced x to positive by atanh(-x) = -atanh(x)
* 2.For x>=0.5
* 1 2x x
* 1 2x x
* atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
* 2 1 - x 1 - x
* 2 1 - x 1 - x
*
* For x<0.5
* atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
@ -130,32 +130,32 @@ _Py_asinh(double x)
double
_Py_atanh(double x)
{
double absx;
double t;
double absx;
double t;
if (Py_IS_NAN(x)) {
return x+x;
}
absx = fabs(x);
if (absx >= 1.) { /* |x| >= 1 */
errno = EDOM;
if (Py_IS_NAN(x)) {
return x+x;
}
absx = fabs(x);
if (absx >= 1.) { /* |x| >= 1 */
errno = EDOM;
#ifdef Py_NAN
return Py_NAN;
return Py_NAN;
#else
return x/zero;
return x/zero;
#endif
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x;
}
if (absx < 0.5) { /* |x| < 0.5 */
t = absx+absx;
t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
}
else { /* 0.5 <= |x| <= 1.0 */
t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
}
return copysign(t, x);
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x;
}
if (absx < 0.5) { /* |x| < 0.5 */
t = absx+absx;
t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
}
else { /* 0.5 <= |x| <= 1.0 */
t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
}
return copysign(t, x);
}
/* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed
@ -173,15 +173,15 @@ _Py_expm1(double x)
*/
if (fabs(x) < 0.7) {
double u;
u = exp(x);
if (u == 1.0)
return x;
else
return (u - 1.0) * x / log(u);
double u;
u = exp(x);
if (u == 1.0)
return x;
else
return (u - 1.0) * x / log(u);
}
else
return exp(x) - 1.0;
return exp(x) - 1.0;
}
/* log1p(x) = log(1+x). The log1p function is designed to avoid the
@ -194,7 +194,7 @@ _Py_log1p(double x)
/* For x small, we use the following approach. Let y be the nearest float
to 1+x, then
1+x = y * (1 - (y-1-x)/y)
1+x = y * (1 - (y-1-x)/y)
so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the
second term is well approximated by (y-1-x)/y. If abs(x) >=
@ -213,17 +213,17 @@ _Py_log1p(double x)
double y;
if (fabs(x) < DBL_EPSILON/2.) {
return x;
return x;
} else if (-0.5 <= x && x <= 1.) {
/* WARNING: it's possible than an overeager compiler
will incorrectly optimize the following two lines
to the equivalent of "return log(1.+x)". If this
happens, then results from log1p will be inaccurate
for small x. */
y = 1.+x;
return log(y)-((y-1.)-x)/y;
/* WARNING: it's possible than an overeager compiler
will incorrectly optimize the following two lines
to the equivalent of "return log(1.+x)". If this
happens, then results from log1p will be inaccurate
for small x. */
y = 1.+x;
return log(y)-((y-1.)-x)/y;
} else {
/* NaNs and infinities should end up here */
return log(1.+x);
/* NaNs and infinities should end up here */
return log(1.+x);
}
}

View file

@ -19,14 +19,14 @@
#define CHECK_READABLE(self) \
if (!(self->flags & READABLE)) { \
PyErr_SetString(PyExc_IOError, "connection is write-only"); \
return NULL; \
PyErr_SetString(PyExc_IOError, "connection is write-only"); \
return NULL; \
}
#define CHECK_WRITABLE(self) \
if (!(self->flags & WRITABLE)) { \
PyErr_SetString(PyExc_IOError, "connection is read-only"); \
return NULL; \
PyErr_SetString(PyExc_IOError, "connection is read-only"); \
return NULL; \
}
/*
@ -36,57 +36,57 @@
static PyObject *
connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
ConnectionObject *self;
HANDLE handle;
BOOL readable = TRUE, writable = TRUE;
ConnectionObject *self;
HANDLE handle;
BOOL readable = TRUE, writable = TRUE;
static char *kwlist[] = {"handle", "readable", "writable", NULL};
static char *kwlist[] = {"handle", "readable", "writable", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
&handle, &readable, &writable))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
&handle, &readable, &writable))
return NULL;
if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
PyErr_Format(PyExc_IOError, "invalid handle %zd",
(Py_ssize_t)handle);
return NULL;
}
if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
PyErr_Format(PyExc_IOError, "invalid handle %zd",
(Py_ssize_t)handle);
return NULL;
}
if (!readable && !writable) {
PyErr_SetString(PyExc_ValueError,
"either readable or writable must be true");
return NULL;
}
if (!readable && !writable) {
PyErr_SetString(PyExc_ValueError,
"either readable or writable must be true");
return NULL;
}
self = PyObject_New(ConnectionObject, type);
if (self == NULL)
return NULL;
self = PyObject_New(ConnectionObject, type);
if (self == NULL)
return NULL;
self->weakreflist = NULL;
self->handle = handle;
self->flags = 0;
self->weakreflist = NULL;
self->handle = handle;
self->flags = 0;
if (readable)
self->flags |= READABLE;
if (writable)
self->flags |= WRITABLE;
assert(self->flags >= 1 && self->flags <= 3);
if (readable)
self->flags |= READABLE;
if (writable)
self->flags |= WRITABLE;
assert(self->flags >= 1 && self->flags <= 3);
return (PyObject*)self;
return (PyObject*)self;
}
static void
connection_dealloc(ConnectionObject* self)
{
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject*)self);
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject*)self);
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
}
PyObject_Del(self);
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
}
PyObject_Del(self);
}
/*
@ -96,160 +96,160 @@ connection_dealloc(ConnectionObject* self)
static PyObject *
connection_sendbytes(ConnectionObject *self, PyObject *args)
{
char *buffer;
Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
int res;
char *buffer;
Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
int res;
if (!PyArg_ParseTuple(args, F_RBUFFER "#|" F_PY_SSIZE_T F_PY_SSIZE_T,
&buffer, &length, &offset, &size))
return NULL;
if (!PyArg_ParseTuple(args, F_RBUFFER "#|" F_PY_SSIZE_T F_PY_SSIZE_T,
&buffer, &length, &offset, &size))
return NULL;
CHECK_WRITABLE(self);
CHECK_WRITABLE(self);
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "offset is negative");
return NULL;
}
if (length < offset) {
PyErr_SetString(PyExc_ValueError, "buffer length < offset");
return NULL;
}
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "offset is negative");
return NULL;
}
if (length < offset) {
PyErr_SetString(PyExc_ValueError, "buffer length < offset");
return NULL;
}
if (size == PY_SSIZE_T_MIN) {
size = length - offset;
} else {
if (size < 0) {
PyErr_SetString(PyExc_ValueError, "size is negative");
return NULL;
}
if (offset + size > length) {
PyErr_SetString(PyExc_ValueError,
"buffer length < offset + size");
return NULL;
}
}
if (size == PY_SSIZE_T_MIN) {
size = length - offset;
} else {
if (size < 0) {
PyErr_SetString(PyExc_ValueError, "size is negative");
return NULL;
}
if (offset + size > length) {
PyErr_SetString(PyExc_ValueError,
"buffer length < offset + size");
return NULL;
}
}
res = conn_send_string(self, buffer + offset, size);
res = conn_send_string(self, buffer + offset, size);
if (res < 0) {
if (PyErr_Occurred())
return NULL;
else
return mp_SetError(PyExc_IOError, res);
}
if (res < 0) {
if (PyErr_Occurred())
return NULL;
else
return mp_SetError(PyExc_IOError, res);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
connection_recvbytes(ConnectionObject *self, PyObject *args)
{
char *freeme = NULL;
Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
PyObject *result = NULL;
char *freeme = NULL;
Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
PyObject *result = NULL;
if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
return NULL;
if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
return NULL;
CHECK_READABLE(self);
CHECK_READABLE(self);
if (maxlength < 0) {
PyErr_SetString(PyExc_ValueError, "maxlength < 0");
return NULL;
}
if (maxlength < 0) {
PyErr_SetString(PyExc_ValueError, "maxlength < 0");
return NULL;
}
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, maxlength);
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, maxlength);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyString_FromStringAndSize(self->buffer, res);
} else {
result = PyString_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyString_FromStringAndSize(self->buffer, res);
} else {
result = PyString_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
return result;
return result;
}
static PyObject *
connection_recvbytes_into(ConnectionObject *self, PyObject *args)
{
char *freeme = NULL, *buffer = NULL;
Py_ssize_t res, length, offset = 0;
PyObject *result = NULL;
Py_buffer pbuf;
char *freeme = NULL, *buffer = NULL;
Py_ssize_t res, length, offset = 0;
PyObject *result = NULL;
Py_buffer pbuf;
CHECK_READABLE(self);
CHECK_READABLE(self);
if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
&pbuf, &offset))
return NULL;
if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
&pbuf, &offset))
return NULL;
buffer = pbuf.buf;
length = pbuf.len;
buffer = pbuf.buf;
length = pbuf.len;
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "negative offset");
goto _error;
}
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "negative offset");
goto _error;
}
if (offset > length) {
PyErr_SetString(PyExc_ValueError, "offset too large");
goto _error;
}
if (offset > length) {
PyErr_SetString(PyExc_ValueError, "offset too large");
goto _error;
}
res = conn_recv_string(self, buffer+offset, length-offset,
&freeme, PY_SSIZE_T_MAX);
res = conn_recv_string(self, buffer+offset, length-offset,
&freeme, PY_SSIZE_T_MAX);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyInt_FromSsize_t(res);
} else {
result = PyObject_CallFunction(BufferTooShort,
F_RBUFFER "#",
freeme, res);
PyMem_Free(freeme);
if (result) {
PyErr_SetObject(BufferTooShort, result);
Py_DECREF(result);
}
goto _error;
}
}
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyInt_FromSsize_t(res);
} else {
result = PyObject_CallFunction(BufferTooShort,
F_RBUFFER "#",
freeme, res);
PyMem_Free(freeme);
if (result) {
PyErr_SetObject(BufferTooShort, result);
Py_DECREF(result);
}
goto _error;
}
}
_cleanup:
PyBuffer_Release(&pbuf);
return result;
PyBuffer_Release(&pbuf);
return result;
_error:
result = NULL;
goto _cleanup;
result = NULL;
goto _cleanup;
}
/*
@ -259,74 +259,74 @@ connection_recvbytes_into(ConnectionObject *self, PyObject *args)
static PyObject *
connection_send_obj(ConnectionObject *self, PyObject *obj)
{
char *buffer;
int res;
Py_ssize_t length;
PyObject *pickled_string = NULL;
char *buffer;
int res;
Py_ssize_t length;
PyObject *pickled_string = NULL;
CHECK_WRITABLE(self);
CHECK_WRITABLE(self);
pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
pickle_protocol, NULL);
if (!pickled_string)
goto failure;
pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
pickle_protocol, NULL);
if (!pickled_string)
goto failure;
if (PyString_AsStringAndSize(pickled_string, &buffer, &length) < 0)
goto failure;
if (PyString_AsStringAndSize(pickled_string, &buffer, &length) < 0)
goto failure;
res = conn_send_string(self, buffer, (int)length);
res = conn_send_string(self, buffer, (int)length);
if (res < 0) {
mp_SetError(PyExc_IOError, res);
goto failure;
}
if (res < 0) {
mp_SetError(PyExc_IOError, res);
goto failure;
}
Py_XDECREF(pickled_string);
Py_RETURN_NONE;
Py_XDECREF(pickled_string);
Py_RETURN_NONE;
failure:
Py_XDECREF(pickled_string);
return NULL;
Py_XDECREF(pickled_string);
return NULL;
}
static PyObject *
connection_recv_obj(ConnectionObject *self)
{
char *freeme = NULL;
Py_ssize_t res;
PyObject *temp = NULL, *result = NULL;
char *freeme = NULL;
Py_ssize_t res;
PyObject *temp = NULL, *result = NULL;
CHECK_READABLE(self);
CHECK_READABLE(self);
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, PY_SSIZE_T_MAX);
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, PY_SSIZE_T_MAX);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
temp = PyString_FromStringAndSize(self->buffer, res);
} else {
temp = PyString_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
temp = PyString_FromStringAndSize(self->buffer, res);
} else {
temp = PyString_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
if (temp)
result = PyObject_CallFunctionObjArgs(pickle_loads,
temp, NULL);
Py_XDECREF(temp);
return result;
if (temp)
result = PyObject_CallFunctionObjArgs(pickle_loads,
temp, NULL);
Py_XDECREF(temp);
return result;
}
/*
@ -336,73 +336,73 @@ connection_recv_obj(ConnectionObject *self)
static PyObject *
connection_poll(ConnectionObject *self, PyObject *args)
{
PyObject *timeout_obj = NULL;
double timeout = 0.0;
int res;
PyObject *timeout_obj = NULL;
double timeout = 0.0;
int res;
CHECK_READABLE(self);
CHECK_READABLE(self);
if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
return NULL;
if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
return NULL;
if (timeout_obj == NULL) {
timeout = 0.0;
} else if (timeout_obj == Py_None) {
timeout = -1.0; /* block forever */
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
}
if (timeout_obj == NULL) {
timeout = 0.0;
} else if (timeout_obj == Py_None) {
timeout = -1.0; /* block forever */
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
}
Py_BEGIN_ALLOW_THREADS
res = conn_poll(self, timeout, _save);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = conn_poll(self, timeout, _save);
Py_END_ALLOW_THREADS
switch (res) {
case TRUE:
Py_RETURN_TRUE;
case FALSE:
Py_RETURN_FALSE;
default:
return mp_SetError(PyExc_IOError, res);
}
switch (res) {
case TRUE:
Py_RETURN_TRUE;
case FALSE:
Py_RETURN_FALSE;
default:
return mp_SetError(PyExc_IOError, res);
}
}
static PyObject *
connection_fileno(ConnectionObject* self)
{
if (self->handle == INVALID_HANDLE_VALUE) {
PyErr_SetString(PyExc_IOError, "handle is invalid");
return NULL;
}
return PyInt_FromLong((long)self->handle);
if (self->handle == INVALID_HANDLE_VALUE) {
PyErr_SetString(PyExc_IOError, "handle is invalid");
return NULL;
}
return PyInt_FromLong((long)self->handle);
}
static PyObject *
connection_close(ConnectionObject *self)
{
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
}
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
connection_repr(ConnectionObject *self)
{
static char *conn_type[] = {"read-only", "write-only", "read-write"};
static char *conn_type[] = {"read-only", "write-only", "read-write"};
assert(self->flags >= 1 && self->flags <= 3);
return FROM_FORMAT("<%s %s, handle %zd>",
conn_type[self->flags - 1],
CONNECTION_NAME, (Py_ssize_t)self->handle);
assert(self->flags >= 1 && self->flags <= 3);
return FROM_FORMAT("<%s %s, handle %zd>",
conn_type[self->flags - 1],
CONNECTION_NAME, (Py_ssize_t)self->handle);
}
/*
@ -412,19 +412,19 @@ connection_repr(ConnectionObject *self)
static PyObject *
connection_closed(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
}
static PyObject *
connection_readable(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->flags & READABLE));
return PyBool_FromLong((long)(self->flags & READABLE));
}
static PyObject *
connection_writable(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->flags & WRITABLE));
return PyBool_FromLong((long)(self->flags & WRITABLE));
}
/*
@ -432,37 +432,37 @@ connection_writable(ConnectionObject *self, void *closure)
*/
static PyMethodDef connection_methods[] = {
{"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
"send the byte data from a readable buffer-like object"},
{"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
"receive byte data as a string"},
{"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
"receive byte data into a writeable buffer-like object\n"
"returns the number of bytes read"},
{"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
"send the byte data from a readable buffer-like object"},
{"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
"receive byte data as a string"},
{"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
"receive byte data into a writeable buffer-like object\n"
"returns the number of bytes read"},
{"send", (PyCFunction)connection_send_obj, METH_O,
"send a (picklable) object"},
{"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
"receive a (picklable) object"},
{"send", (PyCFunction)connection_send_obj, METH_O,
"send a (picklable) object"},
{"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
"receive a (picklable) object"},
{"poll", (PyCFunction)connection_poll, METH_VARARGS,
"whether there is any input available to be read"},
{"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
"file descriptor or handle of the connection"},
{"close", (PyCFunction)connection_close, METH_NOARGS,
"close the connection"},
{"poll", (PyCFunction)connection_poll, METH_VARARGS,
"whether there is any input available to be read"},
{"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
"file descriptor or handle of the connection"},
{"close", (PyCFunction)connection_close, METH_NOARGS,
"close the connection"},
{NULL} /* Sentinel */
{NULL} /* Sentinel */
};
static PyGetSetDef connection_getset[] = {
{"closed", (getter)connection_closed, NULL,
"True if the connection is closed", NULL},
{"readable", (getter)connection_readable, NULL,
"True if the connection is readable", NULL},
{"writable", (getter)connection_writable, NULL,
"True if the connection is writable", NULL},
{NULL}
{"closed", (getter)connection_closed, NULL,
"True if the connection is closed", NULL},
{"readable", (getter)connection_readable, NULL,
"True if the connection is readable", NULL},
{"writable", (getter)connection_writable, NULL,
"True if the connection is writable", NULL},
{NULL}
};
/*
@ -470,50 +470,50 @@ static PyGetSetDef connection_getset[] = {
*/
PyDoc_STRVAR(connection_doc,
"Connection type whose constructor signature is\n\n"
" Connection(handle, readable=True, writable=True).\n\n"
"The constructor does *not* duplicate the handle.");
"Connection type whose constructor signature is\n\n"
" Connection(handle, readable=True, writable=True).\n\n"
"The constructor does *not* duplicate the handle.");
PyTypeObject CONNECTION_TYPE = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing." CONNECTION_NAME,
/* tp_basicsize */ sizeof(ConnectionObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)connection_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_compare */ 0,
/* tp_repr */ (reprfunc)connection_repr,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_WEAKREFS,
/* tp_doc */ connection_doc,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ connection_methods,
/* tp_members */ 0,
/* tp_getset */ connection_getset,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ connection_new,
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing." CONNECTION_NAME,
/* tp_basicsize */ sizeof(ConnectionObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)connection_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_compare */ 0,
/* tp_repr */ (reprfunc)connection_repr,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_WEAKREFS,
/* tp_doc */ connection_doc,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ connection_methods,
/* tp_members */ 0,
/* tp_getset */ connection_getset,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ connection_new,
};
#endif /* CONNECTION_H */

View file

@ -9,9 +9,9 @@
#include "multiprocessing.h"
#ifdef SCM_RIGHTS
#define HAVE_FD_TRANSFER 1
#define HAVE_FD_TRANSFER 1
#else
#define HAVE_FD_TRANSFER 0
#define HAVE_FD_TRANSFER 0
#endif
PyObject *create_win32_namespace(void);
@ -26,46 +26,46 @@ PyObject *ProcessError, *BufferTooShort;
PyObject *
mp_SetError(PyObject *Type, int num)
{
switch (num) {
switch (num) {
#ifdef MS_WINDOWS
case MP_STANDARD_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, 0);
break;
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
break;
case MP_STANDARD_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, 0);
break;
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
break;
#else /* !MS_WINDOWS */
case MP_STANDARD_ERROR:
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_OSError;
PyErr_SetFromErrno(Type);
break;
case MP_STANDARD_ERROR:
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_OSError;
PyErr_SetFromErrno(Type);
break;
#endif /* !MS_WINDOWS */
case MP_MEMORY_ERROR:
PyErr_NoMemory();
break;
case MP_END_OF_FILE:
PyErr_SetNone(PyExc_EOFError);
break;
case MP_EARLY_END_OF_FILE:
PyErr_SetString(PyExc_IOError,
"got end of file during message");
break;
case MP_BAD_MESSAGE_LENGTH:
PyErr_SetString(PyExc_IOError, "bad message length");
break;
case MP_EXCEPTION_HAS_BEEN_SET:
break;
default:
PyErr_Format(PyExc_RuntimeError,
"unkown error number %d", num);
}
return NULL;
case MP_MEMORY_ERROR:
PyErr_NoMemory();
break;
case MP_END_OF_FILE:
PyErr_SetNone(PyExc_EOFError);
break;
case MP_EARLY_END_OF_FILE:
PyErr_SetString(PyExc_IOError,
"got end of file during message");
break;
case MP_BAD_MESSAGE_LENGTH:
PyErr_SetString(PyExc_IOError, "bad message length");
break;
case MP_EXCEPTION_HAS_BEEN_SET:
break;
default:
PyErr_Format(PyExc_RuntimeError,
"unkown error number %d", num);
}
return NULL;
}
@ -82,8 +82,8 @@ HANDLE sigint_event = NULL;
static BOOL WINAPI
ProcessingCtrlHandler(DWORD dwCtrlType)
{
SetEvent(sigint_event);
return FALSE;
SetEvent(sigint_event);
return FALSE;
}
/*
@ -101,72 +101,72 @@ ProcessingCtrlHandler(DWORD dwCtrlType)
static PyObject *
multiprocessing_sendfd(PyObject *self, PyObject *args)
{
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
return NULL;
if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
*(int*)CMSG_DATA(cmsg) = fd;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
*(int*)CMSG_DATA(cmsg) = fd;
Py_BEGIN_ALLOW_THREADS
res = sendmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = sendmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
static PyObject *
multiprocessing_recvfd(PyObject *self, PyObject *args)
{
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
if (!PyArg_ParseTuple(args, "i", &conn))
return NULL;
if (!PyArg_ParseTuple(args, "i", &conn))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
Py_BEGIN_ALLOW_THREADS
res = recvmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = recvmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
fd = *(int*)CMSG_DATA(cmsg);
return Py_BuildValue("i", fd);
fd = *(int*)CMSG_DATA(cmsg);
return Py_BuildValue("i", fd);
}
#endif /* HAVE_FD_TRANSFER */
@ -181,14 +181,14 @@ multiprocessing_recvfd(PyObject *self, PyObject *args)
static PyObject*
multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
{
void *buffer;
Py_ssize_t buffer_len;
void *buffer;
Py_ssize_t buffer_len;
if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
return NULL;
if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
return NULL;
return Py_BuildValue("N" F_PY_SSIZE_T,
PyLong_FromVoidPtr(buffer), buffer_len);
return Py_BuildValue("N" F_PY_SSIZE_T,
PyLong_FromVoidPtr(buffer), buffer_len);
}
@ -197,20 +197,20 @@ multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
*/
static PyMethodDef module_methods[] = {
{"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
"address_of_buffer(obj) -> int\n"
"Return address of obj assuming obj supports buffer inteface"},
{"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
"address_of_buffer(obj) -> int\n"
"Return address of obj assuming obj supports buffer inteface"},
#if HAVE_FD_TRANSFER
{"sendfd", multiprocessing_sendfd, METH_VARARGS,
"sendfd(sockfd, fd) -> None\n"
"Send file descriptor given by fd over the unix domain socket\n"
"whose file decriptor is sockfd"},
{"recvfd", multiprocessing_recvfd, METH_VARARGS,
"recvfd(sockfd) -> fd\n"
"Receive a file descriptor over a unix domain socket\n"
"whose file decriptor is sockfd"},
{"sendfd", multiprocessing_sendfd, METH_VARARGS,
"sendfd(sockfd, fd) -> None\n"
"Send file descriptor given by fd over the unix domain socket\n"
"whose file decriptor is sockfd"},
{"recvfd", multiprocessing_recvfd, METH_VARARGS,
"recvfd(sockfd) -> fd\n"
"Receive a file descriptor over a unix domain socket\n"
"whose file decriptor is sockfd"},
#endif
{NULL}
{NULL}
};
@ -221,98 +221,98 @@ static PyMethodDef module_methods[] = {
PyMODINIT_FUNC
init_multiprocessing(void)
{
PyObject *module, *temp, *value;
PyObject *module, *temp, *value;
/* Initialize module */
module = Py_InitModule("_multiprocessing", module_methods);
if (!module)
return;
/* Initialize module */
module = Py_InitModule("_multiprocessing", module_methods);
if (!module)
return;
/* Get copy of objects from pickle */
temp = PyImport_ImportModule(PICKLE_MODULE);
if (!temp)
return;
pickle_dumps = PyObject_GetAttrString(temp, "dumps");
pickle_loads = PyObject_GetAttrString(temp, "loads");
pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
Py_XDECREF(temp);
/* Get copy of objects from pickle */
temp = PyImport_ImportModule(PICKLE_MODULE);
if (!temp)
return;
pickle_dumps = PyObject_GetAttrString(temp, "dumps");
pickle_loads = PyObject_GetAttrString(temp, "loads");
pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
Py_XDECREF(temp);
/* Get copy of BufferTooShort */
temp = PyImport_ImportModule("multiprocessing");
if (!temp)
return;
BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
Py_XDECREF(temp);
/* Get copy of BufferTooShort */
temp = PyImport_ImportModule("multiprocessing");
if (!temp)
return;
BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
Py_XDECREF(temp);
/* Add connection type to module */
if (PyType_Ready(&ConnectionType) < 0)
return;
Py_INCREF(&ConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
/* Add connection type to module */
if (PyType_Ready(&ConnectionType) < 0)
return;
Py_INCREF(&ConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
#if defined(MS_WINDOWS) || \
#if defined(MS_WINDOWS) || \
(defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
/* Add SemLock type to module */
if (PyType_Ready(&SemLockType) < 0)
return;
Py_INCREF(&SemLockType);
PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
Py_BuildValue("i", SEM_VALUE_MAX));
PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
/* Add SemLock type to module */
if (PyType_Ready(&SemLockType) < 0)
return;
Py_INCREF(&SemLockType);
PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
Py_BuildValue("i", SEM_VALUE_MAX));
PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
#endif
#ifdef MS_WINDOWS
/* Add PipeConnection to module */
if (PyType_Ready(&PipeConnectionType) < 0)
return;
Py_INCREF(&PipeConnectionType);
PyModule_AddObject(module, "PipeConnection",
(PyObject*)&PipeConnectionType);
/* Add PipeConnection to module */
if (PyType_Ready(&PipeConnectionType) < 0)
return;
Py_INCREF(&PipeConnectionType);
PyModule_AddObject(module, "PipeConnection",
(PyObject*)&PipeConnectionType);
/* Initialize win32 class and add to multiprocessing */
temp = create_win32_namespace();
if (!temp)
return;
PyModule_AddObject(module, "win32", temp);
/* Initialize win32 class and add to multiprocessing */
temp = create_win32_namespace();
if (!temp)
return;
PyModule_AddObject(module, "win32", temp);
/* Initialize the event handle used to signal Ctrl-C */
sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!sigint_event) {
PyErr_SetFromWindowsErr(0);
return;
}
if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
PyErr_SetFromWindowsErr(0);
return;
}
/* Initialize the event handle used to signal Ctrl-C */
sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!sigint_event) {
PyErr_SetFromWindowsErr(0);
return;
}
if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
PyErr_SetFromWindowsErr(0);
return;
}
#endif
/* Add configuration macros */
temp = PyDict_New();
if (!temp)
return;
#define ADD_FLAG(name) \
value = Py_BuildValue("i", name); \
if (value == NULL) { Py_DECREF(temp); return; } \
if (PyDict_SetItemString(temp, #name, value) < 0) { \
Py_DECREF(temp); Py_DECREF(value); return; } \
Py_DECREF(value)
/* Add configuration macros */
temp = PyDict_New();
if (!temp)
return;
#define ADD_FLAG(name) \
value = Py_BuildValue("i", name); \
if (value == NULL) { Py_DECREF(temp); return; } \
if (PyDict_SetItemString(temp, #name, value) < 0) { \
Py_DECREF(temp); Py_DECREF(value); return; } \
Py_DECREF(value)
#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
ADD_FLAG(HAVE_SEM_OPEN);
ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
ADD_FLAG(HAVE_SEM_TIMEDWAIT);
ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
ADD_FLAG(HAVE_FD_TRANSFER);
ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
if (PyModule_AddObject(module, "flags", temp) < 0)
return;
if (PyModule_AddObject(module, "flags", temp) < 0)
return;
}

View file

@ -15,7 +15,7 @@
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <winsock2.h>
# include <process.h> /* getpid() */
# include <process.h> /* getpid() */
# ifdef Py_DEBUG
# include <crtdbg.h>
# endif
@ -45,15 +45,15 @@
* Issue 3110 - Solaris does not define SEM_VALUE_MAX
*/
#ifndef SEM_VALUE_MAX
#if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
# define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
#elif defined(_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _SEM_VALUE_MAX
#elif defined(_POSIX_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
#else
# define SEM_VALUE_MAX INT_MAX
#endif
#if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
# define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
#elif defined(_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _SEM_VALUE_MAX
#elif defined(_POSIX_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
#else
# define SEM_VALUE_MAX INT_MAX
#endif
#endif
@ -162,11 +162,11 @@ extern HANDLE sigint_event;
#define CONNECTION_BUFFER_SIZE 1024
typedef struct {
PyObject_HEAD
HANDLE handle;
int flags;
PyObject *weakreflist;
char buffer[CONNECTION_BUFFER_SIZE];
PyObject_HEAD
HANDLE handle;
int flags;
PyObject *weakreflist;
char buffer[CONNECTION_BUFFER_SIZE];
} ConnectionObject;
/*

View file

@ -17,19 +17,19 @@
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
DWORD amount_written;
BOOL ret;
DWORD amount_written;
BOOL ret;
Py_BEGIN_ALLOW_THREADS
ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
Py_END_ALLOW_THREADS
if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
return MP_STANDARD_ERROR;
}
if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
return MP_STANDARD_ERROR;
}
return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
}
/*
@ -40,49 +40,49 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
static Py_ssize_t
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
size_t buflength, char **newbuffer, size_t maxlength)
{
DWORD left, length, full_length, err;
BOOL ret;
*newbuffer = NULL;
DWORD left, length, full_length, err;
BOOL ret;
*newbuffer = NULL;
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
&length, NULL);
Py_END_ALLOW_THREADS
if (ret)
return length;
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
&length, NULL);
Py_END_ALLOW_THREADS
if (ret)
return length;
err = GetLastError();
if (err != ERROR_MORE_DATA) {
if (err == ERROR_BROKEN_PIPE)
return MP_END_OF_FILE;
return MP_STANDARD_ERROR;
}
err = GetLastError();
if (err != ERROR_MORE_DATA) {
if (err == ERROR_BROKEN_PIPE)
return MP_END_OF_FILE;
return MP_STANDARD_ERROR;
}
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
return MP_STANDARD_ERROR;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
return MP_STANDARD_ERROR;
full_length = length + left;
if (full_length > maxlength)
return MP_BAD_MESSAGE_LENGTH;
full_length = length + left;
if (full_length > maxlength)
return MP_BAD_MESSAGE_LENGTH;
*newbuffer = PyMem_Malloc(full_length);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
*newbuffer = PyMem_Malloc(full_length);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
memcpy(*newbuffer, buffer, length);
memcpy(*newbuffer, buffer, length);
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
Py_END_ALLOW_THREADS
if (ret) {
assert(length == left);
return full_length;
} else {
PyMem_Free(*newbuffer);
return MP_STANDARD_ERROR;
}
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
Py_END_ALLOW_THREADS
if (ret) {
assert(length == left);
return full_length;
} else {
PyMem_Free(*newbuffer);
return MP_STANDARD_ERROR;
}
}
/*
@ -92,51 +92,51 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
DWORD bytes, deadline, delay;
int difference, res;
BOOL block = FALSE;
DWORD bytes, deadline, delay;
int difference, res;
BOOL block = FALSE;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
if (timeout == 0.0)
return bytes > 0;
if (timeout == 0.0)
return bytes > 0;
if (timeout < 0.0)
block = TRUE;
else
/* XXX does not check for overflow */
deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
if (timeout < 0.0)
block = TRUE;
else
/* XXX does not check for overflow */
deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
Sleep(0);
Sleep(0);
for (delay = 1 ; ; delay += 1) {
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
else if (bytes > 0)
return TRUE;
for (delay = 1 ; ; delay += 1) {
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
else if (bytes > 0)
return TRUE;
if (!block) {
difference = deadline - GetTickCount();
if (difference < 0)
return FALSE;
if ((int)delay > difference)
delay = difference;
}
if (!block) {
difference = deadline - GetTickCount();
if (difference < 0)
return FALSE;
if ((int)delay > difference)
delay = difference;
}
if (delay > 20)
delay = 20;
if (delay > 20)
delay = 20;
Sleep(delay);
Sleep(delay);
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
if (res)
return MP_EXCEPTION_HAS_BEEN_SET;
}
if (res)
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
/*

View file

@ -11,12 +11,12 @@
enum { RECURSIVE_MUTEX, SEMAPHORE };
typedef struct {
PyObject_HEAD
SEM_HANDLE handle;
long last_tid;
int count;
int maxvalue;
int kind;
PyObject_HEAD
SEM_HANDLE handle;
long last_tid;
int count;
int maxvalue;
int kind;
} SemLockObject;
#define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid)
@ -40,148 +40,148 @@ typedef struct {
static int
_GetSemaphoreValue(HANDLE handle, long *value)
{
long previous;
long previous;
switch (WaitForSingleObject(handle, 0)) {
case WAIT_OBJECT_0:
if (!ReleaseSemaphore(handle, 1, &previous))
return MP_STANDARD_ERROR;
*value = previous + 1;
return 0;
case WAIT_TIMEOUT:
*value = 0;
return 0;
default:
return MP_STANDARD_ERROR;
}
switch (WaitForSingleObject(handle, 0)) {
case WAIT_OBJECT_0:
if (!ReleaseSemaphore(handle, 1, &previous))
return MP_STANDARD_ERROR;
*value = previous + 1;
return 0;
case WAIT_TIMEOUT:
*value = 0;
return 0;
default:
return MP_STANDARD_ERROR;
}
}
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
int blocking = 1;
double timeout;
PyObject *timeout_obj = Py_None;
DWORD res, full_msecs, msecs, start, ticks;
int blocking = 1;
double timeout;
PyObject *timeout_obj = Py_None;
DWORD res, full_msecs, msecs, start, ticks;
static char *kwlist[] = {"block", "timeout", NULL};
static char *kwlist[] = {"block", "timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
/* calculate timeout */
if (!blocking) {
full_msecs = 0;
} else if (timeout_obj == Py_None) {
full_msecs = INFINITE;
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
timeout *= 1000.0; /* convert to millisecs */
if (timeout < 0.0) {
timeout = 0.0;
} else if (timeout >= 0.5 * INFINITE) { /* 25 days */
PyErr_SetString(PyExc_OverflowError,
"timeout is too large");
return NULL;
}
full_msecs = (DWORD)(timeout + 0.5);
}
/* check whether we already own the lock */
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
/* calculate timeout */
if (!blocking) {
full_msecs = 0;
} else if (timeout_obj == Py_None) {
full_msecs = INFINITE;
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
timeout *= 1000.0; /* convert to millisecs */
if (timeout < 0.0) {
timeout = 0.0;
} else if (timeout >= 0.5 * INFINITE) { /* 25 days */
PyErr_SetString(PyExc_OverflowError,
"timeout is too large");
return NULL;
}
full_msecs = (DWORD)(timeout + 0.5);
}
/* check whether we can acquire without blocking */
if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
}
msecs = full_msecs;
start = GetTickCount();
/* check whether we already own the lock */
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
for ( ; ; ) {
HANDLE handles[2] = {self->handle, sigint_event};
/* do the wait */
Py_BEGIN_ALLOW_THREADS
ResetEvent(sigint_event);
res = WaitForMultipleObjects(2, handles, FALSE, msecs);
Py_END_ALLOW_THREADS
/* handle result */
if (res != WAIT_OBJECT_0 + 1)
break;
/* got SIGINT so give signal handler a chance to run */
Sleep(1);
/* if this is main thread let KeyboardInterrupt be raised */
if (PyErr_CheckSignals())
return NULL;
/* recalculate timeout */
if (msecs != INFINITE) {
ticks = GetTickCount();
if ((DWORD)(ticks - start) >= full_msecs)
Py_RETURN_FALSE;
msecs = full_msecs - (ticks - start);
}
}
/* handle result */
switch (res) {
case WAIT_TIMEOUT:
Py_RETURN_FALSE;
case WAIT_OBJECT_0:
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
case WAIT_FAILED:
return PyErr_SetFromWindowsErr(0);
default:
PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
"WaitForMultipleObjects() gave unrecognized "
"value %d", res);
return NULL;
}
/* check whether we can acquire without blocking */
if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
}
msecs = full_msecs;
start = GetTickCount();
for ( ; ; ) {
HANDLE handles[2] = {self->handle, sigint_event};
/* do the wait */
Py_BEGIN_ALLOW_THREADS
ResetEvent(sigint_event);
res = WaitForMultipleObjects(2, handles, FALSE, msecs);
Py_END_ALLOW_THREADS
/* handle result */
if (res != WAIT_OBJECT_0 + 1)
break;
/* got SIGINT so give signal handler a chance to run */
Sleep(1);
/* if this is main thread let KeyboardInterrupt be raised */
if (PyErr_CheckSignals())
return NULL;
/* recalculate timeout */
if (msecs != INFINITE) {
ticks = GetTickCount();
if ((DWORD)(ticks - start) >= full_msecs)
Py_RETURN_FALSE;
msecs = full_msecs - (ticks - start);
}
}
/* handle result */
switch (res) {
case WAIT_TIMEOUT:
Py_RETURN_FALSE;
case WAIT_OBJECT_0:
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
case WAIT_FAILED:
return PyErr_SetFromWindowsErr(0);
default:
PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
"WaitForMultipleObjects() gave unrecognized "
"value %d", res);
return NULL;
}
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
}
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
}
if (!ReleaseSemaphore(self->handle, 1, NULL)) {
if (GetLastError() == ERROR_TOO_MANY_POSTS) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
} else {
return PyErr_SetFromWindowsErr(0);
}
}
if (!ReleaseSemaphore(self->handle, 1, NULL)) {
if (GetLastError() == ERROR_TOO_MANY_POSTS) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
} else {
return PyErr_SetFromWindowsErr(0);
}
}
--self->count;
Py_RETURN_NONE;
--self->count;
Py_RETURN_NONE;
}
#else /* !MS_WINDOWS */
@ -207,59 +207,59 @@ semlock_release(SemLockObject *self, PyObject *args)
int
sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
{
int res;
unsigned long delay, difference;
struct timeval now, tvdeadline, tvdelay;
int res;
unsigned long delay, difference;
struct timeval now, tvdeadline, tvdelay;
errno = 0;
tvdeadline.tv_sec = deadline->tv_sec;
tvdeadline.tv_usec = deadline->tv_nsec / 1000;
errno = 0;
tvdeadline.tv_sec = deadline->tv_sec;
tvdeadline.tv_usec = deadline->tv_nsec / 1000;
for (delay = 0 ; ; delay += 1000) {
/* poll */
if (sem_trywait(sem) == 0)
return 0;
else if (errno != EAGAIN)
return MP_STANDARD_ERROR;
for (delay = 0 ; ; delay += 1000) {
/* poll */
if (sem_trywait(sem) == 0)
return 0;
else if (errno != EAGAIN)
return MP_STANDARD_ERROR;
/* get current time */
if (gettimeofday(&now, NULL) < 0)
return MP_STANDARD_ERROR;
/* get current time */
if (gettimeofday(&now, NULL) < 0)
return MP_STANDARD_ERROR;
/* check for timeout */
if (tvdeadline.tv_sec < now.tv_sec ||
(tvdeadline.tv_sec == now.tv_sec &&
tvdeadline.tv_usec <= now.tv_usec)) {
errno = ETIMEDOUT;
return MP_STANDARD_ERROR;
}
/* check for timeout */
if (tvdeadline.tv_sec < now.tv_sec ||
(tvdeadline.tv_sec == now.tv_sec &&
tvdeadline.tv_usec <= now.tv_usec)) {
errno = ETIMEDOUT;
return MP_STANDARD_ERROR;
}
/* calculate how much time is left */
difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
(tvdeadline.tv_usec - now.tv_usec);
/* calculate how much time is left */
difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
(tvdeadline.tv_usec - now.tv_usec);
/* check delay not too long -- maximum is 20 msecs */
if (delay > 20000)
delay = 20000;
if (delay > difference)
delay = difference;
/* check delay not too long -- maximum is 20 msecs */
if (delay > 20000)
delay = 20000;
if (delay > difference)
delay = difference;
/* sleep */
tvdelay.tv_sec = delay / 1000000;
tvdelay.tv_usec = delay % 1000000;
if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
return MP_STANDARD_ERROR;
/* sleep */
tvdelay.tv_sec = delay / 1000000;
tvdelay.tv_usec = delay % 1000000;
if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
return MP_STANDARD_ERROR;
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
if (res) {
errno = EINTR;
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
if (res) {
errno = EINTR;
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
}
#endif /* !HAVE_SEM_TIMEDWAIT */
@ -267,129 +267,129 @@ sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
int blocking = 1, res;
double timeout;
PyObject *timeout_obj = Py_None;
struct timespec deadline = {0};
struct timeval now;
long sec, nsec;
int blocking = 1, res;
double timeout;
PyObject *timeout_obj = Py_None;
struct timespec deadline = {0};
struct timeval now;
long sec, nsec;
static char *kwlist[] = {"block", "timeout", NULL};
static char *kwlist[] = {"block", "timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
if (timeout_obj != Py_None) {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
if (timeout_obj != Py_None) {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
if (gettimeofday(&now, NULL) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
sec = (long) timeout;
nsec = (long) (1e9 * (timeout - sec) + 0.5);
deadline.tv_sec = now.tv_sec + sec;
deadline.tv_nsec = now.tv_usec * 1000 + nsec;
deadline.tv_sec += (deadline.tv_nsec / 1000000000);
deadline.tv_nsec %= 1000000000;
}
if (gettimeofday(&now, NULL) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
sec = (long) timeout;
nsec = (long) (1e9 * (timeout - sec) + 0.5);
deadline.tv_sec = now.tv_sec + sec;
deadline.tv_nsec = now.tv_usec * 1000 + nsec;
deadline.tv_sec += (deadline.tv_nsec / 1000000000);
deadline.tv_nsec %= 1000000000;
}
do {
Py_BEGIN_ALLOW_THREADS
if (blocking && timeout_obj == Py_None)
res = sem_wait(self->handle);
else if (!blocking)
res = sem_trywait(self->handle);
else
res = sem_timedwait(self->handle, &deadline);
Py_END_ALLOW_THREADS
if (res == MP_EXCEPTION_HAS_BEEN_SET)
break;
} while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
do {
Py_BEGIN_ALLOW_THREADS
if (blocking && timeout_obj == Py_None)
res = sem_wait(self->handle);
else if (!blocking)
res = sem_trywait(self->handle);
else
res = sem_timedwait(self->handle, &deadline);
Py_END_ALLOW_THREADS
if (res == MP_EXCEPTION_HAS_BEEN_SET)
break;
} while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
if (res < 0) {
if (errno == EAGAIN || errno == ETIMEDOUT)
Py_RETURN_FALSE;
else if (errno == EINTR)
return NULL;
else
return PyErr_SetFromErrno(PyExc_OSError);
}
if (res < 0) {
if (errno == EAGAIN || errno == ETIMEDOUT)
Py_RETURN_FALSE;
else if (errno == EINTR)
return NULL;
else
return PyErr_SetFromErrno(PyExc_OSError);
}
++self->count;
self->last_tid = PyThread_get_thread_ident();
++self->count;
self->last_tid = PyThread_get_thread_ident();
Py_RETURN_TRUE;
Py_RETURN_TRUE;
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
} else {
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
} else {
#ifdef HAVE_BROKEN_SEM_GETVALUE
/* We will only check properly the maxvalue == 1 case */
if (self->maxvalue == 1) {
/* make sure that already locked */
if (sem_trywait(self->handle) < 0) {
if (errno != EAGAIN) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* it is already locked as expected */
} else {
/* it was not locked so undo wait and raise */
if (sem_post(self->handle) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyErr_SetString(PyExc_ValueError, "semaphore "
"or lock released too many "
"times");
return NULL;
}
}
/* We will only check properly the maxvalue == 1 case */
if (self->maxvalue == 1) {
/* make sure that already locked */
if (sem_trywait(self->handle) < 0) {
if (errno != EAGAIN) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* it is already locked as expected */
} else {
/* it was not locked so undo wait and raise */
if (sem_post(self->handle) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyErr_SetString(PyExc_ValueError, "semaphore "
"or lock released too many "
"times");
return NULL;
}
}
#else
int sval;
int sval;
/* This check is not an absolute guarantee that the semaphore
does not rise above maxvalue. */
if (sem_getvalue(self->handle, &sval) < 0) {
return PyErr_SetFromErrno(PyExc_OSError);
} else if (sval >= self->maxvalue) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
}
/* This check is not an absolute guarantee that the semaphore
does not rise above maxvalue. */
if (sem_getvalue(self->handle, &sval) < 0) {
return PyErr_SetFromErrno(PyExc_OSError);
} else if (sval >= self->maxvalue) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
}
#endif
}
}
if (sem_post(self->handle) < 0)
return PyErr_SetFromErrno(PyExc_OSError);
if (sem_post(self->handle) < 0)
return PyErr_SetFromErrno(PyExc_OSError);
--self->count;
Py_RETURN_NONE;
--self->count;
Py_RETURN_NONE;
}
#endif /* !MS_WINDOWS */
@ -401,111 +401,111 @@ semlock_release(SemLockObject *self, PyObject *args)
static PyObject *
newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue)
{
SemLockObject *self;
SemLockObject *self;
self = PyObject_New(SemLockObject, type);
if (!self)
return NULL;
self->handle = handle;
self->kind = kind;
self->count = 0;
self->last_tid = 0;
self->maxvalue = maxvalue;
return (PyObject*)self;
self = PyObject_New(SemLockObject, type);
if (!self)
return NULL;
self->handle = handle;
self->kind = kind;
self->count = 0;
self->last_tid = 0;
self->maxvalue = maxvalue;
return (PyObject*)self;
}
static PyObject *
semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
char buffer[256];
SEM_HANDLE handle = SEM_FAILED;
int kind, maxvalue, value;
PyObject *result;
static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
static int counter = 0;
char buffer[256];
SEM_HANDLE handle = SEM_FAILED;
int kind, maxvalue, value;
PyObject *result;
static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
static int counter = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
&kind, &value, &maxvalue))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
&kind, &value, &maxvalue))
return NULL;
if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
PyErr_SetString(PyExc_ValueError, "unrecognized kind");
return NULL;
}
if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
PyErr_SetString(PyExc_ValueError, "unrecognized kind");
return NULL;
}
PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
SEM_CLEAR_ERROR();
handle = SEM_CREATE(buffer, value, maxvalue);
/* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
goto failure;
SEM_CLEAR_ERROR();
handle = SEM_CREATE(buffer, value, maxvalue);
/* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
goto failure;
if (SEM_UNLINK(buffer) < 0)
goto failure;
if (SEM_UNLINK(buffer) < 0)
goto failure;
result = newsemlockobject(type, handle, kind, maxvalue);
if (!result)
goto failure;
result = newsemlockobject(type, handle, kind, maxvalue);
if (!result)
goto failure;
return result;
return result;
failure:
if (handle != SEM_FAILED)
SEM_CLOSE(handle);
mp_SetError(NULL, MP_STANDARD_ERROR);
return NULL;
if (handle != SEM_FAILED)
SEM_CLOSE(handle);
mp_SetError(NULL, MP_STANDARD_ERROR);
return NULL;
}
static PyObject *
semlock_rebuild(PyTypeObject *type, PyObject *args)
{
SEM_HANDLE handle;
int kind, maxvalue;
SEM_HANDLE handle;
int kind, maxvalue;
if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
&handle, &kind, &maxvalue))
return NULL;
if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
&handle, &kind, &maxvalue))
return NULL;
return newsemlockobject(type, handle, kind, maxvalue);
return newsemlockobject(type, handle, kind, maxvalue);
}
static void
semlock_dealloc(SemLockObject* self)
{
if (self->handle != SEM_FAILED)
SEM_CLOSE(self->handle);
PyObject_Del(self);
if (self->handle != SEM_FAILED)
SEM_CLOSE(self->handle);
PyObject_Del(self);
}
static PyObject *
semlock_count(SemLockObject *self)
{
return PyInt_FromLong((long)self->count);
return PyInt_FromLong((long)self->count);
}
static PyObject *
semlock_ismine(SemLockObject *self)
{
/* only makes sense for a lock */
return PyBool_FromLong(ISMINE(self));
/* only makes sense for a lock */
return PyBool_FromLong(ISMINE(self));
}
static PyObject *
semlock_getvalue(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
#else
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
/* some posix implementations use negative numbers to indicate
the number of waiting threads */
if (sval < 0)
sval = 0;
return PyInt_FromLong((long)sval);
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
/* some posix implementations use negative numbers to indicate
the number of waiting threads */
if (sval < 0)
sval = 0;
return PyInt_FromLong((long)sval);
#endif
}
@ -513,28 +513,28 @@ static PyObject *
semlock_iszero(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
if (sem_trywait(self->handle) < 0) {
if (errno == EAGAIN)
Py_RETURN_TRUE;
return mp_SetError(NULL, MP_STANDARD_ERROR);
} else {
if (sem_post(self->handle) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
Py_RETURN_FALSE;
}
if (sem_trywait(self->handle) < 0) {
if (errno == EAGAIN)
Py_RETURN_TRUE;
return mp_SetError(NULL, MP_STANDARD_ERROR);
} else {
if (sem_post(self->handle) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
Py_RETURN_FALSE;
}
#else
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
return PyBool_FromLong((long)sval == 0);
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
return PyBool_FromLong((long)sval == 0);
#endif
}
static PyObject *
semlock_afterfork(SemLockObject *self)
{
self->count = 0;
Py_RETURN_NONE;
self->count = 0;
Py_RETURN_NONE;
}
/*
@ -542,27 +542,27 @@ semlock_afterfork(SemLockObject *self)
*/
static PyMethodDef semlock_methods[] = {
{"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"acquire the semaphore/lock"},
{"release", (PyCFunction)semlock_release, METH_NOARGS,
"release the semaphore/lock"},
{"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"acquire the semaphore/lock"},
{"release", (PyCFunction)semlock_release, METH_NOARGS,
"release the semaphore/lock"},
{"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"enter the semaphore/lock"},
{"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
"exit the semaphore/lock"},
{"_count", (PyCFunction)semlock_count, METH_NOARGS,
"num of `acquire()`s minus num of `release()`s for this process"},
{"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
"whether the lock is owned by this thread"},
{"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
"get the value of the semaphore"},
{"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
"returns whether semaphore has value zero"},
{"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
""},
{"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
"rezero the net acquisition count after fork()"},
{NULL}
"enter the semaphore/lock"},
{"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
"exit the semaphore/lock"},
{"_count", (PyCFunction)semlock_count, METH_NOARGS,
"num of `acquire()`s minus num of `release()`s for this process"},
{"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
"whether the lock is owned by this thread"},
{"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
"get the value of the semaphore"},
{"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
"returns whether semaphore has value zero"},
{"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
""},
{"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
"rezero the net acquisition count after fork()"},
{NULL}
};
/*
@ -570,13 +570,13 @@ static PyMethodDef semlock_methods[] = {
*/
static PyMemberDef semlock_members[] = {
{"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
""},
{"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
""},
{"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
""},
{NULL}
{"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
""},
{"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
""},
{"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
""},
{NULL}
};
/*
@ -584,42 +584,42 @@ static PyMemberDef semlock_members[] = {
*/
PyTypeObject SemLockType = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing.SemLock",
/* tp_basicsize */ sizeof(SemLockObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)semlock_dealloc,
/* 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 */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
/* tp_doc */ "Semaphore/Mutex type",
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ semlock_methods,
/* tp_members */ semlock_members,
/* 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 */ 0,
/* tp_new */ semlock_new,
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing.SemLock",
/* tp_basicsize */ sizeof(SemLockObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)semlock_dealloc,
/* 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 */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
/* tp_doc */ "Semaphore/Mutex type",
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ semlock_methods,
/* tp_members */ semlock_members,
/* 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 */ 0,
/* tp_new */ semlock_new,
};

View file

@ -25,45 +25,45 @@
static Py_ssize_t
_conn_sendall(HANDLE h, char *string, size_t length)
{
char *p = string;
Py_ssize_t res;
char *p = string;
Py_ssize_t res;
while (length > 0) {
res = WRITE(h, p, length);
if (res < 0)
return MP_SOCKET_ERROR;
length -= res;
p += res;
}
while (length > 0) {
res = WRITE(h, p, length);
if (res < 0)
return MP_SOCKET_ERROR;
length -= res;
p += res;
}
return MP_SUCCESS;
return MP_SUCCESS;
}
/*
* Receive string of exact length from file descriptor
* Receive string of exact length from file descriptor
*/
static Py_ssize_t
_conn_recvall(HANDLE h, char *buffer, size_t length)
{
size_t remaining = length;
Py_ssize_t temp;
char *p = buffer;
size_t remaining = length;
Py_ssize_t temp;
char *p = buffer;
while (remaining > 0) {
temp = READ(h, p, remaining);
if (temp <= 0) {
if (temp == 0)
return remaining == length ?
MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
else
return temp;
}
remaining -= temp;
p += temp;
}
while (remaining > 0) {
temp = READ(h, p, remaining);
if (temp <= 0) {
if (temp == 0)
return remaining == length ?
MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
else
return temp;
}
remaining -= temp;
p += temp;
}
return MP_SUCCESS;
return MP_SUCCESS;
}
/*
@ -73,38 +73,38 @@ _conn_recvall(HANDLE h, char *buffer, size_t length)
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
Py_ssize_t res;
/* The "header" of the message is a 32 bit unsigned number (in
network order) which specifies the length of the "body". If
the message is shorter than about 16kb then it is quicker to
combine the "header" and the "body" of the message and send
them at once. */
if (length < (16*1024)) {
char *message;
Py_ssize_t res;
/* The "header" of the message is a 32 bit unsigned number (in
network order) which specifies the length of the "body". If
the message is shorter than about 16kb then it is quicker to
combine the "header" and the "body" of the message and send
them at once. */
if (length < (16*1024)) {
char *message;
message = PyMem_Malloc(length+4);
if (message == NULL)
return MP_MEMORY_ERROR;
message = PyMem_Malloc(length+4);
if (message == NULL)
return MP_MEMORY_ERROR;
*(UINT32*)message = htonl((UINT32)length);
memcpy(message+4, string, length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, message, length+4);
Py_END_ALLOW_THREADS
PyMem_Free(message);
} else {
UINT32 lenbuff;
*(UINT32*)message = htonl((UINT32)length);
memcpy(message+4, string, length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, message, length+4);
Py_END_ALLOW_THREADS
PyMem_Free(message);
} else {
UINT32 lenbuff;
if (length > MAX_MESSAGE_LENGTH)
return MP_BAD_MESSAGE_LENGTH;
if (length > MAX_MESSAGE_LENGTH)
return MP_BAD_MESSAGE_LENGTH;
lenbuff = htonl((UINT32)length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
_conn_sendall(conn->handle, string, length);
Py_END_ALLOW_THREADS
}
return res;
lenbuff = htonl((UINT32)length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
_conn_sendall(conn->handle, string, length);
Py_END_ALLOW_THREADS
}
return res;
}
/*
@ -114,38 +114,38 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
*/
static Py_ssize_t
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
{
int res;
UINT32 ulength;
int res;
UINT32 ulength;
*newbuffer = NULL;
*newbuffer = NULL;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, (char*)&ulength, 4);
Py_END_ALLOW_THREADS
if (res < 0)
return res;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, (char*)&ulength, 4);
Py_END_ALLOW_THREADS
if (res < 0)
return res;
ulength = ntohl(ulength);
if (ulength > maxlength)
return MP_BAD_MESSAGE_LENGTH;
ulength = ntohl(ulength);
if (ulength > maxlength)
return MP_BAD_MESSAGE_LENGTH;
if (ulength <= buflength) {
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? res : ulength;
} else {
*newbuffer = PyMem_Malloc((size_t)ulength);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
}
if (ulength <= buflength) {
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? res : ulength;
} else {
*newbuffer = PyMem_Malloc((size_t)ulength);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
}
}
/*
@ -155,41 +155,41 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
int res;
fd_set rfds;
int res;
fd_set rfds;
/*
* Verify the handle, issue 3321. Not required for windows.
*/
#ifndef MS_WINDOWS
if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
Py_BLOCK_THREADS
PyErr_SetString(PyExc_IOError, "handle out of range in select()");
Py_UNBLOCK_THREADS
return MP_EXCEPTION_HAS_BEEN_SET;
}
#endif
/*
* Verify the handle, issue 3321. Not required for windows.
*/
#ifndef MS_WINDOWS
if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
Py_BLOCK_THREADS
PyErr_SetString(PyExc_IOError, "handle out of range in select()");
Py_UNBLOCK_THREADS
return MP_EXCEPTION_HAS_BEEN_SET;
}
#endif
FD_ZERO(&rfds);
FD_SET((SOCKET)conn->handle, &rfds);
FD_ZERO(&rfds);
FD_SET((SOCKET)conn->handle, &rfds);
if (timeout < 0.0) {
res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
} else {
struct timeval tv;
tv.tv_sec = (long)timeout;
tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
}
if (timeout < 0.0) {
res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
} else {
struct timeval tv;
tv.tv_sec = (long)timeout;
tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
}
if (res < 0) {
return MP_SOCKET_ERROR;
} else if (FD_ISSET(conn->handle, &rfds)) {
return TRUE;
} else {
assert(res == 0);
return FALSE;
}
if (res < 0) {
return MP_SOCKET_ERROR;
} else if (FD_ISSET(conn->handle, &rfds)) {
return TRUE;
} else {
assert(res == 0);
return FALSE;
}
}
/*

View file

@ -19,248 +19,248 @@
static PyObject *
win32_CloseHandle(PyObject *self, PyObject *args)
{
HANDLE hObject;
BOOL success;
HANDLE hObject;
BOOL success;
if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = CloseHandle(hObject);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = CloseHandle(hObject);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_ConnectNamedPipe(PyObject *self, PyObject *args)
{
HANDLE hNamedPipe;
LPOVERLAPPED lpOverlapped;
BOOL success;
HANDLE hNamedPipe;
LPOVERLAPPED lpOverlapped;
BOOL success;
if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
&hNamedPipe, &lpOverlapped))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
&hNamedPipe, &lpOverlapped))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_CreateFile(PyObject *self, PyObject *args)
{
LPCTSTR lpFileName;
DWORD dwDesiredAccess;
DWORD dwShareMode;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes;
HANDLE hTemplateFile;
HANDLE handle;
LPCTSTR lpFileName;
DWORD dwDesiredAccess;
DWORD dwShareMode;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes;
HANDLE hTemplateFile;
HANDLE handle;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
F_DWORD F_DWORD F_HANDLE,
&lpFileName, &dwDesiredAccess, &dwShareMode,
&lpSecurityAttributes, &dwCreationDisposition,
&dwFlagsAndAttributes, &hTemplateFile))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
F_DWORD F_DWORD F_HANDLE,
&lpFileName, &dwDesiredAccess, &dwShareMode,
&lpSecurityAttributes, &dwCreationDisposition,
&dwFlagsAndAttributes, &hTemplateFile))
return NULL;
Py_BEGIN_ALLOW_THREADS
handle = CreateFile(lpFileName, dwDesiredAccess,
dwShareMode, lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
handle = CreateFile(lpFileName, dwDesiredAccess,
dwShareMode, lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
Py_END_ALLOW_THREADS
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_CreateNamedPipe(PyObject *self, PyObject *args)
{
LPCTSTR lpName;
DWORD dwOpenMode;
DWORD dwPipeMode;
DWORD nMaxInstances;
DWORD nOutBufferSize;
DWORD nInBufferSize;
DWORD nDefaultTimeOut;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
HANDLE handle;
LPCTSTR lpName;
DWORD dwOpenMode;
DWORD dwPipeMode;
DWORD nMaxInstances;
DWORD nOutBufferSize;
DWORD nInBufferSize;
DWORD nDefaultTimeOut;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
HANDLE handle;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
F_DWORD F_DWORD F_DWORD F_POINTER,
&lpName, &dwOpenMode, &dwPipeMode,
&nMaxInstances, &nOutBufferSize,
&nInBufferSize, &nDefaultTimeOut,
&lpSecurityAttributes))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
F_DWORD F_DWORD F_DWORD F_POINTER,
&lpName, &dwOpenMode, &dwPipeMode,
&nMaxInstances, &nOutBufferSize,
&nInBufferSize, &nDefaultTimeOut,
&lpSecurityAttributes))
return NULL;
Py_BEGIN_ALLOW_THREADS
handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
nMaxInstances, nOutBufferSize,
nInBufferSize, nDefaultTimeOut,
lpSecurityAttributes);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
nMaxInstances, nOutBufferSize,
nInBufferSize, nDefaultTimeOut,
lpSecurityAttributes);
Py_END_ALLOW_THREADS
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_ExitProcess(PyObject *self, PyObject *args)
{
UINT uExitCode;
UINT uExitCode;
if (!PyArg_ParseTuple(args, "I", &uExitCode))
return NULL;
if (!PyArg_ParseTuple(args, "I", &uExitCode))
return NULL;
#if defined(Py_DEBUG)
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
#endif
#if defined(Py_DEBUG)
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
#endif
ExitProcess(uExitCode);
ExitProcess(uExitCode);
return NULL;
return NULL;
}
static PyObject *
win32_GetLastError(PyObject *self, PyObject *args)
{
return Py_BuildValue(F_DWORD, GetLastError());
return Py_BuildValue(F_DWORD, GetLastError());
}
static PyObject *
win32_OpenProcess(PyObject *self, PyObject *args)
{
DWORD dwDesiredAccess;
BOOL bInheritHandle;
DWORD dwProcessId;
HANDLE handle;
DWORD dwDesiredAccess;
BOOL bInheritHandle;
DWORD dwProcessId;
HANDLE handle;
if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
&dwDesiredAccess, &bInheritHandle, &dwProcessId))
return NULL;
if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
&dwDesiredAccess, &bInheritHandle, &dwProcessId))
return NULL;
handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (handle == NULL)
return PyErr_SetFromWindowsErr(0);
handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (handle == NULL)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_SetNamedPipeHandleState(PyObject *self, PyObject *args)
{
HANDLE hNamedPipe;
PyObject *oArgs[3];
DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
int i;
HANDLE hNamedPipe;
PyObject *oArgs[3];
DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
int i;
if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
&hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
&hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
return NULL;
PyErr_Clear();
PyErr_Clear();
for (i = 0 ; i < 3 ; i++) {
if (oArgs[i] != Py_None) {
dwArgs[i] = PyInt_AsUnsignedLongMask(oArgs[i]);
if (PyErr_Occurred())
return NULL;
pArgs[i] = &dwArgs[i];
}
}
for (i = 0 ; i < 3 ; i++) {
if (oArgs[i] != Py_None) {
dwArgs[i] = PyInt_AsUnsignedLongMask(oArgs[i]);
if (PyErr_Occurred())
return NULL;
pArgs[i] = &dwArgs[i];
}
}
if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
return PyErr_SetFromWindowsErr(0);
if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_WaitNamedPipe(PyObject *self, PyObject *args)
{
LPCTSTR lpNamedPipeName;
DWORD nTimeOut;
BOOL success;
LPCTSTR lpNamedPipeName;
DWORD nTimeOut;
BOOL success;
if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyMethodDef win32_methods[] = {
WIN32_FUNCTION(CloseHandle),
WIN32_FUNCTION(GetLastError),
WIN32_FUNCTION(OpenProcess),
WIN32_FUNCTION(ExitProcess),
WIN32_FUNCTION(ConnectNamedPipe),
WIN32_FUNCTION(CreateFile),
WIN32_FUNCTION(CreateNamedPipe),
WIN32_FUNCTION(SetNamedPipeHandleState),
WIN32_FUNCTION(WaitNamedPipe),
{NULL}
WIN32_FUNCTION(CloseHandle),
WIN32_FUNCTION(GetLastError),
WIN32_FUNCTION(OpenProcess),
WIN32_FUNCTION(ExitProcess),
WIN32_FUNCTION(ConnectNamedPipe),
WIN32_FUNCTION(CreateFile),
WIN32_FUNCTION(CreateNamedPipe),
WIN32_FUNCTION(SetNamedPipeHandleState),
WIN32_FUNCTION(WaitNamedPipe),
{NULL}
};
PyTypeObject Win32Type = {
PyVarObject_HEAD_INIT(NULL, 0)
PyVarObject_HEAD_INIT(NULL, 0)
};
PyObject *
create_win32_namespace(void)
{
Win32Type.tp_name = "_multiprocessing.win32";
Win32Type.tp_methods = win32_methods;
if (PyType_Ready(&Win32Type) < 0)
return NULL;
Py_INCREF(&Win32Type);
Win32Type.tp_name = "_multiprocessing.win32";
Win32Type.tp_methods = win32_methods;
if (PyType_Ready(&Win32Type) < 0)
return NULL;
Py_INCREF(&Win32Type);
WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
WIN32_CONSTANT(F_DWORD, GENERIC_READ);
WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
WIN32_CONSTANT(F_DWORD, INFINITE);
WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
WIN32_CONSTANT(F_DWORD, GENERIC_READ);
WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
WIN32_CONSTANT(F_DWORD, INFINITE);
WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
WIN32_CONSTANT("i", NULL);
WIN32_CONSTANT("i", NULL);
return (PyObject*)&Win32Type;
return (PyObject*)&Win32Type;
}

View file

@ -2,23 +2,23 @@
/* ------------------------------------------------------------------
The code in this module was based on a download from:
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
It was modified in 2002 by Raymond Hettinger as follows:
* the principal computational lines untouched except for tabbing.
* the principal computational lines untouched except for tabbing.
* renamed genrand_res53() to random_random() and wrapped
in python calling/return code.
* renamed genrand_res53() to random_random() and wrapped
in python calling/return code.
* genrand_int32() and the helper functions, init_genrand()
and init_by_array(), were declared static, wrapped in
Python calling/return code. also, their global data
references were replaced with structure references.
* genrand_int32() and the helper functions, init_genrand()
and init_by_array(), were declared static, wrapped in
Python calling/return code. also, their global data
references were replaced with structure references.
* unused functions from the original were deleted.
new, original C python code was added to implement the
Random() interface.
* unused functions from the original were deleted.
new, original C python code was added to implement the
Random() interface.
The following are the verbatim comments from the original code:
@ -36,15 +36,15 @@
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
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.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
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
@ -67,24 +67,24 @@
/* ---------------------------------------------------------------*/
#include "Python.h"
#include <time.h> /* for seeding to current time */
#include <time.h> /* for seeding to current time */
/* Period parameters -- These are all magic. Don't change. */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
typedef struct {
PyObject_HEAD
unsigned long state[N];
int index;
PyObject_HEAD
unsigned long state[N];
int index;
} RandomObject;
static PyTypeObject Random_Type;
#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
/* Random methods */
@ -94,28 +94,28 @@ static PyTypeObject Random_Type;
static unsigned long
genrand_int32(RandomObject *self)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
unsigned long *mt;
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
unsigned long *mt;
mt = self->state;
if (self->index >= N) { /* generate N words at one time */
int kk;
mt = self->state;
if (self->index >= N) { /* generate N words at one time */
int kk;
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
self->index = 0;
}
self->index = 0;
}
y = mt[self->index++];
y ^= (y >> 11);
@ -137,31 +137,31 @@ genrand_int32(RandomObject *self)
static PyObject *
random_random(RandomObject *self)
{
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
/* initializes mt[N] with a seed */
static void
init_genrand(RandomObject *self, unsigned long s)
{
int mti;
unsigned long *mt;
int mti;
unsigned long *mt;
mt = self->state;
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
self->index = mti;
return;
mt = self->state;
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
self->index = mti;
return;
}
/* initialize by an array with array-length */
@ -170,28 +170,28 @@ init_genrand(RandomObject *self, unsigned long s)
static PyObject *
init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length)
{
unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
unsigned long *mt;
unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
unsigned long *mt;
mt = self->state;
init_genrand(self, 19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt = self->state;
init_genrand(self, 19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
Py_INCREF(Py_None);
@ -206,167 +206,167 @@ init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_le
static PyObject *
random_seed(RandomObject *self, PyObject *args)
{
PyObject *result = NULL; /* guilty until proved innocent */
PyObject *masklower = NULL;
PyObject *thirtytwo = NULL;
PyObject *n = NULL;
unsigned long *key = NULL;
unsigned long keymax; /* # of allocated slots in key */
unsigned long keyused; /* # of used slots in key */
int err;
PyObject *result = NULL; /* guilty until proved innocent */
PyObject *masklower = NULL;
PyObject *thirtytwo = NULL;
PyObject *n = NULL;
unsigned long *key = NULL;
unsigned long keymax; /* # of allocated slots in key */
unsigned long keyused; /* # of used slots in key */
int err;
PyObject *arg = NULL;
PyObject *arg = NULL;
if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
return NULL;
if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
return NULL;
if (arg == NULL || arg == Py_None) {
time_t now;
if (arg == NULL || arg == Py_None) {
time_t now;
time(&now);
init_genrand(self, (unsigned long)now);
Py_INCREF(Py_None);
return Py_None;
}
/* If the arg is an int or long, use its absolute value; else use
* the absolute value of its hash code.
*/
if (PyInt_Check(arg) || PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
if (n == NULL)
goto Done;
time(&now);
init_genrand(self, (unsigned long)now);
Py_INCREF(Py_None);
return Py_None;
}
/* If the arg is an int or long, use its absolute value; else use
* the absolute value of its hash code.
*/
if (PyInt_Check(arg) || PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
if (n == NULL)
goto Done;
/* Now split n into 32-bit chunks, from the right. Each piece is
* stored into key, which has a capacity of keymax chunks, of which
* keyused are filled. Alas, the repeated shifting makes this a
* quadratic-time algorithm; we'd really like to use
* _PyLong_AsByteArray here, but then we'd have to break into the
* long representation to figure out how big an array was needed
* in advance.
*/
keymax = 8; /* arbitrary; grows later if needed */
keyused = 0;
key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
if (key == NULL)
goto Done;
/* Now split n into 32-bit chunks, from the right. Each piece is
* stored into key, which has a capacity of keymax chunks, of which
* keyused are filled. Alas, the repeated shifting makes this a
* quadratic-time algorithm; we'd really like to use
* _PyLong_AsByteArray here, but then we'd have to break into the
* long representation to figure out how big an array was needed
* in advance.
*/
keymax = 8; /* arbitrary; grows later if needed */
keyused = 0;
key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
if (key == NULL)
goto Done;
masklower = PyLong_FromUnsignedLong(0xffffffffU);
if (masklower == NULL)
goto Done;
thirtytwo = PyInt_FromLong(32L);
if (thirtytwo == NULL)
goto Done;
while ((err=PyObject_IsTrue(n))) {
PyObject *newn;
PyObject *pychunk;
unsigned long chunk;
masklower = PyLong_FromUnsignedLong(0xffffffffU);
if (masklower == NULL)
goto Done;
thirtytwo = PyInt_FromLong(32L);
if (thirtytwo == NULL)
goto Done;
while ((err=PyObject_IsTrue(n))) {
PyObject *newn;
PyObject *pychunk;
unsigned long chunk;
if (err == -1)
goto Done;
pychunk = PyNumber_And(n, masklower);
if (pychunk == NULL)
goto Done;
chunk = PyLong_AsUnsignedLong(pychunk);
Py_DECREF(pychunk);
if (chunk == (unsigned long)-1 && PyErr_Occurred())
goto Done;
newn = PyNumber_Rshift(n, thirtytwo);
if (newn == NULL)
goto Done;
Py_DECREF(n);
n = newn;
if (keyused >= keymax) {
unsigned long bigger = keymax << 1;
if ((bigger >> 1) != keymax) {
PyErr_NoMemory();
goto Done;
}
key = (unsigned long *)PyMem_Realloc(key,
bigger * sizeof(*key));
if (key == NULL)
goto Done;
keymax = bigger;
}
assert(keyused < keymax);
key[keyused++] = chunk;
}
if (err == -1)
goto Done;
pychunk = PyNumber_And(n, masklower);
if (pychunk == NULL)
goto Done;
chunk = PyLong_AsUnsignedLong(pychunk);
Py_DECREF(pychunk);
if (chunk == (unsigned long)-1 && PyErr_Occurred())
goto Done;
newn = PyNumber_Rshift(n, thirtytwo);
if (newn == NULL)
goto Done;
Py_DECREF(n);
n = newn;
if (keyused >= keymax) {
unsigned long bigger = keymax << 1;
if ((bigger >> 1) != keymax) {
PyErr_NoMemory();
goto Done;
}
key = (unsigned long *)PyMem_Realloc(key,
bigger * sizeof(*key));
if (key == NULL)
goto Done;
keymax = bigger;
}
assert(keyused < keymax);
key[keyused++] = chunk;
}
if (keyused == 0)
key[keyused++] = 0UL;
result = init_by_array(self, key, keyused);
if (keyused == 0)
key[keyused++] = 0UL;
result = init_by_array(self, key, keyused);
Done:
Py_XDECREF(masklower);
Py_XDECREF(thirtytwo);
Py_XDECREF(n);
PyMem_Free(key);
return result;
Py_XDECREF(masklower);
Py_XDECREF(thirtytwo);
Py_XDECREF(n);
PyMem_Free(key);
return result;
}
static PyObject *
random_getstate(RandomObject *self)
{
PyObject *state;
PyObject *element;
int i;
PyObject *state;
PyObject *element;
int i;
state = PyTuple_New(N+1);
if (state == NULL)
return NULL;
for (i=0; i<N ; i++) {
element = PyLong_FromUnsignedLong(self->state[i]);
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
}
element = PyLong_FromLong((long)(self->index));
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
return state;
state = PyTuple_New(N+1);
if (state == NULL)
return NULL;
for (i=0; i<N ; i++) {
element = PyLong_FromUnsignedLong(self->state[i]);
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
}
element = PyLong_FromLong((long)(self->index));
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
return state;
Fail:
Py_DECREF(state);
return NULL;
Py_DECREF(state);
return NULL;
}
static PyObject *
random_setstate(RandomObject *self, PyObject *state)
{
int i;
unsigned long element;
long index;
int i;
unsigned long element;
long index;
if (!PyTuple_Check(state)) {
PyErr_SetString(PyExc_TypeError,
"state vector must be a tuple");
return NULL;
}
if (PyTuple_Size(state) != N+1) {
PyErr_SetString(PyExc_ValueError,
"state vector is the wrong size");
return NULL;
}
if (!PyTuple_Check(state)) {
PyErr_SetString(PyExc_TypeError,
"state vector must be a tuple");
return NULL;
}
if (PyTuple_Size(state) != N+1) {
PyErr_SetString(PyExc_ValueError,
"state vector is the wrong size");
return NULL;
}
for (i=0; i<N ; i++) {
element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
if (element == (unsigned long)-1 && PyErr_Occurred())
return NULL;
self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
}
for (i=0; i<N ; i++) {
element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
if (element == (unsigned long)-1 && PyErr_Occurred())
return NULL;
self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
}
index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
if (index == -1 && PyErr_Occurred())
return NULL;
self->index = (int)index;
index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
if (index == -1 && PyErr_Occurred())
return NULL;
self->index = (int)index;
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
}
/*
@ -389,7 +389,7 @@ each element at position i. Successive calls are then guaranteed to
have changing (growing) values as well as shuffled positions.
Finally, the self->index value is set to N so that the generator itself
kicks in on the next call to random(). This assures that all results
kicks in on the next call to random(). This assures that all results
have been through the generator and do not just reflect alterations to
the underlying state.
*/
@ -397,169 +397,169 @@ the underlying state.
static PyObject *
random_jumpahead(RandomObject *self, PyObject *n)
{
long i, j;
PyObject *iobj;
PyObject *remobj;
unsigned long *mt, tmp;
long i, j;
PyObject *iobj;
PyObject *remobj;
unsigned long *mt, tmp;
if (!PyInt_Check(n) && !PyLong_Check(n)) {
PyErr_Format(PyExc_TypeError, "jumpahead requires an "
"integer, not '%s'",
Py_TYPE(n)->tp_name);
return NULL;
}
if (!PyInt_Check(n) && !PyLong_Check(n)) {
PyErr_Format(PyExc_TypeError, "jumpahead requires an "
"integer, not '%s'",
Py_TYPE(n)->tp_name);
return NULL;
}
mt = self->state;
for (i = N-1; i > 1; i--) {
iobj = PyInt_FromLong(i);
if (iobj == NULL)
return NULL;
remobj = PyNumber_Remainder(n, iobj);
Py_DECREF(iobj);
if (remobj == NULL)
return NULL;
j = PyInt_AsLong(remobj);
Py_DECREF(remobj);
if (j == -1L && PyErr_Occurred())
return NULL;
tmp = mt[i];
mt[i] = mt[j];
mt[j] = tmp;
}
mt = self->state;
for (i = N-1; i > 1; i--) {
iobj = PyInt_FromLong(i);
if (iobj == NULL)
return NULL;
remobj = PyNumber_Remainder(n, iobj);
Py_DECREF(iobj);
if (remobj == NULL)
return NULL;
j = PyInt_AsLong(remobj);
Py_DECREF(remobj);
if (j == -1L && PyErr_Occurred())
return NULL;
tmp = mt[i];
mt[i] = mt[j];
mt[j] = tmp;
}
for (i = 0; i < N; i++)
mt[i] += i+1;
for (i = 0; i < N; i++)
mt[i] += i+1;
self->index = N;
Py_INCREF(Py_None);
return Py_None;
self->index = N;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
random_getrandbits(RandomObject *self, PyObject *args)
{
int k, i, bytes;
unsigned long r;
unsigned char *bytearray;
PyObject *result;
int k, i, bytes;
unsigned long r;
unsigned char *bytearray;
PyObject *result;
if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
return NULL;
if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
return NULL;
if (k <= 0) {
PyErr_SetString(PyExc_ValueError,
"number of bits must be greater than zero");
return NULL;
}
if (k <= 0) {
PyErr_SetString(PyExc_ValueError,
"number of bits must be greater than zero");
return NULL;
}
bytes = ((k - 1) / 32 + 1) * 4;
bytearray = (unsigned char *)PyMem_Malloc(bytes);
if (bytearray == NULL) {
PyErr_NoMemory();
return NULL;
}
bytes = ((k - 1) / 32 + 1) * 4;
bytearray = (unsigned char *)PyMem_Malloc(bytes);
if (bytearray == NULL) {
PyErr_NoMemory();
return NULL;
}
/* Fill-out whole words, byte-by-byte to avoid endianness issues */
for (i=0 ; i<bytes ; i+=4, k-=32) {
r = genrand_int32(self);
if (k < 32)
r >>= (32 - k);
bytearray[i+0] = (unsigned char)r;
bytearray[i+1] = (unsigned char)(r >> 8);
bytearray[i+2] = (unsigned char)(r >> 16);
bytearray[i+3] = (unsigned char)(r >> 24);
}
/* Fill-out whole words, byte-by-byte to avoid endianness issues */
for (i=0 ; i<bytes ; i+=4, k-=32) {
r = genrand_int32(self);
if (k < 32)
r >>= (32 - k);
bytearray[i+0] = (unsigned char)r;
bytearray[i+1] = (unsigned char)(r >> 8);
bytearray[i+2] = (unsigned char)(r >> 16);
bytearray[i+3] = (unsigned char)(r >> 24);
}
/* little endian order to match bytearray assignment order */
result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
PyMem_Free(bytearray);
return result;
/* little endian order to match bytearray assignment order */
result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
PyMem_Free(bytearray);
return result;
}
static PyObject *
random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
RandomObject *self;
PyObject *tmp;
RandomObject *self;
PyObject *tmp;
if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
return NULL;
if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
return NULL;
self = (RandomObject *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
tmp = random_seed(self, args);
if (tmp == NULL) {
Py_DECREF(self);
return NULL;
}
Py_DECREF(tmp);
return (PyObject *)self;
self = (RandomObject *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
tmp = random_seed(self, args);
if (tmp == NULL) {
Py_DECREF(self);
return NULL;
}
Py_DECREF(tmp);
return (PyObject *)self;
}
static PyMethodDef random_methods[] = {
{"random", (PyCFunction)random_random, METH_NOARGS,
PyDoc_STR("random() -> x in the interval [0, 1).")},
{"seed", (PyCFunction)random_seed, METH_VARARGS,
PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
{"getstate", (PyCFunction)random_getstate, METH_NOARGS,
PyDoc_STR("getstate() -> tuple containing the current state.")},
{"setstate", (PyCFunction)random_setstate, METH_O,
PyDoc_STR("setstate(state) -> None. Restores generator state.")},
{"jumpahead", (PyCFunction)random_jumpahead, METH_O,
PyDoc_STR("jumpahead(int) -> None. Create new state from "
"existing state and integer.")},
{"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
"k random bits.")},
{NULL, NULL} /* sentinel */
{"random", (PyCFunction)random_random, METH_NOARGS,
PyDoc_STR("random() -> x in the interval [0, 1).")},
{"seed", (PyCFunction)random_seed, METH_VARARGS,
PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
{"getstate", (PyCFunction)random_getstate, METH_NOARGS,
PyDoc_STR("getstate() -> tuple containing the current state.")},
{"setstate", (PyCFunction)random_setstate, METH_O,
PyDoc_STR("setstate(state) -> None. Restores generator state.")},
{"jumpahead", (PyCFunction)random_jumpahead, METH_O,
PyDoc_STR("jumpahead(int) -> None. Create new state from "
"existing state and integer.")},
{"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
"k random bits.")},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(random_doc,
"Random() -> create a random number generator with its own internal state.");
static PyTypeObject Random_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_random.Random", /*tp_name*/
sizeof(RandomObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*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*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
random_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
random_methods, /*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*/
random_new, /*tp_new*/
_PyObject_Del, /*tp_free*/
0, /*tp_is_gc*/
PyVarObject_HEAD_INIT(NULL, 0)
"_random.Random", /*tp_name*/
sizeof(RandomObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*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*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
random_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
random_methods, /*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*/
random_new, /*tp_new*/
_PyObject_Del, /*tp_free*/
0, /*tp_is_gc*/
};
PyDoc_STRVAR(module_doc,
@ -568,13 +568,13 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
init_random(void)
{
PyObject *m;
PyObject *m;
if (PyType_Ready(&Random_Type) < 0)
return;
m = Py_InitModule3("_random", NULL, module_doc);
if (m == NULL)
return;
Py_INCREF(&Random_Type);
PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
if (PyType_Ready(&Random_Type) < 0)
return;
m = Py_InitModule3("_random", NULL, module_doc);
if (m == NULL)
return;
Py_INCREF(&Random_Type);
PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE 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:
@ -13,7 +13,7 @@
* 3. Neither the name of the 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 PROJECT 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
@ -55,20 +55,20 @@
#define getaddrinfo fake_getaddrinfo
#endif /* EAI_ADDRFAMILY */
#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
#define EAI_FAMILY 5 /* ai_family not supported */
#define EAI_MEMORY 6 /* memory allocation failure */
#define EAI_NODATA 7 /* no address associated with hostname */
#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#define EAI_SYSTEM 11 /* system error returned in errno */
#define EAI_BADHINTS 12
#define EAI_PROTOCOL 13
#define EAI_MAX 14
#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
#define EAI_FAMILY 5 /* ai_family not supported */
#define EAI_MEMORY 6 /* memory allocation failure */
#define EAI_NODATA 7 /* no address associated with hostname */
#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#define EAI_SYSTEM 11 /* system error returned in errno */
#define EAI_BADHINTS 12
#define EAI_PROTOCOL 13
#define EAI_MAX 14
/*
* Flag values for getaddrinfo()
@ -85,18 +85,18 @@
#undef AI_DEFAULT
#endif /* AI_PASSIVE */
#define AI_PASSIVE 0x00000001 /* get address to use bind() */
#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
#define AI_PASSIVE 0x00000001 /* get address to use bind() */
#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
/* valid flags for addrinfo */
#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
/* special recommended flags for getipnodebyname */
#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
#endif /* !HAVE_GETADDRINFO */
@ -106,33 +106,33 @@
* Constants for getnameinfo()
*/
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#endif /* !NI_MAXHOST */
/*
* Flag values for getnameinfo()
*/
#ifndef NI_NOFQDN
#define NI_NOFQDN 0x00000001
#define NI_NUMERICHOST 0x00000002
#define NI_NAMEREQD 0x00000004
#define NI_NUMERICSERV 0x00000008
#define NI_DGRAM 0x00000010
#define NI_NOFQDN 0x00000001
#define NI_NUMERICHOST 0x00000002
#define NI_NAMEREQD 0x00000004
#define NI_NUMERICSERV 0x00000008
#define NI_DGRAM 0x00000010
#endif /* !NI_NOFQDN */
#endif /* !HAVE_GETNAMEINFO */
#ifndef HAVE_ADDRINFO
struct addrinfo {
int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for hostname */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for hostname */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
};
#endif /* !HAVE_ADDRINFO */
@ -140,30 +140,30 @@ struct addrinfo {
/*
* RFC 2553: protocol-independent placeholder for socket addresses
*/
#define _SS_MAXSIZE 128
#define _SS_MAXSIZE 128
#ifdef HAVE_LONG_LONG
#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
#else
#define _SS_ALIGNSIZE (sizeof(double))
#define _SS_ALIGNSIZE (sizeof(double))
#endif /* HAVE_LONG_LONG */
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
_SS_PAD1SIZE - _SS_ALIGNSIZE)
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
_SS_PAD1SIZE - _SS_ALIGNSIZE)
struct sockaddr_storage {
#ifdef HAVE_SOCKADDR_SA_LEN
unsigned char ss_len; /* address length */
unsigned char ss_family; /* address family */
unsigned char ss_len; /* address length */
unsigned char ss_family; /* address family */
#else
unsigned short ss_family; /* address family */
unsigned short ss_family; /* address family */
#endif /* HAVE_SOCKADDR_SA_LEN */
char __ss_pad1[_SS_PAD1SIZE];
char __ss_pad1[_SS_PAD1SIZE];
#ifdef HAVE_LONG_LONG
PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
#else
double __ss_align; /* force desired structure storage alignment */
double __ss_align; /* force desired structure storage alignment */
#endif /* HAVE_LONG_LONG */
char __ss_pad2[_SS_PAD2SIZE];
char __ss_pad2[_SS_PAD2SIZE];
};
#endif /* !HAVE_SOCKADDR_STORAGE */

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more